repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
googlesamples/android-testdpc
app/src/main/java/com/afwsamples/testdpc/policy/systemupdatepolicy/SystemUpdatePolicyFragment.java
15547
/* * Copyright (C) 2015 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.afwsamples.testdpc.policy.systemupdatepolicy; import android.annotation.TargetApi; import android.app.DatePickerDialog; import android.app.Fragment; import android.app.TimePickerDialog; import android.app.admin.DevicePolicyManager; import android.app.admin.FreezePeriod; import android.app.admin.SystemUpdatePolicy; import android.content.Context; import android.os.Build.VERSION_CODES; import android.os.Bundle; import androidx.annotation.RequiresApi; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioGroup; import android.widget.Toast; import com.afwsamples.testdpc.DeviceAdminReceiver; import com.afwsamples.testdpc.R; import com.afwsamples.testdpc.common.Util; import java.time.LocalDate; import java.time.MonthDay; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; /** * This fragment provides functionalities related to managed system update that are available in a * device owner. * These includes * 1) {@link DevicePolicyManager#setSystemUpdatePolicy} * 2) {@link DevicePolicyManager#getSystemUpdatePolicy} * 3) {@link SystemUpdatePolicy} */ @TargetApi(VERSION_CODES.M) public class SystemUpdatePolicyFragment extends Fragment implements View.OnClickListener, RadioGroup.OnCheckedChangeListener { @RequiresApi(api = VERSION_CODES.O) static class Period { MonthDay mStart; MonthDay mEnd; public Period() { } public Period(MonthDay start, MonthDay end) { mStart = start; mEnd = end; } public void set(LocalDate startDate, LocalDate endDate) { mStart = MonthDay.of(startDate.getMonth(), startDate.getDayOfMonth()); mEnd = MonthDay.of(endDate.getMonth(), endDate.getDayOfMonth()); } @Override public String toString() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd"); return mStart.format(formatter) + " - " + mEnd.format(formatter); } public LocalDate getStartDate() { return mStart.atYear(LocalDate.now().getYear()); } public LocalDate getEndDate() { return mEnd.atYear(LocalDate.now().getYear()); } @TargetApi(VERSION_CODES.P) public FreezePeriod toFreezePeriod() { return new FreezePeriod(mStart, mEnd); } } private EditText mCurrentSystemUpdatePolicy; private RadioGroup mSystemUpdatePolicySelection; private LinearLayout mMaintenanceWindowDetails; private Button mSetMaintenanceWindowStart; private Button mSetMaintenanceWindowEnd; private LinearLayout mFreezePeriodPanel; private ListView mFreezePeriodList; private DevicePolicyManager mDpm; private int mMaintenanceStart; private int mMaintenanceEnd; private ArrayList<Period> mFreezePeriods = new ArrayList<>(); private FreezePeriodAdapter mFreezePeriodAdapter; @Override public void onResume() { super.onResume(); getActivity().getActionBar().setTitle(R.string.system_update_policy); reloadSystemUpdatePolicy(); } class FreezePeriodAdapter extends ArrayAdapter<Period> { public ArrayList<Period> mData; public FreezePeriodAdapter(Context context, ArrayList<Period> periods) { super(context, 0, periods); this.mData = periods; } @RequiresApi(api = VERSION_CODES.O) @Override public View getView(int position, View convertView, ViewGroup parent) { Period currentPeriod = getItem(position); if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.freeze_period_row, parent, false); } Button textView = convertView.findViewById(R.id.string_period); textView.setText(currentPeriod.toString()); textView.setTag(mData.get(position)); textView.setOnClickListener(view -> { final Period period = (Period) view.getTag(); promptToSetFreezePeriod((LocalDate startDate, LocalDate endDate) -> { period.set(startDate, endDate); mFreezePeriodAdapter.notifyDataSetChanged(); }, period.getStartDate(), period.getEndDate()); }); View deleteButton = convertView.findViewById(R.id.delete_period); deleteButton.setTag(mData.get(position)); deleteButton.setOnClickListener(view -> { Period period = (Period) view.getTag(); mData.remove(period); FreezePeriodAdapter.this.notifyDataSetChanged(); }); return convertView; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDpm = (DevicePolicyManager) getActivity().getSystemService(Context.DEVICE_POLICY_SERVICE); } @Override public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) { View view = layoutInflater.inflate(R.layout.system_update_policy, null); mCurrentSystemUpdatePolicy = view.findViewById(R.id.system_update_policy_current); mSystemUpdatePolicySelection = view.findViewById(R.id.system_update_policy_selection); mMaintenanceWindowDetails = view.findViewById(R.id.system_update_policy_windowed_details); mSetMaintenanceWindowStart = view.findViewById(R.id.system_update_policy_window_start); mSetMaintenanceWindowEnd = view.findViewById(R.id.system_update_policy_window_end); mFreezePeriodPanel = view.findViewById(R.id.system_update_policy_blackout_periods); mFreezePeriodList = view.findViewById(R.id.system_update_policy_blackout_period_list); mFreezePeriodAdapter = new FreezePeriodAdapter(getContext(), mFreezePeriods); mFreezePeriodList.setAdapter(mFreezePeriodAdapter); mSetMaintenanceWindowStart.setOnClickListener(this); mSetMaintenanceWindowEnd.setOnClickListener(this); view.findViewById(R.id.system_update_policy_set).setOnClickListener(this); view.findViewById(R.id.system_update_policy_btn_add_period).setOnClickListener(this); mSystemUpdatePolicySelection.setOnCheckedChangeListener(this); mFreezePeriodPanel.setVisibility( Util.SDK_INT >= VERSION_CODES.P ?View.VISIBLE : View.GONE); return view; } private void selectTime(final boolean isWindowStart) { int defaultMinutes = isWindowStart ? mMaintenanceStart : mMaintenanceEnd; TimePickerDialog timePicker = new TimePickerDialog(getActivity(), (picker, hour, minutes) -> { if (isWindowStart) { mMaintenanceStart = hour * 60 + minutes; } else { mMaintenanceEnd = hour * 60 + minutes; } updateMaintenanceWindowDisplay(); }, defaultMinutes / 60, defaultMinutes % 60, true); timePicker.show(); } @RequiresApi(api = VERSION_CODES.O) @Override public void onClick(View v) { switch (v.getId()) { case R.id.system_update_policy_window_start: selectTime(true); break; case R.id.system_update_policy_window_end: selectTime(false); break; case R.id.system_update_policy_set: if (setSystemUpdatePolicy()) { reloadSystemUpdatePolicy(); } break; case R.id.system_update_policy_btn_add_period: promptToSetFreezePeriod((LocalDate startDate, LocalDate endDate) -> { Period period = new Period(); period.set(startDate, endDate); mFreezePeriods.add(period); mFreezePeriodAdapter.notifyDataSetChanged(); }, LocalDate.now(), LocalDate.now()); } } interface FreezePeriodPickResult { void onResult(LocalDate startDate, LocalDate endDate); } interface DatePickResult { void onResult(LocalDate pickedDate); } @RequiresApi(api = VERSION_CODES.O) private void showDatePicker(LocalDate hint, int titleResId, DatePickResult resultCallback) { DatePickerDialog picker = new DatePickerDialog(getActivity(), (pickerObj, year, month, day) -> { final LocalDate pickedDate = LocalDate.of(year, month + 1, day); resultCallback.onResult(pickedDate); }, hint.getYear(), hint.getMonth().getValue() - 1, hint.getDayOfMonth()); picker.setTitle(getString(titleResId)); picker.show(); } @RequiresApi(api = VERSION_CODES.O) private void promptToSetFreezePeriod(FreezePeriodPickResult callback, final LocalDate startDate, final LocalDate endDate) { showDatePicker(startDate, R.string.system_update_policy_pick_start_free_period_title, pickedStartDate -> { LocalDate proposedEndDate = endDate; if (proposedEndDate.compareTo(pickedStartDate) < 0) { proposedEndDate = pickedStartDate; } showDatePicker(proposedEndDate, R.string.system_update_policy_pick_end_free_period_title, pickedEndDate -> callback.onResult(pickedStartDate, pickedEndDate)); }); } @TargetApi(VERSION_CODES.P) private boolean setSystemUpdatePolicy() { SystemUpdatePolicy newPolicy; switch (mSystemUpdatePolicySelection.getCheckedRadioButtonId()) { case R.id.system_update_policy_automatic: newPolicy = SystemUpdatePolicy.createAutomaticInstallPolicy(); break; case R.id.system_update_policy_Windowed: newPolicy = SystemUpdatePolicy.createWindowedInstallPolicy( mMaintenanceStart, mMaintenanceEnd); break; case R.id.system_update_policy_postpone: newPolicy = SystemUpdatePolicy.createPostponeInstallPolicy(); break; case R.id.system_update_policy_none: default: newPolicy = null; } try { if (Util.SDK_INT >= VERSION_CODES.P && newPolicy != null && mFreezePeriods.size() != 0) { final List<FreezePeriod> periods = new ArrayList<>(mFreezePeriods.size()); for (Period p : mFreezePeriods) { periods.add(p.toFreezePeriod()); } newPolicy.setFreezePeriods(periods); } mDpm.setSystemUpdatePolicy(DeviceAdminReceiver.getComponentName(getActivity()), newPolicy); Toast.makeText(getContext(), "Policy set successfully", Toast.LENGTH_LONG).show(); return true; } catch (IllegalArgumentException e) { Toast.makeText(getContext(), "Failed to set system update policy: " + e.getMessage(), Toast.LENGTH_LONG).show(); } return false; } private String formatMinutes(int minutes) { return String.format("%02d:%02d", minutes / 60, minutes % 60); } private void updateMaintenanceWindowDisplay() { mSetMaintenanceWindowStart.setText(formatMinutes(mMaintenanceStart)); mSetMaintenanceWindowEnd.setText(formatMinutes(mMaintenanceEnd)); } @TargetApi(VERSION_CODES.P) private void reloadSystemUpdatePolicy() { SystemUpdatePolicy policy = mDpm.getSystemUpdatePolicy(); String policyDescription = "Unknown"; if (policy == null) { policyDescription = "None"; mSystemUpdatePolicySelection.check(R.id.system_update_policy_none); mMaintenanceWindowDetails.setVisibility(View.INVISIBLE); mFreezePeriodPanel.setVisibility(View.GONE); } else { switch (policy.getPolicyType()) { case SystemUpdatePolicy.TYPE_INSTALL_AUTOMATIC: policyDescription = "Automatic"; mSystemUpdatePolicySelection.check(R.id.system_update_policy_automatic); mMaintenanceWindowDetails.setVisibility(View.INVISIBLE); break; case SystemUpdatePolicy.TYPE_INSTALL_WINDOWED: { mMaintenanceStart = policy.getInstallWindowStart(); mMaintenanceEnd = policy.getInstallWindowEnd(); policyDescription = String.format("Windowed: %s-%s", formatMinutes(mMaintenanceStart), formatMinutes(mMaintenanceEnd)); updateMaintenanceWindowDisplay(); mSystemUpdatePolicySelection.check(R.id.system_update_policy_Windowed); mMaintenanceWindowDetails.setVisibility(View.VISIBLE); break; } case SystemUpdatePolicy.TYPE_POSTPONE: policyDescription = "Postpone"; mSystemUpdatePolicySelection.check(R.id.system_update_policy_postpone); mMaintenanceWindowDetails.setVisibility(View.INVISIBLE); break; } if (Util.SDK_INT >= VERSION_CODES.P) { List<FreezePeriod> freezePeriods = policy.getFreezePeriods(); mFreezePeriods.clear(); for (FreezePeriod period : freezePeriods) { Period p = new Period(period.getStart(), period.getEnd()); mFreezePeriods.add(p); } mFreezePeriodAdapter.notifyDataSetChanged(); mFreezePeriodPanel.setVisibility(View.VISIBLE); } } mCurrentSystemUpdatePolicy.setText(policyDescription); } @Override public void onCheckedChanged(RadioGroup view, int checkedId) { if (checkedId == R.id.system_update_policy_Windowed) { updateMaintenanceWindowDisplay(); mMaintenanceWindowDetails.setVisibility(View.VISIBLE); } else { mMaintenanceWindowDetails.setVisibility(View.INVISIBLE); } if (checkedId == R.id.system_update_policy_none || Util.SDK_INT < VERSION_CODES.P) { mFreezePeriodPanel.setVisibility(View.GONE); } else { mFreezePeriodPanel.setVisibility(View.VISIBLE); } } }
apache-2.0
JavaUAM2016/PracticasOCA
Practica3/luzmx/JavaApp/src/mx/edu/uam/practica3/controles/ControlTelevision.java
3150
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mx.edu.uam.practica3.controles; import mx.edu.uam.practica3.electroDomesticos.Television; /** * * @author invited */ public class ControlTelevision { public void enciendeTv(Television tv){ if(tv.isEncendido()){ System.out.println("La televisión ya se encuentra encedida"); }else{ tv.setEncendido(true); System.out.println("Se cambia el estado a ON"); } } public void apagaTv(Television tv){ if(tv.isEncendido()){ tv.setEncendido(false); System.out.println("Se cambia el estado a OFF"); }else{ System.out.println("No se puede apagar la televisión pues se encuentra apagada"); } } public void subeVolumen(Television tv){ if(tv.isEncendido()){ if(tv.getVolMaximo() == tv.getVolActual()){ System.out.println("El volumen se encuentra al Maximo posible"); }else{ tv.setVolActual(tv.getVolActual()+1); System.out.println("El volumen Actual se aumentó y es : "+ tv.getVolActual()); } }else{ System.out.println("La televisión se encuentra apagada"); } } public void bajaVolumen(Television tv){ if(tv.isEncendido()){ if(tv.getVolActual() == 0){ System.out.println("El volumen no se puede bajar más... Está en el mínimo"); }else{ tv.setVolActual(tv.getVolActual()-1); } }else{ System.out.println("La televisión se encuentra apagada"); } } public void subeCanal(Television tv){ if(tv.isEncendido()){ if(tv.getUltimoCanal() == tv.getCanalActual()){ System.out.println("No puede subir canal ... Se encuentra en el Máximo Canal"); }else{ tv.setCanalActual(tv.getCanalActual()+1); System.out.println("El canal actual es: "+ tv.getCanalActual()); } }else{ System.out.println("La televisión se encuentra apagada"); } } public void bajaCanal(Television tv){ if(tv.isEncendido()){ if(tv.getCanalActual() == 1){ System.out.println("No puede bajar canal ... Se encuentra en el canal mìnimo"); }else{ tv.setCanalActual(tv.getCanalActual()-1); System.out.println("El canal actual es: "+ tv.getCanalActual()); } }else{ System.out.println("La televisión se encuentra apagada"); } } public void cambiaCanal(Television tv, int canal){ if(tv.isEncendido()){ tv.setCanalActual(canal); System.out.println("El canal actual es: "+ tv.getCanalActual()); }else{ System.out.println("La televisión se encuentra apagada"); } } }
apache-2.0
ifnul/ums-backend
is-lnu-converter/src/test/java/org/lnu/is/converter/specoffer/type/SpecOfferTypeConverterTest.java
3632
package org.lnu.is.converter.specoffer.type; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.lnu.is.domain.specoffer.SpecOfferType; import org.lnu.is.domain.timeperiod.TimePeriod; import org.lnu.is.resource.specoffer.type.SpecOfferTypeResource; public class SpecOfferTypeConverterTest { private SpecOfferTypeConverter unit = new SpecOfferTypeConverter(); @Test public void testConvert() throws Exception { // Given String name = "first blood"; String abbrName = "fb"; Long id = 1L; Long timePeriodId = 2L; TimePeriod timePeriod = new TimePeriod(); timePeriod.setId(timePeriodId); SpecOfferType source = new SpecOfferType(); source.setName(name); source.setAbbrName(abbrName); source.setId(id); source.setTimePeriod(timePeriod); SpecOfferTypeResource expected = new SpecOfferTypeResource(); expected.setName(name); expected.setAbbrName(abbrName); expected.setTimePeriodId(timePeriodId); expected.setId(id); // When SpecOfferTypeResource actual = unit.convert(source); // Then assertEquals(expected, actual); } @Test public void testConvertWithNoRelations() throws Exception { // Given String name = "first blood"; String abbrName = "fb"; Long id = 1L; SpecOfferType source = new SpecOfferType(); source.setName(name); source.setAbbrName(abbrName); source.setId(id); SpecOfferTypeResource expected = new SpecOfferTypeResource(); expected.setName(name); expected.setAbbrName(abbrName); expected.setId(id); // When SpecOfferTypeResource actual = unit.convert(source); // Then assertEquals(expected, actual); } @Test public void testConvertAll() throws Exception { // Given String name = "first blood"; String abbrName = "fb"; Long id = 1L; Long timePeriodId = 2L; TimePeriod timePeriod = new TimePeriod(); timePeriod.setId(timePeriodId); SpecOfferType source = new SpecOfferType(); source.setName(name); source.setAbbrName(abbrName); source.setId(id); source.setTimePeriod(timePeriod); SpecOfferTypeResource expected = new SpecOfferTypeResource(); expected.setName(name); expected.setAbbrName(abbrName); expected.setTimePeriodId(timePeriodId); expected.setId(id); List<SpecOfferType> sources = Arrays.asList(source); List<SpecOfferTypeResource> expecteds = Arrays.asList(expected); // Where List<SpecOfferTypeResource> actuals = unit.convertAll(sources); //Then assertEquals(expecteds, actuals); } @Test public void testConvertAllWithNoRelations() throws Exception { // Given String name = "first blood"; String abbrName = "fb"; Long id = 1L; SpecOfferType source = new SpecOfferType(); source.setName(name); source.setAbbrName(abbrName); source.setId(id); SpecOfferTypeResource expected = new SpecOfferTypeResource(); expected.setName(name); expected.setAbbrName(abbrName); expected.setId(id); String name1 = "first blood1"; String abbrName1 = "fb1"; Long id1 = 2L; SpecOfferType source1 = new SpecOfferType(); source1.setName(name1); source1.setAbbrName(abbrName1); source1.setId(id1); SpecOfferTypeResource expected1 = new SpecOfferTypeResource(); expected1.setName(name1); expected1.setAbbrName(abbrName1); expected1.setId(id1); List<SpecOfferType> sources = Arrays.asList(source,source1); List<SpecOfferTypeResource> expecteds = Arrays.asList(expected,expected1); // Where List<SpecOfferTypeResource> actuals = unit.convertAll(sources); //Then assertEquals(expecteds, actuals); } }
apache-2.0
martyanova/java_pft
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/model/Persons.java
1043
package ru.stqa.pft.addressbook.model; import com.google.common.collect.ForwardingSet; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created by Саша on 13.12.2016. */ public class Persons extends ForwardingSet<PersonData> { private Set<PersonData> delegate; public Persons(Persons persons) { this.delegate = new HashSet<PersonData>(persons.delegate); } public Persons() { this.delegate = new HashSet<PersonData>(); } public Persons(Collection<PersonData> persons) { this.delegate = new HashSet<PersonData>(persons); } @Override protected Set<PersonData> delegate() { return delegate; } public Persons withAdded (PersonData person){ Persons persons = new Persons(this); persons.add(person); return persons; } public Persons without (PersonData person){ Persons persons = new Persons(this); persons.remove(person); return persons; } }
apache-2.0
lakshmiDRIP/DRIP
src/main/java/org/drip/service/template/OTCInstrumentBuilder.java
33137
package org.drip.service.template; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2017 Lakshmi Krishnamurthy * Copyright (C) 2016 Lakshmi Krishnamurthy * Copyright (C) 2015 Lakshmi Krishnamurthy * * This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model * libraries targeting analysts and developers * https://lakshmidrip.github.io/DRIP/ * * DRIP is composed of four main libraries: * * - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/ * - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/ * - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/ * - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/ * * - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options, * Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA * Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV * Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM * Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics. * * - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy * Incorporator, Holdings Constraint, and Transaction Costs. * * - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality. * * - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning. * * 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. */ /** * OTCInstrumentBuilder contains static Helper API to facilitate Construction of OTC Instruments. * * @author Lakshmi Krishnamurthy */ public class OTCInstrumentBuilder { /** * Construct an OTC Funding Deposit Instrument from the Spot Date and the Maturity Tenor * * @param dtSpot The Spot Date * @param strCurrency Currency * @param strMaturityTenor The Maturity Tenor * * @return Funding Deposit Instrument Instance from the Spot Date and the corresponding Maturity Tenor */ public static final org.drip.product.rates.SingleStreamComponent FundingDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strMaturityTenor) { if (null == dtSpot || null == strCurrency || strCurrency.isEmpty() || null == strMaturityTenor || strMaturityTenor.isEmpty()) return null; org.drip.market.otc.FixedFloatSwapConvention ffsc = org.drip.market.otc.IBORFixedFloatContainer.ConventionFromJurisdiction (strCurrency, "ALL", strMaturityTenor, "MAIN"); if (null == ffsc) return null; org.drip.state.identifier.ForwardLabel forwardLabel = ffsc.floatStreamConvention().floaterIndex(); org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCurrency); try { java.lang.String strFloaterTenor = forwardLabel.tenor(); org.drip.analytics.date.JulianDate dtMaturity = strMaturityTenor.contains ("D") ? new org.drip.analytics.date.JulianDate (org.drip.analytics.daycount.Convention.AddBusinessDays (dtEffective.julian(), org.drip.analytics.support.Helper.TenorToDays (strMaturityTenor), strCurrency)) : dtEffective.addTenorAndAdjust (strMaturityTenor, strCurrency); return new org.drip.product.rates.SingleStreamComponent ("DEPOSIT_" + strMaturityTenor, new org.drip.product.rates.Stream (org.drip.analytics.support.CompositePeriodBuilder.FloatingCompositeUnit (org.drip.analytics.support.CompositePeriodBuilder.EdgePair (dtEffective, dtMaturity), new org.drip.param.period.CompositePeriodSetting (org.drip.analytics.support.Helper.TenorToFreq (strFloaterTenor), strFloaterTenor, strCurrency, null, 1., null, null, null, null), new org.drip.param.period.ComposableFloatingUnitSetting (strFloaterTenor, org.drip.analytics.support.CompositePeriodBuilder.EDGE_DATE_SEQUENCE_SINGLE, null, org.drip.state.identifier.ForwardLabel.Create (strCurrency, strFloaterTenor), org.drip.analytics.support.CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE, 0.))), null); } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } /** * Construct an OTC Forward Deposit Instrument from Spot Date and the Maturity Tenor * * @param dtSpot The Spot Date * @param strMaturityTenor The Maturity Tenor * @param forwardLabel The Forward Label * * @return Forward Deposit Instrument Instance from the Spot Date and the corresponding Maturity Tenor */ public static final org.drip.product.rates.SingleStreamComponent ForwardRateDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strMaturityTenor, final org.drip.state.identifier.ForwardLabel forwardLabel) { if (null == dtSpot || null == forwardLabel) return null; java.lang.String strCalendar = forwardLabel.currency(); org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCalendar); return org.drip.product.creator.SingleStreamComponentBuilder.Deposit (dtEffective, dtEffective.addTenor (strMaturityTenor), forwardLabel); } /** * Construct an OTC Overnight Deposit Instrument from the Spot Date and the Maturity Tenor * * @param dtSpot The Spot Date * @param strCurrency Currency * @param strMaturityTenor The Maturity Tenor * * @return Overnight Deposit Instrument Instance from the Spot Date and the corresponding Maturity Tenor */ public static final org.drip.product.rates.SingleStreamComponent OvernightDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strMaturityTenor) { if (null == dtSpot) return null; org.drip.state.identifier.OvernightLabel overnightLabel = org.drip.state.identifier.OvernightLabel.Create (strCurrency); if (null == overnightLabel) return null; org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCurrency); return null == dtEffective ? null : org.drip.product.creator.SingleStreamComponentBuilder.Deposit (dtEffective, dtEffective.addTenorAndAdjust (strMaturityTenor, strCurrency),overnightLabel); } /** * Create a Standard FRA from the Spot Date, the Forward Label, and the Strike * * @param dtSpot Spot Date * @param forwardLabel The Forward Label * @param strMaturityTenor Maturity Tenor * @param dblStrike Futures Strike * * @return The Standard FRA Instance */ public static final org.drip.product.fra.FRAStandardComponent FRAStandard ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String strMaturityTenor, final double dblStrike) { return null == dtSpot || null == forwardLabel ? null : org.drip.product.creator.SingleStreamComponentBuilder.FRAStandard (dtSpot.addBusDays (0, forwardLabel.currency()).addTenor (strMaturityTenor), forwardLabel, dblStrike); } /** * Construct an OTC Standard Fix Float Swap using the specified Input Parameters * * @param dtSpot The Spot Date * @param strCurrency The OTC Currency * @param strLocation Location * @param strMaturityTenor Maturity Tenor * @param strIndex Index * @param dblCoupon Coupon * * @return The OTC Standard Fix Float Swap constructed using the specified Input Parameters */ public static final org.drip.product.rates.FixFloatComponent FixFloatStandard ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strLocation, final java.lang.String strMaturityTenor, final java.lang.String strIndex, final double dblCoupon) { if (null == dtSpot) return null; org.drip.market.otc.FixedFloatSwapConvention ffsc = org.drip.market.otc.IBORFixedFloatContainer.ConventionFromJurisdiction (strCurrency, strLocation, strMaturityTenor, strIndex); return null == ffsc ? null : ffsc.createFixFloatComponent (dtSpot.addBusDays (0, strCurrency), strMaturityTenor, dblCoupon, 0., 1.); } /** * Construct a Standard Fix Float Swap Instances * * @param dtSpot The Spot Date * @param forwardLabel The Forward Label * @param strMaturityTenor Maturity Tenor * * @return A Standard Fix Float Swap Instances */ public static final org.drip.product.rates.FixFloatComponent FixFloatCustom ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String strMaturityTenor) { if (null == dtSpot || null == forwardLabel) return null; java.lang.String strCurrency = forwardLabel.currency(); java.lang.String strForwardTenor = forwardLabel.tenor(); int iTenorInMonths = new java.lang.Integer (strForwardTenor.split ("M")[0]); org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCurrency).addDays (2); org.drip.market.otc.FixedFloatSwapConvention ffsc = org.drip.market.otc.IBORFixedFloatContainer.ConventionFromJurisdiction (strCurrency, "ALL", strMaturityTenor, "MAIN"); if (null == ffsc) return null; try { org.drip.param.period.ComposableFloatingUnitSetting cfusFloating = new org.drip.param.period.ComposableFloatingUnitSetting (strForwardTenor, org.drip.analytics.support.CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR, null, forwardLabel, org.drip.analytics.support.CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE, 0.); org.drip.param.period.CompositePeriodSetting cpsFloating = new org.drip.param.period.CompositePeriodSetting (12 / iTenorInMonths, strForwardTenor, strCurrency, null, -1., null, null, null, null); org.drip.product.rates.Stream floatingStream = new org.drip.product.rates.Stream (org.drip.analytics.support.CompositePeriodBuilder.FloatingCompositeUnit (org.drip.analytics.support.CompositePeriodBuilder.RegularEdgeDates (dtEffective, strForwardTenor, strMaturityTenor, null), cpsFloating, cfusFloating)); org.drip.product.rates.Stream fixedStream = ffsc.fixedStreamConvention().createStream (dtEffective, strMaturityTenor, 0., 1.); org.drip.product.rates.FixFloatComponent ffc = new org.drip.product.rates.FixFloatComponent (fixedStream, floatingStream, null); ffc.setPrimaryCode ("FixFloat:" + strMaturityTenor); return ffc; } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } /** * Construct an Instance of OTC OIS Fix Float Swap * * @param dtSpot Spot Date * @param strCurrency Currency * @param strMaturityTenor The OIS Maturity Tenor * @param dblCoupon The Fixed Coupon Rate * @param bFund TRUE - Floater Based off of Fund * * @return Instance of OIS Fix Float Swap */ public static final org.drip.product.rates.FixFloatComponent OISFixFloat ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strMaturityTenor, final double dblCoupon, final boolean bFund) { if (null == dtSpot) return null; org.drip.market.otc.FixedFloatSwapConvention ffsc = bFund ? org.drip.market.otc.OvernightFixedFloatContainer.FundConventionFromJurisdiction (strCurrency) : org.drip.market.otc.OvernightFixedFloatContainer.IndexConventionFromJurisdiction (strCurrency, strMaturityTenor); return null == ffsc ? null : ffsc.createFixFloatComponent (dtSpot.addBusDays (0, strCurrency), strMaturityTenor, dblCoupon, 0., 1.); } /** * Construct an OTC Float-Float Swap Instance * * @param dtSpot Spot Date * @param strCurrency Currency * @param strDerivedTenor Tenor of the Derived Leg * @param strMaturityTenor Maturity Tenor of the Float-Float Swap * @param dblBasis The Float-Float Swap Basis * * @return The OTC Float-Float Swap Instance */ public static final org.drip.product.rates.FloatFloatComponent FloatFloat ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strDerivedTenor, final java.lang.String strMaturityTenor, final double dblBasis) { if (null == dtSpot) return null; org.drip.market.otc.FloatFloatSwapConvention ffsc = org.drip.market.otc.IBORFloatFloatContainer.ConventionFromJurisdiction (strCurrency); return null == ffsc ? null : ffsc.createFloatFloatComponent (dtSpot.addBusDays (0, strCurrency), strDerivedTenor, strMaturityTenor, dblBasis, 1.); } /** * Create an Instance of the OTC CDS. * * @param dtSpot The Spot Date * @param strMaturityTenor Maturity Tenor * @param dblCoupon Coupon * @param strCurrency Currency * @param strCredit Credit Curve * * @return The OTC CDS Instance */ public static final org.drip.product.definition.CreditDefaultSwap CDS ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strMaturityTenor, final double dblCoupon, final java.lang.String strCurrency, final java.lang.String strCredit) { if (null == dtSpot || null == strCurrency) return null; org.drip.analytics.date.JulianDate dtFirstCoupon = dtSpot.addBusDays (0, strCurrency).nextCreditIMM (3); return null == dtFirstCoupon ? null : org.drip.product.creator.CDSBuilder.CreateCDS (dtFirstCoupon.subtractTenor ("3M"), dtFirstCoupon.addTenor (strMaturityTenor), dblCoupon, strCurrency, "CAD".equalsIgnoreCase (strCurrency) || "EUR".equalsIgnoreCase (strCurrency) || "GBP".equalsIgnoreCase (strCurrency) || "HKD".equalsIgnoreCase (strCurrency) || "USD".equalsIgnoreCase (strCurrency) ? 0.40 : 0.25, strCredit, strCurrency, true); } /** * Create an OTC FX Forward Component * * @param dtSpot Spot Date * @param ccyPair Currency Pair * @param strMaturityTenor Maturity Tenor * * @return The OTC FX Forward Component Instance */ public static final org.drip.product.fx.FXForwardComponent FXForward ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.product.params.CurrencyPair ccyPair, final java.lang.String strMaturityTenor) { if (null == dtSpot || null == ccyPair) return null; org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, ccyPair.denomCcy()); try { return new org.drip.product.fx.FXForwardComponent ("FXFWD::" + ccyPair.code() + "::" + strMaturityTenor, ccyPair, dtEffective.julian(), dtEffective.addTenor (strMaturityTenor).julian(), 1., null); } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } /** * Construct an Array of OTC Funding Deposit Instruments from their corresponding Maturity Tenors * * @param dtSpot Spot Date * @param strCurrency Currency * @param astrMaturityTenor Array of Maturity Tenors * * @return Array of OTC Funding Deposit Instruments from their corresponding Maturity Tenors */ public static final org.drip.product.rates.SingleStreamComponent[] FundingDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String[] astrMaturityTenor) { if (null == astrMaturityTenor) return null; int iNumDeposit = astrMaturityTenor.length; org.drip.product.rates.SingleStreamComponent[] aSSCDeposit = new org.drip.product.rates.SingleStreamComponent[iNumDeposit]; if (0 == iNumDeposit) return null; for (int i = 0; i < astrMaturityTenor.length; ++i) { if (null == (aSSCDeposit[i] = FundingDeposit (dtSpot, strCurrency, astrMaturityTenor[i]))) return null; aSSCDeposit[i].setPrimaryCode (astrMaturityTenor[i]); } return aSSCDeposit; } /** * Construct an Array of OTC Forward Deposit Instruments from the corresponding Maturity Tenors * * @param dtSpot Spot Date * @param astrMaturityTenor Array of Maturity Tenors * @param forwardLabel The Forward Label * * @return Forward Deposit Instrument Instance from the corresponding Maturity Tenor */ public static final org.drip.product.rates.SingleStreamComponent[] ForwardRateDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String[] astrMaturityTenor, final org.drip.state.identifier.ForwardLabel forwardLabel) { if (null == astrMaturityTenor) return null; int iNumDeposit = astrMaturityTenor.length; org.drip.product.rates.SingleStreamComponent[] aSSCDeposit = new org.drip.product.rates.SingleStreamComponent[iNumDeposit]; if (0 == iNumDeposit) return null; for (int i = 0; i < astrMaturityTenor.length; ++i) { if (null == (aSSCDeposit[i] = ForwardRateDeposit (dtSpot, astrMaturityTenor[i], forwardLabel))) return null; aSSCDeposit[i].setPrimaryCode (astrMaturityTenor[i]); } return aSSCDeposit; } /** * Construct an Array of OTC Overnight Deposit Instrument from their Maturity Tenors * * @param dtSpot Spot Date * @param strCurrency Currency * @param astrMaturityTenor Array of Maturity Tenor * * @return Array of Overnight Deposit Instrument from their Maturity Tenors */ public static final org.drip.product.rates.SingleStreamComponent[] OvernightDeposit ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String[] astrMaturityTenor) { if (null == astrMaturityTenor) return null; int iNumDeposit = astrMaturityTenor.length; org.drip.product.rates.SingleStreamComponent[] aSSCDeposit = new org.drip.product.rates.SingleStreamComponent[iNumDeposit]; if (0 == iNumDeposit) return null; for (int i = 0; i < iNumDeposit; ++i) { if (null == (aSSCDeposit[i] = OvernightDeposit (dtSpot, strCurrency, astrMaturityTenor[i]))) return null; } return aSSCDeposit; } /** * Create an Array of Standard FRAs from the Spot Date, the Forward Label, and the Strike * * @param dtSpot Spot Date * @param forwardLabel The Forward Label * @param astrMaturityTenor Array of Maturity Tenors * @param adblFRAStrike Array of FRA Strikes * * @return Array of Standard FRA Instances */ public static final org.drip.product.fra.FRAStandardComponent[] FRAStandard ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String[] astrMaturityTenor, final double[] adblFRAStrike) { if (null == astrMaturityTenor || null == adblFRAStrike) return null; int iNumFRA = astrMaturityTenor.length; org.drip.product.fra.FRAStandardComponent[] aFRA = new org.drip.product.fra.FRAStandardComponent[iNumFRA]; if (0 == iNumFRA || iNumFRA != adblFRAStrike.length) return null; for (int i = 0; i < iNumFRA; ++i) { if (null == (aFRA[i] = FRAStandard (dtSpot, forwardLabel, astrMaturityTenor[i], adblFRAStrike[i]))) return null; } return aFRA; } /** * Construct an Array of OTC Fix Float Swaps using the specified Input Parameters * * @param dtSpot The Spot Date * @param strCurrency The OTC Currency * @param strLocation Location * @param astrMaturityTenor Array of Maturity Tenors * @param strIndex Index * @param dblCoupon Coupon * * @return The Array of OTC Fix Float Swaps */ public static final org.drip.product.rates.FixFloatComponent[] FixFloatStandard ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strLocation, final java.lang.String[] astrMaturityTenor, final java.lang.String strIndex, final double dblCoupon) { if (null == astrMaturityTenor) return null; int iNumFixFloat = astrMaturityTenor.length; org.drip.product.rates.FixFloatComponent[] aFFC = new org.drip.product.rates.FixFloatComponent[iNumFixFloat]; if (0 == iNumFixFloat) return null; for (int i = 0; i < iNumFixFloat; ++i) { if (null == (aFFC[i] = FixFloatStandard (dtSpot, strCurrency, strLocation, astrMaturityTenor[i], strIndex, 0.))) return null; } return aFFC; } /** * Construct an Array of Custom Fix Float Swap Instances * * @param dtSpot The Spot Date * @param forwardLabel The Forward Label * @param astrMaturityTenor Array of Maturity Tenors * * @return Array of Custom Fix Float Swap Instances */ public static final org.drip.product.rates.FixFloatComponent[] FixFloatCustom ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String[] astrMaturityTenor) { if (null == dtSpot || null == forwardLabel || null == astrMaturityTenor) return null; int iNumComp = astrMaturityTenor.length; org.drip.param.period.CompositePeriodSetting cpsFloating = null; org.drip.param.period.ComposableFloatingUnitSetting cfusFloating = null; org.drip.product.rates.FixFloatComponent[] aFFC = new org.drip.product.rates.FixFloatComponent[iNumComp]; if (0 == iNumComp) return null; java.lang.String strCurrency = forwardLabel.currency(); java.lang.String strForwardTenor = forwardLabel.tenor(); int iTenorInMonths = new java.lang.Integer (strForwardTenor.split ("M")[0]); org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCurrency).addDays (2); try { cfusFloating = new org.drip.param.period.ComposableFloatingUnitSetting (strForwardTenor, org.drip.analytics.support.CompositePeriodBuilder.EDGE_DATE_SEQUENCE_REGULAR, null, forwardLabel, org.drip.analytics.support.CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE, 0.); cpsFloating = new org.drip.param.period.CompositePeriodSetting (12 / iTenorInMonths, strForwardTenor, strCurrency, null, -1., null, null, null, null); } catch (java.lang.Exception e) { e.printStackTrace(); return null; } for (int i = 0; i < iNumComp; ++i) { org.drip.market.otc.FixedFloatSwapConvention ffsc = org.drip.market.otc.IBORFixedFloatContainer.ConventionFromJurisdiction (strCurrency, "ALL", astrMaturityTenor[i], "MAIN"); if (null == ffsc) return null; try { org.drip.product.rates.Stream floatingStream = new org.drip.product.rates.Stream (org.drip.analytics.support.CompositePeriodBuilder.FloatingCompositeUnit (org.drip.analytics.support.CompositePeriodBuilder.RegularEdgeDates (dtEffective, strForwardTenor, astrMaturityTenor[i], null), cpsFloating, cfusFloating)); org.drip.product.rates.Stream fixedStream = ffsc.fixedStreamConvention().createStream (dtEffective, astrMaturityTenor[i], 0., 1.); aFFC[i] = new org.drip.product.rates.FixFloatComponent (fixedStream, floatingStream, null); } catch (java.lang.Exception e) { e.printStackTrace(); return null; } aFFC[i].setPrimaryCode ("FixFloat:" + astrMaturityTenor[i]); } return aFFC; } /** * Construct an Array of OTC Fix Float OIS Instances * * @param dtSpot Spot Date * @param strCurrency Currency * @param astrMaturityTenor Array of OIS Maturity Tenors * @param adblCoupon OIS Fixed Rate Coupon * @param bFund TRUE - Floater Based off of Fund * * @return Array of Fix Float OIS Instances */ public static final org.drip.product.rates.FixFloatComponent[] OISFixFloat ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String[] astrMaturityTenor, final double[] adblCoupon, final boolean bFund) { if (null == astrMaturityTenor) return null; int iNumOIS = astrMaturityTenor.length; org.drip.product.rates.FixFloatComponent[] aFixFloatOIS = new org.drip.product.rates.FixFloatComponent[iNumOIS]; if (0 == iNumOIS) return null; for (int i = 0; i < iNumOIS; ++i) { if (null == (aFixFloatOIS[i] = OISFixFloat (dtSpot, strCurrency, astrMaturityTenor[i], adblCoupon[i], bFund))) return null; } return aFixFloatOIS; } /** * Construct an Array of OTC OIS Fix-Float Futures * * @param dtSpot Spot Date * @param strCurrency Currency * @param astrEffectiveTenor Array of Effective Tenors * @param astrMaturityTenor Array of Maturity Tenors * @param adblCoupon Array of Coupons * @param bFund TRUE - Floater Based off of Fund * * @return Array of OIS Fix-Float Futures */ public static final org.drip.product.rates.FixFloatComponent[] OISFixFloatFutures ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String[] astrEffectiveTenor, final java.lang.String[] astrMaturityTenor, final double[] adblCoupon, final boolean bFund) { if (null == dtSpot || null == astrEffectiveTenor || null == astrMaturityTenor || null == adblCoupon) return null; int iNumOISFutures = astrEffectiveTenor.length; org.drip.product.rates.FixFloatComponent[] aOISFutures = new org.drip.product.rates.FixFloatComponent[iNumOISFutures]; if (0 == iNumOISFutures || iNumOISFutures != astrMaturityTenor.length || iNumOISFutures != adblCoupon.length) return null; for (int i = 0; i < iNumOISFutures; ++i) { if (null == (aOISFutures[i] = OISFixFloat (dtSpot.addTenor (astrEffectiveTenor[i]), strCurrency, astrMaturityTenor[i], adblCoupon[i], bFund))) return null; } return aOISFutures; } /** * Construct an Array of OTC Float-Float Swap Instances * * @param dtSpot Spot Date * @param strCurrency Currency * @param strDerivedTenor Tenor of the Derived Leg * @param astrMaturityTenor Array of the Float-Float Swap Maturity Tenors * @param dblBasis The Float-Float Swap Basis * * @return Array of OTC Float-Float Swap Instances */ public static final org.drip.product.rates.FloatFloatComponent[] FloatFloat ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String strCurrency, final java.lang.String strDerivedTenor, final java.lang.String[] astrMaturityTenor, final double dblBasis) { if (null == astrMaturityTenor) return null; org.drip.market.otc.FloatFloatSwapConvention ffsc = org.drip.market.otc.IBORFloatFloatContainer.ConventionFromJurisdiction (strCurrency); int iNumFFC = astrMaturityTenor.length; org.drip.product.rates.FloatFloatComponent[] aFFC = new org.drip.product.rates.FloatFloatComponent[iNumFFC]; if (null == ffsc || 0 == iNumFFC) return null; for (int i = 0; i < iNumFFC; ++i) { if (null == (aFFC[i] = ffsc.createFloatFloatComponent (dtSpot, strDerivedTenor, astrMaturityTenor[i], dblBasis, 1.))) return null; } return aFFC; } /** * Create an Array of the OTC CDS Instance. * * @param dtSpot Spot Date * @param astrMaturityTenor Array of Maturity Tenors * @param adblCoupon Array of Coupon * @param strCurrency Currency * @param strCredit Credit Curve * * @return Array of OTC CDS Instances */ public static final org.drip.product.definition.CreditDefaultSwap[] CDS ( final org.drip.analytics.date.JulianDate dtSpot, final java.lang.String[] astrMaturityTenor, final double[] adblCoupon, final java.lang.String strCurrency, final java.lang.String strCredit) { if (null == dtSpot || null == strCurrency || null == astrMaturityTenor || null == adblCoupon) return null; int iNumCDS = astrMaturityTenor.length; java.lang.String strCalendar = strCurrency; org.drip.product.definition.CreditDefaultSwap[] aCDS = new org.drip.product.definition.CreditDefaultSwap[iNumCDS]; if (0 == iNumCDS || iNumCDS != adblCoupon.length) return null; org.drip.analytics.date.JulianDate dtFirstCoupon = dtSpot.addBusDays (0, strCalendar).nextCreditIMM (3); if (null == dtFirstCoupon) return null; org.drip.analytics.date.JulianDate dtEffective = dtFirstCoupon.subtractTenor ("3M"); if (null == dtEffective) return null; double dblRecovery = "CAD".equalsIgnoreCase (strCurrency) || "EUR".equalsIgnoreCase (strCurrency) || "GBP".equalsIgnoreCase (strCurrency) || "HKD".equalsIgnoreCase (strCurrency) || "USD".equalsIgnoreCase (strCurrency) ? 0.40 : 0.25; for (int i = 0; i < iNumCDS; ++i) aCDS[i] = org.drip.product.creator.CDSBuilder.CreateCDS (dtEffective, dtFirstCoupon.addTenor (astrMaturityTenor[i]), adblCoupon[i], strCurrency, dblRecovery, strCredit, strCalendar, true); return aCDS; } /** * Create an Array of OTC FX Forward Components * * @param dtSpot Spot Date * @param ccyPair Currency Pair * @param astrMaturityTenor Array of Maturity Tenors * * @return Array of OTC FX Forward Component Instances */ public static final org.drip.product.fx.FXForwardComponent[] FXForward ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.product.params.CurrencyPair ccyPair, final java.lang.String[] astrMaturityTenor) { if (null == astrMaturityTenor) return null; int iNumFXComp = astrMaturityTenor.length; org.drip.product.fx.FXForwardComponent[] aFXFC = new org.drip.product.fx.FXForwardComponent[iNumFXComp]; if (0 == iNumFXComp) return null; for (int i = 0; i < iNumFXComp; ++i) aFXFC[i] = FXForward (dtSpot, ccyPair, astrMaturityTenor[i]); return aFXFC; } /** * Construct an Instance of the Standard OTC FRA Cap/Floor * * @param dtSpot Spot Date * @param forwardLabel The Forward Label * @param strMaturityTenor Cap/Floor Maturity Tenor * @param dblStrike Cap/Floor Strike * @param bIsCap TRUE - Contract is a Cap * * @return The Cap/Floor Instance */ public static final org.drip.product.fra.FRAStandardCapFloor CapFloor ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String strMaturityTenor, final double dblStrike, final boolean bIsCap) { if (null == dtSpot || null == forwardLabel) return null; java.lang.String strForwardTenor = forwardLabel.tenor(); java.lang.String strCurrency = forwardLabel.currency(); java.lang.String strCalendar = strCurrency; org.drip.analytics.date.JulianDate dtEffective = dtSpot.addBusDays (0, strCalendar); try { org.drip.param.period.ComposableFloatingUnitSetting cfus = new org.drip.param.period.ComposableFloatingUnitSetting (strForwardTenor, org.drip.analytics.support.CompositePeriodBuilder.EDGE_DATE_SEQUENCE_SINGLE, null, forwardLabel, org.drip.analytics.support.CompositePeriodBuilder.REFERENCE_PERIOD_IN_ADVANCE, 0.); org.drip.param.period.CompositePeriodSetting cps = new org.drip.param.period.CompositePeriodSetting (org.drip.analytics.support.Helper.TenorToFreq (strForwardTenor), strForwardTenor, strCurrency, null, 1., null, null, null, null); org.drip.product.rates.Stream floatStream = new org.drip.product.rates.Stream (org.drip.analytics.support.CompositePeriodBuilder.FloatingCompositeUnit (org.drip.analytics.support.CompositePeriodBuilder.RegularEdgeDates (dtEffective.julian(), strForwardTenor, strMaturityTenor, null), cps, cfus)); return new org.drip.product.fra.FRAStandardCapFloor (forwardLabel.fullyQualifiedName() + (bIsCap ? "::CAP" : "::FLOOR"), floatStream, "ParForward", bIsCap, dblStrike, new org.drip.product.params.LastTradingDateSetting (org.drip.product.params.LastTradingDateSetting.MID_CURVE_OPTION_QUARTERLY, "", java.lang.Integer.MIN_VALUE), null, new org.drip.pricer.option.BlackScholesAlgorithm()); } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } /** * Construct an Instance of the Standard OTC FRA Cap/Floor * * @param dtSpot Spot Date * @param forwardLabel The Forward Label * @param astrMaturityTenor Array of Cap/Floor Maturity Tenors * @param adblStrike Array of Cap/Floor Strikes * @param bIsCap TRUE - Contract is a Cap * * @return The Cap/Floor Instance */ public static final org.drip.product.fra.FRAStandardCapFloor[] CapFloor ( final org.drip.analytics.date.JulianDate dtSpot, final org.drip.state.identifier.ForwardLabel forwardLabel, final java.lang.String[] astrMaturityTenor, final double[] adblStrike, final boolean bIsCap) { if (null == astrMaturityTenor || null == adblStrike) return null; int iNumCapFloor = astrMaturityTenor.length; org.drip.product.fra.FRAStandardCapFloor[] aFRACapFloor = new org.drip.product.fra.FRAStandardCapFloor[iNumCapFloor]; if (0 == iNumCapFloor || iNumCapFloor != adblStrike.length) return null; for (int i = 0; i < iNumCapFloor; ++i) { if (null == (aFRACapFloor[i] = org.drip.service.template.OTCInstrumentBuilder.CapFloor (dtSpot, forwardLabel, astrMaturityTenor[i], adblStrike[i], bIsCap))) return null; } return aFRACapFloor; } }
apache-2.0
nuwand/carbon-apimgt
components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/v1/KeyManagersApiService.java
733
package org.wso2.carbon.apimgt.rest.api.publisher.v1; import org.wso2.carbon.apimgt.rest.api.publisher.v1.*; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.*; import org.apache.cxf.jaxrs.ext.MessageContext; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.KeyManagerListDTO; import java.util.List; import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; public interface KeyManagersApiService { public Response keyManagersGet(MessageContext messageContext) throws APIManagementException; }
apache-2.0
nitram509/decentral-authentication-playground
java/src/main/java/jose4j/asym/Jose4jVerifier.java
847
package jose4j.asym; import org.jose4j.jws.JsonWebSignature; import org.jose4j.lang.JoseException; import java.security.PublicKey; public class Jose4jVerifier { public static void main(String[] args) { String token = new Jose4jProvider().create(); try { new Jose4jVerifier().verify(token); } catch (JoseException e) { e.printStackTrace(); } } public void verify(String token) throws JoseException { JsonWebSignature jws = new JsonWebSignature(); jws.setCompactSerialization(token); PublicKey publicKey = ExampleRsaKeyPair.createPublicKey(); jws.setKey(publicKey); boolean signatureVerified = jws.verifySignature(); System.out.println("JWS Signature is valid: " + signatureVerified); String payload = jws.getPayload(); System.out.println("JWS payload: " + payload); } }
apache-2.0
tommyettinger/doughyo
src/main/java/vigna/fastutil/ints/AbstractIntList.java
19931
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Primitive-type-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* * Copyright (C) 2002-2015 Sebastiano Vigna * * 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 vigna.fastutil.ints; import java.util.*; /** An abstract class providing basic methods for lists implementing a type-specific list interface. * * <P>As an additional bonus, this class implements on top of the list operations a type-specific stack. */ public abstract class AbstractIntList extends AbstractIntCollection implements IntList, IntStack { protected AbstractIntList() {} /** Ensures that the given index is nonnegative and not greater than the list size. * * @param index an index. * @throws IndexOutOfBoundsException if the given index is negative or greater than the list size. */ protected void ensureIndex( final int index ) { if ( index < 0 ) throw new IndexOutOfBoundsException( "Index (" + index + ") is negative" ); if ( index > size() ) throw new IndexOutOfBoundsException( "Index (" + index + ") is greater than list size (" + ( size() ) + ")" ); } /** Ensures that the given index is nonnegative and smaller than the list size. * * @param index an index. * @throws IndexOutOfBoundsException if the given index is negative or not smaller than the list size. */ protected void ensureRestrictedIndex( final int index ) { if ( index < 0 ) throw new IndexOutOfBoundsException( "Index (" + index + ") is negative" ); if ( index >= size() ) throw new IndexOutOfBoundsException( "Index (" + index + ") is greater than or equal to list size (" + ( size() ) + ")" ); } public void add( final int index, final int k ) { throw new UnsupportedOperationException(); } public boolean add( final int k ) { add( size(), k ); return true; } public int removeInt( int i ) { throw new UnsupportedOperationException(); } public int set( final int index, final int k ) { throw new UnsupportedOperationException(); } public boolean addAll( int index, final Collection<? extends Integer> c ) { ensureIndex( index ); int n = c.size(); if ( n == 0 ) return false; Iterator<? extends Integer> i = c.iterator(); while ( n-- != 0 ) add( index++, i.next() ); return true; } /** Delegates to a more generic method. */ public boolean addAll( final Collection<? extends Integer> c ) { return addAll( size(), c ); } /** Delegates to the new covariantly stronger generic method. */ @Deprecated public IntListIterator intListIterator() { return listIterator(); } /** Delegates to the new covariantly stronger generic method. */ @Deprecated public IntListIterator intListIterator( final int index ) { return listIterator( index ); } public IntListIterator iterator() { return listIterator(); } public IntListIterator listIterator() { return listIterator( 0 ); } public IntListIterator listIterator( final int index ) { return new AbstractIntListIterator() { int pos = index, last = -1; public boolean hasNext() { return pos < AbstractIntList.this.size(); } public boolean hasPrevious() { return pos > 0; } public int nextInt() { if ( !hasNext() ) throw new NoSuchElementException(); return AbstractIntList.this.getInt( last = pos++ ); } public int previousInt() { if ( !hasPrevious() ) throw new NoSuchElementException(); return AbstractIntList.this.getInt( last = --pos ); } public int nextIndex() { return pos; } public int previousIndex() { return pos - 1; } public void add( int k ) { if ( last == -1 ) throw new IllegalStateException(); AbstractIntList.this.add( pos++, k ); last = -1; } public void set( int k ) { if ( last == -1 ) throw new IllegalStateException(); AbstractIntList.this.set( last, k ); } public void remove() { if ( last == -1 ) throw new IllegalStateException(); AbstractIntList.this.removeInt( last ); /* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */ if ( last < pos ) pos--; last = -1; } }; } public boolean contains( final int k ) { return indexOf( k ) >= 0; } public int indexOf( final int k ) { final IntListIterator i = listIterator(); int e; while ( i.hasNext() ) { e = i.nextInt(); if ( ( ( k ) == ( e ) ) ) return i.previousIndex(); } return -1; } public int lastIndexOf( final int k ) { IntListIterator i = listIterator( size() ); int e; while ( i.hasPrevious() ) { e = i.previousInt(); if ( ( ( k ) == ( e ) ) ) return i.nextIndex(); } return -1; } public void size( final int size ) { int i = size(); if ( size > i ) while ( i++ < size ) add( ( 0 ) ); else while ( i-- != size ) remove( i ); } public IntList subList( final int from, final int to ) { ensureIndex( from ); ensureIndex( to ); if ( from > to ) throw new IndexOutOfBoundsException( "Start index (" + from + ") is greater than end index (" + to + ")" ); return new IntSubList( this, from, to ); } /** Delegates to the new covariantly stronger generic method. */ @Deprecated public IntList intSubList( final int from, final int to ) { return subList( from, to ); } /** Removes elements of this type-specific list one-by-one. * * <P>This is a trivial iterator-based implementation. It is expected that implementations will override this method with a more optimized version. * * * @param from the start index (inclusive). * @param to the end index (exclusive). */ public void removeElements( final int from, final int to ) { ensureIndex( to ); IntListIterator i = listIterator( from ); int n = to - from; if ( n < 0 ) throw new IllegalArgumentException( "Start index (" + from + ") is greater than end index (" + to + ")" ); while ( n-- != 0 ) { i.nextInt(); i.remove(); } } /** Adds elements to this type-specific list one-by-one. * * <P>This is a trivial iterator-based implementation. It is expected that implementations will override this method with a more optimized version. * * @param index the index at which to add elements. * @param a the array containing the elements. * @param offset the offset of the first element to add. * @param length the number of elements to add. */ public void addElements( int index, final int a[], int offset, int length ) { ensureIndex( index ); if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" ); if ( offset + length > a.length ) throw new ArrayIndexOutOfBoundsException( "End index (" + ( offset + length ) + ") is greater than array length (" + a.length + ")" ); while ( length-- != 0 ) add( index++, a[ offset++ ] ); } public void addElements( final int index, final int a[] ) { addElements( index, a, 0, a.length ); } /** Copies element of this type-specific list into the given array one-by-one. * * <P>This is a trivial iterator-based implementation. It is expected that implementations will override this method with a more optimized version. * * @param from the start index (inclusive). * @param a the destination array. * @param offset the offset into the destination array where to store the first element copied. * @param length the number of elements to be copied. */ public void getElements( final int from, final int a[], int offset, int length ) { IntListIterator i = listIterator( from ); if ( offset < 0 ) throw new ArrayIndexOutOfBoundsException( "Offset (" + offset + ") is negative" ); if ( offset + length > a.length ) throw new ArrayIndexOutOfBoundsException( "End index (" + ( offset + length ) + ") is greater than array length (" + a.length + ")" ); if ( from + length > size() ) throw new IndexOutOfBoundsException( "End index (" + ( from + length ) + ") is greater than list size (" + size() + ")" ); while ( length-- != 0 ) a[ offset++ ] = i.nextInt(); } private boolean valEquals(final Object a, final Object b ) { return a == null ? b == null : a.equals( b ); } public boolean equals( final Object o ) { if ( o == this ) return true; if ( !( o instanceof List) ) return false; final List<?> l = (List<?>)o; int s = size(); if ( s != l.size() ) return false; if ( l instanceof IntList ) { final IntListIterator i1 = listIterator(), i2 = ( (IntList)l ).listIterator(); while ( s-- != 0 ) if ( i1.nextInt() != i2.nextInt() ) return false; return true; } final ListIterator<?> i1 = listIterator(), i2 = l.listIterator(); while ( s-- != 0 ) if ( !valEquals( i1.next(), i2.next() ) ) return false; return true; } /** Compares this list to another object. If the argument is a {@link List}, this method performs a lexicographical comparison; otherwise, it throws a <code>ClassCastException</code>. * * @param l a list. * @return if the argument is a {@link List}, a negative integer, zero, or a positive integer as this list is lexicographically less than, equal to, or greater than the argument. * @throws ClassCastException if the argument is not a list. */ public int compareTo( final List<? extends Integer> l ) { if ( l == this ) return 0; if ( l instanceof IntList ) { final IntListIterator i1 = listIterator(), i2 = ( (IntList)l ).listIterator(); int r; int e1, e2; while ( i1.hasNext() && i2.hasNext() ) { e1 = i1.nextInt(); e2 = i2.nextInt(); if ( ( r = ( Integer.compare( ( e1 ), ( e2 ) ) ) ) != 0 ) return r; } return i2.hasNext() ? -1 : ( i1.hasNext() ? 1 : 0 ); } ListIterator<? extends Integer> i1 = listIterator(), i2 = l.listIterator(); int r; while ( i1.hasNext() && i2.hasNext() ) { if ( ( r = ( (Comparable<? super Integer>)i1.next() ).compareTo( i2.next() ) ) != 0 ) return r; } return i2.hasNext() ? -1 : ( i1.hasNext() ? 1 : 0 ); } /** Returns the hash code for this list, which is identical to {@link List#hashCode()}. * * @return the hash code for this list. */ public int hashCode() { IntegerIterator i = iterator(); int h = 1, s = size(); while ( s-- != 0 ) { int k = i.nextInt(); h = 31 * h + ( k ); } return h; } public void push( int o ) { add( o ); } public int popInt() { if ( isEmpty() ) throw new NoSuchElementException(); return removeInt( size() - 1 ); } public int topInt() { if ( isEmpty() ) throw new NoSuchElementException(); return getInt( size() - 1 ); } public int peekInt( int i ) { return getInt( size() - 1 - i ); } public boolean rem( int k ) { int index = indexOf( k ); if ( index == -1 ) return false; removeInt( index ); return true; } /** Delegates to <code>rem()</code>. */ public boolean remove( final Object o ) { return rem( ( ( ( (Integer)( o ) ).intValue() ) ) ); } /** Delegates to a more generic method. */ public boolean addAll( final int index, final IntCollection c ) { return addAll( index, (Collection<? extends Integer>)c ); } /** Delegates to a more generic method. */ public boolean addAll( final int index, final IntList l ) { return addAll( index, (IntCollection)l ); } public boolean addAll( final IntCollection c ) { return addAll( size(), c ); } public boolean addAll( final IntList l ) { return addAll( size(), l ); } /** Delegates to the corresponding type-specific method. */ public void add( final int index, final Integer ok ) { add( index, ok.intValue() ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer set(final int index, final Integer ok ) { return ( Integer.valueOf( set( index, ok.intValue() ) ) ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer get(final int index ) { return ( Integer.valueOf( getInt( index ) ) ); } /** Delegates to the corresponding type-specific method. */ public int indexOf( final Object ok ) { return indexOf( ( ( ( (Integer)( ok ) ).intValue() ) ) ); } /** Delegates to the corresponding type-specific method. */ public int lastIndexOf( final Object ok ) { return lastIndexOf( ( ( ( (Integer)( ok ) ).intValue() ) ) ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer remove(final int index ) { return ( Integer.valueOf( removeInt( index ) ) ); } /** Delegates to the corresponding type-specific method. */ public void push( Integer o ) { push( o.intValue() ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer pop() { return Integer.valueOf( popInt() ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer top() { return Integer.valueOf( topInt() ); } /** Delegates to the corresponding type-specific method. * * @deprecated Please use the corresponding type-specific method instead. */ @Deprecated public Integer peek(int i ) { return Integer.valueOf( peekInt( i ) ); } public String toString() { final StringBuilder s = new StringBuilder(); final IntegerIterator i = iterator(); int n = size(); int k; boolean first = true; s.append( "[" ); while ( n-- != 0 ) { if ( first ) first = false; else s.append( ", " ); k = i.nextInt(); s.append( String.valueOf( k ) ); } s.append( "]" ); return s.toString(); } public static class IntSubList extends AbstractIntList implements java.io.Serializable { private static final long serialVersionUID = -7046029254386353129L; /** The list this sublist restricts. */ protected final IntList l; /** Initial (inclusive) index of this sublist. */ protected final int from; /** Final (exclusive) index of this sublist. */ protected int to; private static final boolean ASSERTS = false; public IntSubList( final IntList l, final int from, final int to ) { this.l = l; this.from = from; this.to = to; } private void assertRange() { if ( ASSERTS ) { assert from <= l.size(); assert to <= l.size(); assert to >= from; } } public boolean add( final int k ) { l.add( to, k ); to++; if ( ASSERTS ) assertRange(); return true; } public void add( final int index, final int k ) { ensureIndex( index ); l.add( from + index, k ); to++; if ( ASSERTS ) assertRange(); } public boolean addAll( final int index, final Collection<? extends Integer> c ) { ensureIndex( index ); to += c.size(); if ( ASSERTS ) { boolean retVal = l.addAll( from + index, c ); assertRange(); return retVal; } return l.addAll( from + index, c ); } public int getInt( int index ) { ensureRestrictedIndex( index ); return l.getInt( from + index ); } public int removeInt( int index ) { ensureRestrictedIndex( index ); to--; return l.removeInt( from + index ); } public int set( int index, int k ) { ensureRestrictedIndex( index ); return l.set( from + index, k ); } public void clear() { removeElements( 0, size() ); if ( ASSERTS ) assertRange(); } public int size() { return to - from; } public void getElements( final int from, final int[] a, final int offset, final int length ) { ensureIndex( from ); if ( from + length > size() ) throw new IndexOutOfBoundsException( "End index (" + from + length + ") is greater than list size (" + size() + ")" ); l.getElements( this.from + from, a, offset, length ); } public void removeElements( final int from, final int to ) { ensureIndex( from ); ensureIndex( to ); l.removeElements( this.from + from, this.from + to ); this.to -= ( to - from ); if ( ASSERTS ) assertRange(); } public void addElements( int index, final int a[], int offset, int length ) { ensureIndex( index ); l.addElements( this.from + index, a, offset, length ); this.to += length; if ( ASSERTS ) assertRange(); } public IntListIterator listIterator( final int index ) { ensureIndex( index ); return new AbstractIntListIterator() { int pos = index, last = -1; public boolean hasNext() { return pos < size(); } public boolean hasPrevious() { return pos > 0; } public int nextInt() { if ( !hasNext() ) throw new NoSuchElementException(); return l.getInt( from + ( last = pos++ ) ); } public int previousInt() { if ( !hasPrevious() ) throw new NoSuchElementException(); return l.getInt( from + ( last = --pos ) ); } public int nextIndex() { return pos; } public int previousIndex() { return pos - 1; } public void add( int k ) { if ( last == -1 ) throw new IllegalStateException(); IntSubList.this.add( pos++, k ); last = -1; if ( ASSERTS ) assertRange(); } public void set( int k ) { if ( last == -1 ) throw new IllegalStateException(); IntSubList.this.set( last, k ); } public void remove() { if ( last == -1 ) throw new IllegalStateException(); IntSubList.this.removeInt( last ); /* If the last operation was a next(), we are removing an element *before* us, and we must decrease pos correspondingly. */ if ( last < pos ) pos--; last = -1; if ( ASSERTS ) assertRange(); } }; } public IntList subList( final int from, final int to ) { ensureIndex( from ); ensureIndex( to ); if ( from > to ) throw new IllegalArgumentException( "Start index (" + from + ") is greater than end index (" + to + ")" ); return new IntSubList( this, from, to ); } public boolean rem( int k ) { int index = indexOf( k ); if ( index == -1 ) return false; to--; l.removeInt( from + index ); if ( ASSERTS ) assertRange(); return true; } public boolean remove( final Object o ) { return rem( ( ( ( (Integer)( o ) ).intValue() ) ) ); } public boolean addAll( final int index, final IntCollection c ) { ensureIndex( index ); to += c.size(); if ( ASSERTS ) { boolean retVal = l.addAll( from + index, c ); assertRange(); return retVal; } return l.addAll( from + index, c ); } public boolean addAll( final int index, final IntList l ) { ensureIndex( index ); to += l.size(); if ( ASSERTS ) { boolean retVal = this.l.addAll( from + index, l ); assertRange(); return retVal; } return this.l.addAll( from + index, l ); } } }
apache-2.0
deanriverson/griffon-javafx-plugin
src/main/org/codehaus/griffon/runtime/javafx/JavaFXGriffonControllerActionManager.java
1346
/* * Copyright 2008-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.griffon.runtime.javafx; import griffon.core.GriffonApplication; import griffon.core.GriffonController; import griffon.core.controller.GriffonControllerAction; import org.codehaus.griffon.runtime.core.controller.AbstractGriffonControllerActionManager; /** * @author Andres Almiray */ public class JavaFXGriffonControllerActionManager extends AbstractGriffonControllerActionManager { protected JavaFXGriffonControllerActionManager(GriffonApplication app) { super(app); } @Override protected GriffonControllerAction createControllerAction(GriffonController controller, String actionName) { return new JavaFXGriffonControllerAction(this, controller, actionName); } }
apache-2.0
NVolcz/zaproxy
src/ch/csnc/extension/httpclient/SSLContextManager.java
16043
/* * This file is part of WebScarab, an Open Web Application Security * Project utility. For details, please see http://www.owasp.org/ * * Copyright (c) 2002 - 2004 Rogan Dawes * * Please note that this file was originally released under the * GNU General Public License as published by the Free Software Foundation; * either version 2 of the License, or (at your option) any later version. * * As of October 2014 Rogan Dawes granted the OWASP ZAP Project permission to * redistribute this code under the Apache License, Version 2.0: * * * 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 ch.csnc.extension.httpclient; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.SecureRandom; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSessionContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.log4j.Logger; import ch.csnc.extension.util.Encoding; public class SSLContextManager { /** * The canonical class name of Sun PKCS#11 Provider. */ public static final String SUN_PKCS11_CANONICAL_CLASS_NAME = "sun.security.pkcs11.SunPKCS11"; /** * The canonical class name of IBMPKCS11Impl Provider. */ public static final String IBM_PKCS11_CONONICAL_CLASS_NAME = "com.ibm.crypto.pkcs11impl.provider.IBMPKCS11Impl"; /** * The name for providers of type PKCS#11. * * @see #isProviderAvailable(String) */ public static final String PKCS11_PROVIDER_TYPE = "PKCS11"; /** * The name of the {@code KeyStore} type of Sun PKCS#11 Provider. * * @see KeyStore#getInstance(String, Provider) */ private static final String SUN_PKCS11_KEYSTORE_TYPE = "PKCS11"; /** * The name of the {@code KeyStore} type of IBMPKCS11Impl Provider. * * @see KeyStore#getInstance(String, Provider) */ private static final String IBM_PKCS11_KEYSTORE_TYPE = "PKCS11IMPLKS"; private Map<String, SSLContext> _contextMaps = new TreeMap<String, SSLContext>(); private SSLContext _noClientCertContext; private String _defaultKey = null; private Map<String, Map<?, ?>> _aliasPasswords = new HashMap<String, Map<?, ?>>(); private List<KeyStore> _keyStores = new ArrayList<KeyStore>(); private Map<KeyStore, String> _keyStoreDescriptions = new HashMap<KeyStore, String>(); private Map<KeyStore, String> _keyStorePasswords = new HashMap<KeyStore, String>(); private static Logger log = Logger.getLogger(SSLContextManager.class); private static TrustManager[] _trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; private int _defaultKeystoreIndex = -1; private int _defaultAliasIndex = -1; /** Creates a new instance of SSLContextManager */ public SSLContextManager() { try { _noClientCertContext = SSLContext.getInstance("SSL"); _noClientCertContext.init(null, _trustAllCerts, new SecureRandom()); } catch (NoSuchAlgorithmException nsao) { log.error("Could not get an instance of the SSL algorithm: " + nsao.getMessage(), nsao); } catch (KeyManagementException kme) { log.error("Error initialising the SSL Context: " + kme.getMessage(), kme); } try { initMSCAPI(); } catch (Exception e) { } } public boolean isProviderAvailable(String type) { try { if (type.equals(PKCS11_PROVIDER_TYPE)) { try { Class.forName(SUN_PKCS11_CANONICAL_CLASS_NAME); return true; } catch (Throwable ignore) { Class.forName(IBM_PKCS11_CONONICAL_CLASS_NAME); return true; } } else if (type.equals("msks")) { Class.forName("se.assembla.jce.provider.ms.MSProvider"); return true; } } catch (Throwable ignore) { } return false; } private int addKeyStore(KeyStore ks, String description, String password) { int index = _keyStores.indexOf(ks); if (index == -1) { _keyStores.add(ks); index = _keyStores.size() - 1; } _keyStoreDescriptions.put(ks, description); _keyStorePasswords.put(ks, password); return index; } public boolean removeKeyStore(int keystoreIndex) { boolean isDefaultKeyStore = (keystoreIndex == _defaultKeystoreIndex); KeyStore ks = _keyStores.get(keystoreIndex); _keyStores.remove(ks); _keyStoreDescriptions.remove(ks); _keyStorePasswords.remove(ks); if (isDefaultKeyStore) { _defaultKeystoreIndex = -1; _defaultAliasIndex = -1; } return isDefaultKeyStore; } public int getKeyStoreCount() { return _keyStores.size(); } public String getKeyStoreDescription(int keystoreIndex) { return _keyStoreDescriptions.get(_keyStores.get(keystoreIndex)); } public String getKeyStorePassword(int keystoreIndex) { return _keyStorePasswords.get(_keyStores.get(keystoreIndex)); } public int getAliasCount(int keystoreIndex) { return getAliases(_keyStores.get(keystoreIndex)).size(); } public String getAliasAt(int keystoreIndex, int aliasIndex) { return getAliases(_keyStores.get(keystoreIndex)).get(aliasIndex).getAlias(); } private List<AliasCertificate> getAliases(KeyStore ks) { List<AliasCertificate> aliases = new ArrayList<AliasCertificate>(); try { Enumeration<String> en = ks.aliases(); boolean isIbm = isIbmPKCS11Provider(); while (en.hasMoreElements()) { String alias = en.nextElement(); // Sun's and IBM's KeyStore implementations behave differently... // With IBM's KeyStore impl #getCertificate(String) returns null when #isKeyEntry(String) returns true. // If IBM add all certificates and let the user choose the correct one. if (ks.isKeyEntry(alias) || (isIbm && ks.isCertificateEntry(alias))) { Certificate cert = ks.getCertificate(alias); // IBM: Maybe we should check the KeyUsage? // ((X509Certificate) cert).getKeyUsage()[0] AliasCertificate aliasCert = new AliasCertificate(cert, alias); aliases.add(aliasCert); } } } catch (KeyStoreException kse) { kse.printStackTrace(); } return aliases; } public List<AliasCertificate> getAliases(int ks) { return getAliases(_keyStores.get(ks)); } public Certificate getCertificate(int keystoreIndex, int aliasIndex) { try { KeyStore ks = _keyStores.get(keystoreIndex); String alias = getAliasAt(keystoreIndex, aliasIndex); return ks.getCertificate(alias); } catch (Exception e) { return null; } } public String getFingerPrint(Certificate cert) throws KeyStoreException { if (!(cert instanceof X509Certificate)) { return null; } StringBuffer buff = new StringBuffer(); X509Certificate x509 = (X509Certificate) cert; try { String fingerprint = Encoding.hashMD5(cert.getEncoded()); for (int i = 0; i < fingerprint.length(); i += 2) { buff.append(fingerprint.substring(i, i + 1)).append(":"); } buff.deleteCharAt(buff.length() - 1); } catch (CertificateEncodingException e) { throw new KeyStoreException(e.getMessage()); } String dn = x509.getSubjectDN().getName(); log.info("Fingerprint is " + buff.toString().toUpperCase()); return buff.toString().toUpperCase() + " " + dn; } public boolean isKeyUnlocked(int keystoreIndex, int aliasIndex) { KeyStore ks = _keyStores.get(keystoreIndex); String alias = getAliasAt(keystoreIndex, aliasIndex); Map<?, ?> pwmap = _aliasPasswords.get(ks); if (pwmap == null) { return false; } return pwmap.containsKey(alias); } public void setDefaultKey(int keystoreIndex, int aliasIndex) throws KeyStoreException { _defaultKeystoreIndex = keystoreIndex; _defaultAliasIndex = aliasIndex; if ((_defaultKeystoreIndex == -1) || (_defaultAliasIndex == -1)) { _defaultKey = ""; } else { _defaultKey = getFingerPrint(getCertificate(keystoreIndex, aliasIndex)); } } public String getDefaultKey() { return _defaultKey; } public Certificate getDefaultCertificate() { return getCertificate(_defaultKeystoreIndex, _defaultAliasIndex); } public int initMSCAPI() throws KeyStoreException, NoSuchProviderException, IOException, NoSuchAlgorithmException, CertificateException { try { if (!isProviderAvailable("msks")) { return -1; } Provider mscapi = (Provider) Class.forName("se.assembla.jce.provider.ms.MSProvider").newInstance(); Security.addProvider(mscapi); // init the key store KeyStore ks = KeyStore.getInstance("msks", "assembla"); ks.load(null, null); return addKeyStore(ks, "Microsoft CAPI Store", null); } catch (Exception e) { log.error("Error instantiating the MSCAPI provider: " + e.getMessage(), e); return -1; } } /* * public int initCryptoApi() throws KeyStoreException, * NoSuchAlgorithmException, CertificateException, IOException{ * * Provider mscapi = new sun.security.mscapi.SunMSCAPI(); * Security.addProvider(mscapi); * * KeyStore ks = KeyStore.getInstance("Windows-MY"); ks.load(null, null); * * return addKeyStore(ks, "CryptoAPI", null); } */ public int initPKCS11(PKCS11Configuration configuration, String kspassword) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { if (!isProviderAvailable(PKCS11_PROVIDER_TYPE)) { return -1; } Provider pkcs11 = createPKCS11Provider(configuration); Security.addProvider(pkcs11); // init the key store KeyStore ks = getPKCS11KeyStore(pkcs11.getName()); ks.load(null, kspassword == null ? null : kspassword.toCharArray()); return addKeyStore(ks, "PKCS#11: " + configuration.getName(), ""); // do not store pin code } private static Provider createPKCS11Provider(PKCS11Configuration configuration) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Provider pkcs11 = null; if (isSunPKCS11Provider()) { pkcs11 = createInstance(SUN_PKCS11_CANONICAL_CLASS_NAME, InputStream.class, configuration.toInpuStream()); } else if (isIbmPKCS11Provider()) { pkcs11 = createInstance(IBM_PKCS11_CONONICAL_CLASS_NAME, BufferedReader.class, new BufferedReader( new InputStreamReader(configuration.toInpuStream()))); } return pkcs11; } private static Provider createInstance(String name, Class<?> paramClass, Object param) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> instanceClass = Class.forName(name); Constructor<?> c = instanceClass.getConstructor(new Class<?>[] { paramClass }); return (Provider) c.newInstance(new Object[] { param }); } private static boolean isSunPKCS11Provider() { try { Class.forName(SUN_PKCS11_CANONICAL_CLASS_NAME); return true; } catch (Throwable ignore) { } return false; } private static boolean isIbmPKCS11Provider() { try { Class.forName(IBM_PKCS11_CONONICAL_CLASS_NAME); return true; } catch (Throwable ignore) { } return false; } private static KeyStore getPKCS11KeyStore(String providerName) throws KeyStoreException { String keyStoreType = SUN_PKCS11_KEYSTORE_TYPE; if (isIbmPKCS11Provider()) { keyStoreType = IBM_PKCS11_KEYSTORE_TYPE; } return KeyStore.getInstance(keyStoreType, Security.getProvider(providerName)); } public int loadPKCS12Certificate(String filename, String ksPassword) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { // Get Filename File file = new File(filename); if (!file.exists()) { throw new FileNotFoundException(filename + " could not be found"); } String name = file.getName(); // Open the file try (InputStream is = new FileInputStream(file)) { // create the keystore KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(is, ksPassword == null ? null : ksPassword.toCharArray()); return addKeyStore(ks, "PKCS#12: " + name, ksPassword); } } public boolean unlockKeyWithDefaultPassword(int keystoreIndex, int aliasIndex) throws KeyManagementException, KeyStoreException { return unlockKey(keystoreIndex, aliasIndex, getKeyStorePassword(keystoreIndex)); } public boolean unlockKey(int keystoreIndex, int aliasIndex, String keyPassword) throws KeyStoreException, KeyManagementException { KeyStore ks = _keyStores.get(keystoreIndex); String alias = getAliasAt(keystoreIndex, aliasIndex); AliasKeyManager akm = new AliasKeyManager(ks, alias, keyPassword); try { akm.getPrivateKey(alias).toString(); } catch (NullPointerException ex) { log.error("Could not get private key: " + ex.getMessage(), ex); return false; } String fingerprint = getFingerPrint(getCertificate(keystoreIndex, aliasIndex)); if (fingerprint == null) { log.info("No fingerprint found"); return false; } SSLContext sc; try { sc = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException nsao) { log.error("Could not get an instance of the SSL algorithm: " + nsao.getMessage(), nsao); return false; } sc.init(new KeyManager[] { akm }, _trustAllCerts, new SecureRandom()); String key = fingerprint; if (key.indexOf(" ") > 0) { key = key.substring(0, key.indexOf(" ")); } _contextMaps.put(key, sc); log.info("Key has been unlocked."); return true; } public void invalidateSessions() { invalidateSession(_noClientCertContext); Iterator<String> it = _contextMaps.keySet().iterator(); while (it.hasNext()) { invalidateSession(_contextMaps.get(it.next())); } } private void invalidateSession(SSLContext sc) { SSLSessionContext sslsc = sc.getClientSessionContext(); if (sslsc != null) { int timeout = sslsc.getSessionTimeout(); // force sessions to be timed out sslsc.setSessionTimeout(1); sslsc.setSessionTimeout(timeout); } sslsc = sc.getServerSessionContext(); if (sslsc != null) { int timeout = sslsc.getSessionTimeout(); // force sessions to be timed out sslsc.setSessionTimeout(1); sslsc.setSessionTimeout(timeout); } } public SSLContext getSSLContext(String fingerprint) { log.info("Requested SSLContext for " + fingerprint); if (fingerprint == null || fingerprint.equals("none")) { return _noClientCertContext; } if (fingerprint.indexOf(" ") > 0) { fingerprint = fingerprint.substring(0, fingerprint.indexOf(" ")); } return _contextMaps.get(fingerprint); } }
apache-2.0
akiskip/KoDeMat-Collaboration-Platform-Application
KoDeMat_TouchScreen/src/kodemat/touch/visu/editor/nifty/panels/ViewCube.java
12097
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package kodemat.touch.visu.editor.nifty.panels; import com.jme3.app.Application; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.builder.EffectBuilder; import de.lessvoid.nifty.builder.ElementBuilder; import de.lessvoid.nifty.builder.HoverEffectBuilder; import de.lessvoid.nifty.builder.ImageBuilder; import de.lessvoid.nifty.builder.PanelBuilder; import de.lessvoid.nifty.controls.AbstractController; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.tools.SizeValue; import de.lessvoid.xml.xpp3.Attributes; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import kodemat.visu.appstates.NiftyGuiAppState; import kodemat.visu.editor.IEditor; import kodemat.touch.visu.editor.TouchVisuEditor; import static kodemat.touch.visu.editor.nifty.panels.TouchImportModelPanel.guiAppState; import kodemat.visu.editor.VisuEditor; import kodemat.visu.editor.nifty.panels.IEditorPanel; import org.openide.util.Exceptions; /** * * @author OzgeA */ public class ViewCube implements IEditorPanel { static NiftyGuiAppState guiAppState; private Element editorPanel; private ViewPanelController viewPanelController; final Nifty nifty; public ViewCube(Application visuClient) { this.guiAppState = visuClient.getStateManager().getState(NiftyGuiAppState.class); nifty = guiAppState.getNifty(); } @Override public void layout(IEditor basicEditor) { final Screen screen = nifty.getScreen("hidden"); Element toolbar = screen.findElementByName("view-cube-panel"); toolbar.setConstraintX(SizeValue.percent(85)); toolbar.setConstraintY(SizeValue.percent(0)); PanelBuilder pb = new PanelBuilder("model-panel") { { height("30%"); childLayoutHorizontal(); valignTop(); controller(ViewPanelController.class.getName()); } }; editorPanel = pb.build(nifty, screen, toolbar); viewPanelController = editorPanel.getControl(ViewPanelController.class); viewPanelController.setBasicEditor((TouchVisuEditor) basicEditor); PanelBuilder pb2 = new PanelBuilder("small-icons-panel") { { height("30%"); childLayoutHorizontal(); valignCenter(); controller(ViewPanelController.class.getName()); } }; Element middlePanel = pb2.build(nifty, screen, toolbar); ViewPanelController middlePanelController = middlePanel.getControl(ViewPanelController.class); middlePanelController.setBasicEditor((TouchVisuEditor) basicEditor); PanelBuilder pb3 = new PanelBuilder("small-icons-panel") { { height("30%"); childLayoutHorizontal(); valignBottom(); controller(ViewPanelController.class.getName()); } }; Element bottomPanel = pb3.build(nifty, screen, toolbar); ViewPanelController bottomPanelController = bottomPanel.getControl(ViewPanelController.class); bottomPanelController.setBasicEditor((TouchVisuEditor) basicEditor); new ImageBuilder("Back") { { paddingRight("5px"); width("30"); height("30"); filename("Interface/Buttons/back.png"); visibleToMouse(true); interactOnClick("viewBack()"); onClickEffect(new EffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/back.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/back.png"); } }); onHoverEffect(new HoverEffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/back.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/back.png"); } }); onHoverEffect(new HoverEffectBuilder("hint") { { getAttributes().setAttribute("hintText", "Back"); } }); } }.build(nifty, screen, editorPanel); new ImageBuilder("Left") { { paddingRight("5px"); width("30"); height("30"); filename("Interface/Buttons/left.png"); visibleToMouse(true); interactOnClick("viewLeft()"); onClickEffect(new EffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/left.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/left.png"); } }); onHoverEffect(new HoverEffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/left.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/left.png"); } }); onHoverEffect(new HoverEffectBuilder("hint") { { getAttributes().setAttribute("hintText", "Left"); } }); } }.build(nifty, screen, middlePanel); new ImageBuilder("Top") { { paddingRight("5px"); width("30"); height("30"); filename("Interface/Buttons/top.png"); visibleToMouse(true); interactOnClick("viewTop()"); onClickEffect(new EffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/top.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/top.png"); } }); onHoverEffect(new HoverEffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/top.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/top.png"); } }); onHoverEffect(new HoverEffectBuilder("hint") { { getAttributes().setAttribute("hintText", "Top"); } }); } }.build(nifty, screen, middlePanel); new ImageBuilder("Left") { { paddingRight("5px"); width("30"); height("30"); filename("Interface/Buttons/right.png"); visibleToMouse(true); interactOnClick("viewRight()"); onClickEffect(new EffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/right.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/right.png"); } }); onHoverEffect(new HoverEffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/right.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/right.png"); } }); onHoverEffect(new HoverEffectBuilder("hint") { { getAttributes().setAttribute("hintText", "Right"); } }); } }.build(nifty, screen, middlePanel); new ImageBuilder("Back") { { paddingRight("5px"); width("30"); height("30"); filename("Interface/Buttons/front.png"); visibleToMouse(true); interactOnClick("viewOriginal()"); onClickEffect(new EffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/front.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/front.png"); } }); onHoverEffect(new HoverEffectBuilder("changeImage") { { getAttributes().setAttribute("active", "Interface/Buttons/front.png"); getAttributes().setAttribute("inactive", "Interface/Buttons/front.png"); } }); onHoverEffect(new HoverEffectBuilder("hint") { { getAttributes().setAttribute("hintText", ""); } }); } }.build(nifty, screen, bottomPanel); toolbar.layoutElements(); } public static class ViewPanelController extends AbstractController { private TouchVisuEditor basicEditor; @Override public void bind(Nifty nifty, Screen screen, Element element, Properties parameter, Attributes controlDefinitionAttributes) { } @Override public void onStartScreen() { } @Override public boolean inputEvent(NiftyInputEvent inputEvent) { return false; } /** * @return the basicEditor */ public TouchVisuEditor getBasicEditor() { return basicEditor; } /** * @param basicEditor the basicEditor to set */ public void setBasicEditor(TouchVisuEditor basicEditor) { this.basicEditor = basicEditor; } public void viewBack() { basicEditor.getHazelcastAppState().threadPool.execute(new Runnable() { public void run() { basicEditor.getCammeraControllAppState().getCameraControllerT().viewBack(); } }); } public void viewOriginal() { basicEditor.getHazelcastAppState().threadPool.execute(new Runnable() { public void run() { basicEditor.getCammeraControllAppState().getCameraControllerT().viewOriginal(); } }); } public void viewLeft() { basicEditor.getHazelcastAppState().threadPool.execute(new Runnable() { public void run() { basicEditor.getCammeraControllAppState().getCameraControllerT().viewLeft(); } }); } public void viewRight() { basicEditor.getHazelcastAppState().threadPool.execute(new Runnable() { public void run() { basicEditor.getCammeraControllAppState().getCameraControllerT().viewRight(); } }); } public void viewTop() { basicEditor.getHazelcastAppState().threadPool.execute(new Runnable() { public void run() { basicEditor.getCammeraControllAppState().getCameraControllerT().viewTop(); } }); } } }
apache-2.0
zhoufan2013/TRIS_Platform
server/src/main/java/com/ai/tris/server/dao/interfaces/ICommonDao.java
433
package com.ai.tris.server.dao.interfaces; import com.ai.tris.server.orm.impl.ClientAppInfoBean; import java.util.List; /** * Common Database Access Object. * <p/> * Created by Sam on 2015/6/9. */ public interface ICommonDao { void querySomething(); /** * get all client app information from tris.client_app_info */ List<ClientAppInfoBean> getTrisClientAppInfo(); void insertSomething(long id); }
apache-2.0
grasscrm/gdesigner
poem-jvm/src/java/org/b3mn/poem/handler/RatingHandler.java
2930
package org.b3mn.poem.handler; import java.util.Collection; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.b3mn.poem.Identity; import org.b3mn.poem.Persistance; import org.b3mn.poem.business.Model; import org.b3mn.poem.util.AccessRight; import org.b3mn.poem.util.FilterMethod; import org.b3mn.poem.util.HandlerWithModelContext; import org.b3mn.poem.util.RestrictAccess; import org.b3mn.poem.util.SortMethod; import org.json.JSONObject; @HandlerWithModelContext(uri="/rating") public class RatingHandler extends HandlerBase { public void writeRating(Model model, HttpServletResponse response, Identity subject, Identity object) throws Exception { JSONObject rating = new JSONObject(); rating.put("userScore", model.getUserScore(subject)); rating.put("totalScore", model.getTotalScore()); rating.put("totalVotes", model.getTotalVotes()); response.getWriter().println(rating.toString()); } @Override @RestrictAccess(AccessRight.READ) public void doGet(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws Exception { Model model = new Model(object); writeRating(model, response, subject, object); } @Override @RestrictAccess(AccessRight.READ) public void doPost(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws Exception { Model model = new Model(object); String userScore = request.getParameter("userScore"); if (userScore != null) model.setUserScore(subject, Integer.parseInt(userScore)); writeRating(model, response, subject, object); } @SuppressWarnings("unchecked") @SortMethod(SortName="rating") public static List<String> sortByRating(Identity subject) { List<String> results = Persistance.getSession() .createSQLQuery("SELECT access.object_name FROM " + "access LEFT JOIN model_rating ON access.object_id=model_rating.object_id " + "WHERE (access.subject_name='public' OR access.subject_id=:subject_id) " + "GROUP BY access.object_name " + "ORDER BY avg(model_rating.score) DESC NULLS LAST") .setInteger("subject_id", subject.getId()) .list(); Persistance.commit(); return results; } @SuppressWarnings({ "unchecked" }) @FilterMethod(FilterName="rating") public static Collection<String> filterByRating(Identity subject, String params) { float score = Float.parseFloat(params); List<String> results = Persistance.getSession() .createSQLQuery("SELECT access.object_name FROM access, model_rating " + "WHERE (access.subject_name='public' OR access.subject_id=:subject_id) AND access.object_id=model_rating.object_id " + "GROUP BY access.object_name " + "HAVING avg(model_rating.score) >= :score") .setFloat("score", score) .setInteger("subject_id", subject.getId()) .list(); Persistance.commit(); return results; } }
apache-2.0
gravitee-io/graviteeio-access-management
gravitee-am-repository/gravitee-am-repository-tests/src/test/java/io/gravitee/am/repository/management/api/GroupRepositoryTest.java
13131
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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.gravitee.am.repository.management.api; import io.gravitee.am.model.Group; import io.gravitee.am.model.ReferenceType; import io.gravitee.am.model.common.Page; import io.gravitee.am.repository.management.AbstractManagementTest; import io.reactivex.observers.TestObserver; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.*; import java.util.stream.Collectors; import static org.junit.Assert.*; /** * @author Eric LELEU (eric.leleu at graviteesource.com) * @author GraviteeSource Team */ public class GroupRepositoryTest extends AbstractManagementTest { public static final String DOMAIN_ID = "DOMAIN_ID1"; @Autowired protected GroupRepository repository; @Test public void shouldCreateGroup() { Group group = buildGroup(); TestObserver<Group> testObserver = repository.create(group).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId() != null); assertEqualsTo(group, testObserver); } private Group buildGroup() { Group group = new Group(); String random = UUID.randomUUID().toString(); group.setDescription("Description"+random); group.setName("name"+random); group.setReferenceId("ref"+random); group.setReferenceType(ReferenceType.DOMAIN); group.setCreatedAt(new Date()); group.setUpdatedAt(new Date()); group.setRoles(Arrays.asList("r1"+random, "r2"+random)); List<String> members = new ArrayList<>(); members.add("m1"+random); members.add("m2"+random); group.setMembers(members); return group; } private void assertEqualsTo(Group group, TestObserver<Group> testObserver) { testObserver.assertValue(g -> g.getName().equals(group.getName())); testObserver.assertValue(g -> g.getDescription().equals(group.getDescription())); testObserver.assertValue(g -> g.getReferenceId().equals(group.getReferenceId())); testObserver.assertValue(g -> g.getReferenceType().equals(group.getReferenceType())); testObserver.assertValue(g -> g.getMembers().size() == group.getMembers().size()); testObserver.assertValue(g -> g.getMembers().containsAll(group.getMembers())); testObserver.assertValue(g -> g.getRoles().size() == group.getRoles().size()); testObserver.assertValue(g -> g.getRoles().containsAll(group.getRoles())); } @Test public void shouldFindById() { Group group = buildGroup(); Group createdGroup = repository.create(group).blockingGet(); TestObserver<Group> testObserver = repository.findById(createdGroup.getId()).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId().equals(createdGroup.getId())); assertEqualsTo(group, testObserver); } @Test public void shouldFindById_WithRef() { Group group = buildGroup(); Group createdGroup = repository.create(group).blockingGet(); TestObserver<Group> testObserver = repository.findById(createdGroup.getReferenceType(), createdGroup.getReferenceId(), createdGroup.getId()).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId().equals(createdGroup.getId())); assertEqualsTo(group, testObserver); } @Test public void shouldUpdate() { Group group = buildGroup(); Group createdGroup = repository.create(group).blockingGet(); Group toUpdate = buildGroup(); toUpdate.setId(createdGroup.getId()); // update and check response final TestObserver<Group> testUpdate = repository.update(toUpdate).test(); testUpdate.awaitTerminalEvent(); testUpdate.assertComplete(); testUpdate.assertNoErrors(); testUpdate.assertValue(g -> g.getId().equals(toUpdate.getId())); assertEqualsTo(toUpdate, testUpdate); // validate the update using findById TestObserver<Group> testObserver = repository.findById(toUpdate.getId()).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId().equals(toUpdate.getId())); assertEqualsTo(toUpdate, testObserver); } @Test public void shouldDelete() { Group group = buildGroup(); Group createdGroup = repository.create(group).blockingGet(); // validate the creation using findById TestObserver<Group> testObserver = repository.findById(createdGroup.getId()).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId().equals(createdGroup.getId())); final TestObserver<Void> testDelete = repository.delete(createdGroup.getId()).test(); testDelete.awaitTerminalEvent(); testDelete.assertComplete(); testDelete.assertNoErrors(); final Group existAfterDelete = repository.findById(createdGroup.getId()).blockingGet(); assertNull(existAfterDelete); } @Test public void shouldFindByMember() { Group group1 = buildGroup(); Group createdGroup1 = repository.create(group1).blockingGet(); final String member1 = group1.getMembers().get(0); final String member2 = group1.getMembers().get(1); Group group2 = buildGroup(); // create a second group to add the same member as group 1 group2.getMembers().add(member1); Group createdGroup2 = repository.create(group2).blockingGet(); TestObserver<List<Group>> testObserver = repository.findByMember(member1).toList().test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.size() == 2); testObserver.assertValue(g -> g.stream().map(Group::getId).collect(Collectors.toSet()).containsAll(Arrays.asList(createdGroup1.getId(), createdGroup2.getId()))); testObserver = repository.findByMember(member2).toList().test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.size() == 1); testObserver.assertValue(g -> g.get(0).getId().equals(createdGroup1.getId())); } @Test public void shouldFindAll() { List<Group> emptyList = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID).toList().blockingGet(); assertNotNull(emptyList); assertTrue(emptyList.isEmpty()); final int loop = 10; for (int i = 0; i < loop; ++i) { // build 10 group with random domain repository.create(buildGroup()).blockingGet(); } for (int i = 0; i < loop; ++i) { // build 10 group with DOMAIN_ID final Group item = buildGroup(); item.setReferenceId(DOMAIN_ID); repository.create(item).blockingGet(); } List<Group> groupOfDomain = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID).toList().blockingGet(); assertNotNull(groupOfDomain); assertEquals(loop, groupOfDomain.size()); assertEquals(loop, groupOfDomain.stream().filter(g -> g.getReferenceId().equals(DOMAIN_ID) && g.getReferenceType().equals(ReferenceType.DOMAIN)).count()); groupOfDomain = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID).toList().blockingGet(); assertNotNull(groupOfDomain); assertEquals(loop, groupOfDomain.size()); assertEquals(loop, groupOfDomain.stream().filter(g -> g.getReferenceId().equals(DOMAIN_ID) && g.getReferenceType().equals(ReferenceType.DOMAIN)).count()); } @Test public void shouldFindAll_WithPage() { List<Group> emptyList = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID).toList().blockingGet(); assertNotNull(emptyList); assertTrue(emptyList.isEmpty()); final int loop = 10; for (int i = 0; i < loop; ++i) { // build 10 group with random domain repository.create(buildGroup()).blockingGet(); } for (int i = 0; i < loop; ++i) { // build 10 group with DOMAIN_ID final Group item = buildGroup(); item.setReferenceId(DOMAIN_ID); repository.create(item).blockingGet(); } Page<Group> groupOfDomain = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID, 0, 20).blockingGet(); assertNotNull(groupOfDomain); assertEquals(0, groupOfDomain.getCurrentPage()); assertEquals(loop, groupOfDomain.getTotalCount()); assertEquals(loop, groupOfDomain.getData().stream() .filter(g -> g.getReferenceId().equals(DOMAIN_ID) && g.getReferenceType().equals(ReferenceType.DOMAIN)).count()); final Collection<Group> data = groupOfDomain.getData(); groupOfDomain = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID, 0, 5).blockingGet(); assertNotNull(groupOfDomain); assertEquals(loop, groupOfDomain.getTotalCount()); assertEquals(0, groupOfDomain.getCurrentPage()); assertEquals(5, groupOfDomain.getData().stream() .filter(g -> g.getReferenceId().equals(DOMAIN_ID) && g.getReferenceType().equals(ReferenceType.DOMAIN)).count()); final Collection<Group> data1 = groupOfDomain.getData(); groupOfDomain = repository.findAll(ReferenceType.DOMAIN, DOMAIN_ID, 1, 5).blockingGet(); assertNotNull(groupOfDomain); assertEquals(loop, groupOfDomain.getTotalCount()); assertEquals(1, groupOfDomain.getCurrentPage()); assertEquals(5, groupOfDomain.getData().stream() .filter(g -> g.getReferenceId().equals(DOMAIN_ID) && g.getReferenceType().equals(ReferenceType.DOMAIN)).count()); final Collection<Group> data2 = groupOfDomain.getData(); Set<String> pagedData = new HashSet<>(); pagedData.addAll(data1.stream().map(Group::getId).collect(Collectors.toSet())); pagedData.addAll(data2.stream().map(Group::getId).collect(Collectors.toSet())); // check that all group are different assertTrue(data.stream().map(Group::getId).collect(Collectors.toSet()).containsAll(pagedData)); } @Test public void shouldFindIdsIn() { final int loop = 10; List<String> ids = new ArrayList<>(); for (int i = 0; i < loop; ++i) { // build 10 group with random domain Group createdGroup = repository.create(buildGroup()).blockingGet(); if (i %2 == 0) { ids.add(createdGroup.getId()); } } final TestObserver<List<Group>> testObserver = repository.findByIdIn(ids).toList().test(); testObserver.awaitTerminalEvent(); testObserver.assertNoErrors(); testObserver.assertValue(lg -> lg.size() == ids.size()); testObserver.assertValue(lg -> lg.stream().map(Group::getId).collect(Collectors.toList()).containsAll(ids)); } @Test public void shouldFindByName() { Group group = buildGroup(); Group createdGroup = repository.create(group).blockingGet(); TestObserver<Group> testObserver = repository.findByName(group.getReferenceType(), group.getReferenceId(), group.getName()).test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue(g -> g.getId().equals(createdGroup.getId())); assertEqualsTo(group, testObserver); } @Test public void shouldFindByName_unknown() { Group group = buildGroup(); repository.create(group).blockingGet(); TestObserver<Group> testObserver = repository.findByName(group.getReferenceType(), group.getReferenceId(), "unknown").test(); testObserver.awaitTerminalEvent(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertNoValues(); } }
apache-2.0
arteam/metrics-jdbi3
src/test/java/com/github/arteam/jdbi3/strategies/AbstractStrategyTest.java
650
package com.github.arteam.jdbi3.strategies; import com.codahale.metrics.MetricRegistry; import org.jdbi.v3.core.statement.StatementContext; import org.junit.Before; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class AbstractStrategyTest { protected MetricRegistry registry = new MetricRegistry(); protected StatementContext ctx = mock(StatementContext.class); @Before public void setUp() throws Exception { when(ctx.getRawSql()).thenReturn("SELECT 1"); } protected long getTimerMaxValue(String name) { return registry.timer(name).getSnapshot().getMax(); } }
apache-2.0
indraneelr/progbook
src/test/java/com/progbook/resource/AnswerResourceTest.java
4695
package com.progbook.resource; import com.fasterxml.jackson.core.JsonProcessingException; import com.ninja_squad.dbsetup.DbSetup; import com.ninja_squad.dbsetup.DbSetupTracker; import com.ninja_squad.dbsetup.destination.DataSourceDestination; import com.progbook.Application; import com.progbook.persistence.CommonDbOperations; import com.progbook.persistence.model.Answer; import com.progbook.persistence.model.Language; import com.progbook.persistence.model.Person; import com.progbook.persistence.model.Question; import com.progbook.representation.command.AnswerSaveRepresentation; import com.progbook.representation.command.RelatedEntity; import com.progbook.representation.query.AnswerRepresentation; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import javax.sql.DataSource; import java.net.URL; import java.util.*; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @WebIntegrationTest("server.port:9090") public class AnswerResourceTest { private URL base; private RestTemplate template; @Autowired private DataSource dataSource; static DbSetupTracker dbSetupTracker = new DbSetupTracker(); @Before public void setUp() throws Exception { this.base = new URL("http://localhost:9090/"); template = new TestRestTemplate(); // this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), CommonDbOperations.LOAD_STARTER_DATASET); dbSetupTracker.launchIfNecessary(dbSetup); } @Test public void shouldGetAnswersByQuestionUuid(){ dbSetupTracker.skipNextLaunch(); Map<String,String> queryParams = new HashMap<>(); queryParams.put("question", "question-uuid-100"); ResponseEntity<Collection> answerResponseEntity = template.getForEntity(this.base + "/answers?question={question}", Collection.class, queryParams); Collection<AnswerRepresentation> answers = answerResponseEntity.getBody(); assertThat(answers.size(), is(3)); } @Test public void shouldGetAnswersByQuestionAndLanguage(){ dbSetupTracker.skipNextLaunch(); Map<String,String> queryParams = new HashMap<>(); queryParams.put("question", "question-uuid-100"); queryParams.put("language", "java"); ResponseEntity<Collection> answerResponseEntity = template.getForEntity(this.base + "/answers?question={question}&language={language}", Collection.class, queryParams); Collection<LinkedHashMap<String,Object>> answers = answerResponseEntity.getBody(); assertThat(answers.size(),is(1)); assertThat(answers.iterator().next().get("id"), CoreMatchers.<Object>is(101)); } @Test public void shouldGetAnswerByUuid(){ } @Test public void shouldSaveAnswer() throws JsonProcessingException { ResponseEntity<AnswerRepresentation> answerResponseEntity = template.postForEntity(this.base+"/answers", answerToSave(), AnswerRepresentation.class); assertTrue(answerResponseEntity.getStatusCode().is2xxSuccessful()); assertThat(answerResponseEntity.getBody().getId(), Matchers.greaterThan(0L)); } private AnswerSaveRepresentation answerToSave() throws JsonProcessingException { AnswerSaveRepresentation answer = new AnswerSaveRepresentation(); answer.setContent("This is a big answer, elaborating the question - how to save a question"); answer.setLanguage(new RelatedEntity(1L)); answer.setQuestion(new RelatedEntity(100L)); answer.setCreator(new RelatedEntity(1L)); return answer; } private Answer answerToSave2() throws JsonProcessingException { Answer answer = new Answer(); answer.setContent("This is a big answer, elaborating the question - how to save a question"); answer.setLanguage(new Language(1L)); answer.setQuestion(new Question(100L)); answer.setCreator(new Person(1L)); return answer; } }
apache-2.0
GoogleCloudPlatform/jenkins-gcr-plugin
src/main/java/com/google/jenkins/plugins/containersecurity/client/ClientUtil.java
5295
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.jenkins.plugins.containersecurity.client; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.domains.DomainRequirement; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.http.HttpTransport; import com.google.cloud.graphite.platforms.plugin.client.ClientFactory; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.jenkins.plugins.credentials.oauth.GoogleOAuth2Credentials; import com.google.jenkins.plugins.credentials.oauth.GoogleRobotCredentials; import hudson.AbortException; import hudson.model.ItemGroup; import hudson.security.ACL; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.List; import java.util.Optional; import lombok.NonNull; /** * Common utility methods for generating a {@link ClientFactory} that can be used to generate * clients. */ public class ClientUtil { private static final String APPLICATION_NAME = "jenkins-google-container-security"; /** * Creates a {@link ClientFactory} for generating the GCP API clients. * * @param itemGroup The Jenkins context to use for retrieving the credentials. * @param domainRequirements A list of domain requirements. * @param credentialsId The ID of the credentials to use for generating clients. * @param transport An {@link Optional} parameter that specifies the {@link HttpTransport} to use. * A default will be used if unspecified. * @return A {@link ClientFactory} to get clients. * @throws AbortException If there was an error initializing the ClientFactory. */ public static ClientFactory getClientFactory( @NonNull ItemGroup itemGroup, @NonNull ImmutableList<DomainRequirement> domainRequirements, @NonNull String credentialsId, @NonNull Optional<HttpTransport> transport) throws AbortException { Preconditions.checkArgument( !credentialsId.isEmpty(), Messages.ClientFactory_CredentialsIdRequired()); ClientFactory clientFactory; try { GoogleRobotCredentials robotCreds = getRobotCredentials(itemGroup, domainRequirements, credentialsId); Credential googleCredential = getGoogleCredential(robotCreds); clientFactory = new ClientFactory(transport, googleCredential, APPLICATION_NAME); } catch (IOException | GeneralSecurityException ex) { throw new AbortException(Messages.ClientFactory_FailedToInitializeHTTPTransport(ex)); } return clientFactory; } /** * Creates a {@link ClientFactory} for generating the GCP API clients. * * @param itemGroup The Jenkins context to use for retrieving the credentials. * @param credentialsId The ID of the credentials to use for generating clients. * @return A {@link ClientFactory} to get clients. * @throws AbortException If there was an error initializing the ClientFactory. */ public static ClientFactory getClientFactory(ItemGroup itemGroup, String credentialsId) throws AbortException { return getClientFactory(itemGroup, ImmutableList.of(), credentialsId, Optional.empty()); } /** * Retrieves the {@link GoogleRobotCredentials} specified by the provided credentialsId. * * @param itemGroup The Jenkins context to use for retrieving the credentials. * @param domainRequirements A list of domain requirements. * @param credentialsId The ID of the credentials to retrieve. * @return The {@link GoogleRobotCredentials} with the provided ID. * @throws AbortException If there was an error retrieving the credentials. */ public static GoogleRobotCredentials getRobotCredentials( @NonNull ItemGroup itemGroup, @NonNull List<DomainRequirement> domainRequirements, @NonNull String credentialsId) throws AbortException { Preconditions.checkArgument(!credentialsId.isEmpty()); GoogleOAuth2Credentials credentials = CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials( GoogleOAuth2Credentials.class, itemGroup, ACL.SYSTEM, domainRequirements), CredentialsMatchers.withId(credentialsId)); if (!(credentials instanceof GoogleRobotCredentials)) { throw new AbortException(Messages.ClientFactory_FailedToRetrieveCredentials(credentialsId)); } return (GoogleRobotCredentials) credentials; } private static Credential getGoogleCredential(GoogleRobotCredentials credentials) throws GeneralSecurityException { return credentials.getGoogleCredential(new ContainerSecurityScopeRequirement()); } }
apache-2.0
matobet/moVirt
moVirt/src/main/java/org/ovirt/mobile/movirt/util/Disposables.java
828
package org.ovirt.mobile.movirt.util; import java.util.ArrayList; import java.util.List; import io.reactivex.disposables.Disposable; public class Disposables { private final List<Disposable> disposables = new ArrayList<>(5); public Disposables add(Disposable disposable) { disposables.add(disposable); return this; } public void destroy() { for (Disposable disposable : disposables) { if (disposable != null && !disposable.isDisposed()) { disposable.dispose(); } } disposables.clear(); } public void destroyLastDisposable() { Disposable disposable = disposables.remove(disposables.size() - 1); if (disposable != null && !disposable.isDisposed()) { disposable.dispose(); } } }
apache-2.0
EvilMcJerkface/presto
presto-main/src/main/java/com/facebook/presto/execution/buffer/ArbitraryOutputBuffer.java
20308
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.execution.buffer; import com.facebook.presto.execution.Lifespan; import com.facebook.presto.execution.StateMachine; import com.facebook.presto.execution.StateMachine.StateChangeListener; import com.facebook.presto.execution.buffer.ClientBuffer.PagesSupplier; import com.facebook.presto.execution.buffer.OutputBuffers.OutputBufferId; import com.facebook.presto.memory.context.LocalMemoryContext; import com.facebook.presto.spi.page.SerializedPage; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.google.common.collect.Sets.SetView; import com.google.common.util.concurrent.ListenableFuture; import io.airlift.units.DataSize; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import java.util.function.Supplier; import static com.facebook.presto.execution.buffer.BufferState.FAILED; import static com.facebook.presto.execution.buffer.BufferState.FINISHED; import static com.facebook.presto.execution.buffer.BufferState.FLUSHING; import static com.facebook.presto.execution.buffer.BufferState.NO_MORE_BUFFERS; import static com.facebook.presto.execution.buffer.BufferState.NO_MORE_PAGES; import static com.facebook.presto.execution.buffer.BufferState.OPEN; import static com.facebook.presto.execution.buffer.OutputBuffers.BufferType.ARBITRARY; import static com.facebook.presto.execution.buffer.OutputBuffers.createInitialEmptyOutputBuffers; import static com.google.common.base.MoreObjects.toStringHelper; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; /** * A buffer that assigns pages to queues based on a first come, first served basis. */ public class ArbitraryOutputBuffer implements OutputBuffer { private final OutputBufferMemoryManager memoryManager; @GuardedBy("this") private OutputBuffers outputBuffers = createInitialEmptyOutputBuffers(ARBITRARY); private final MasterBuffer masterBuffer; @GuardedBy("this") private final ConcurrentMap<OutputBufferId, ClientBuffer> buffers = new ConcurrentHashMap<>(); // The index of the first client buffer that should be polled private final AtomicInteger nextClientBufferIndex = new AtomicInteger(0); private final StateMachine<BufferState> state; private final String taskInstanceId; private final AtomicLong totalPagesAdded = new AtomicLong(); private final AtomicLong totalRowsAdded = new AtomicLong(); private final ConcurrentMap<Lifespan, AtomicLong> outstandingPageCountPerLifespan = new ConcurrentHashMap<>(); private final Set<Lifespan> noMorePagesForLifespan = ConcurrentHashMap.newKeySet(); private volatile Consumer<Lifespan> lifespanCompletionCallback; public ArbitraryOutputBuffer( String taskInstanceId, StateMachine<BufferState> state, DataSize maxBufferSize, Supplier<LocalMemoryContext> systemMemoryContextSupplier, Executor notificationExecutor) { this.taskInstanceId = requireNonNull(taskInstanceId, "taskInstanceId is null"); this.state = requireNonNull(state, "state is null"); requireNonNull(maxBufferSize, "maxBufferSize is null"); checkArgument(maxBufferSize.toBytes() > 0, "maxBufferSize must be at least 1"); this.memoryManager = new OutputBufferMemoryManager( maxBufferSize.toBytes(), requireNonNull(systemMemoryContextSupplier, "systemMemoryContextSupplier is null"), requireNonNull(notificationExecutor, "notificationExecutor is null")); this.masterBuffer = new MasterBuffer(); } @Override public void addStateChangeListener(StateChangeListener<BufferState> stateChangeListener) { state.addStateChangeListener(stateChangeListener); } @Override public boolean isFinished() { return state.get() == FINISHED; } @Override public double getUtilization() { return memoryManager.getUtilization(); } @Override public boolean isOverutilized() { return (memoryManager.getUtilization() >= 0.5) || !state.get().canAddPages(); } @Override public OutputBufferInfo getInfo() { // // NOTE: this code must be lock free so we do not hang for state machine updates // // always get the state first before any other stats BufferState state = this.state.get(); // buffers it a concurrent collection so it is safe to access out side of guard // in this case we only want a snapshot of the current buffers @SuppressWarnings("FieldAccessNotGuarded") Collection<ClientBuffer> buffers = this.buffers.values(); int totalBufferedPages = masterBuffer.getBufferedPages(); ImmutableList.Builder<BufferInfo> infos = ImmutableList.builder(); for (ClientBuffer buffer : buffers) { BufferInfo bufferInfo = buffer.getInfo(); infos.add(bufferInfo); PageBufferInfo pageBufferInfo = bufferInfo.getPageBufferInfo(); totalBufferedPages += pageBufferInfo.getBufferedPages(); } return new OutputBufferInfo( "ARBITRARY", state, state.canAddBuffers(), state.canAddPages(), memoryManager.getBufferedBytes(), totalBufferedPages, totalRowsAdded.get(), totalPagesAdded.get(), infos.build()); } @Override public void setOutputBuffers(OutputBuffers newOutputBuffers) { checkState(!Thread.holdsLock(this), "Can not set output buffers while holding a lock on this"); requireNonNull(newOutputBuffers, "newOutputBuffers is null"); synchronized (this) { // ignore buffers added after query finishes, which can happen when a query is canceled // also ignore old versions, which is normal BufferState state = this.state.get(); if (state.isTerminal() || outputBuffers.getVersion() >= newOutputBuffers.getVersion()) { return; } // verify this is valid state change outputBuffers.checkValidTransition(newOutputBuffers); outputBuffers = newOutputBuffers; // add the new buffers for (OutputBufferId outputBufferId : outputBuffers.getBuffers().keySet()) { getBuffer(outputBufferId); } // Reset resume from position nextClientBufferIndex.set(0); // update state if no more buffers is set if (outputBuffers.isNoMoreBufferIds()) { this.state.compareAndSet(OPEN, NO_MORE_BUFFERS); this.state.compareAndSet(NO_MORE_PAGES, FLUSHING); } } if (!state.get().canAddBuffers()) { noMoreBuffers(); } checkFlushComplete(); } @Override public ListenableFuture<?> isFull() { return memoryManager.getBufferBlockedFuture(); } @Override public void registerLifespanCompletionCallback(Consumer<Lifespan> callback) { checkState(lifespanCompletionCallback == null, "lifespanCompletionCallback is already set"); this.lifespanCompletionCallback = requireNonNull(callback, "callback is null"); } @Override public void enqueue(Lifespan lifespan, List<SerializedPage> pages) { checkState(!Thread.holdsLock(this), "Can not enqueue pages while holding a lock on this"); requireNonNull(lifespan, "lifespan is null"); requireNonNull(pages, "page is null"); checkState(lifespanCompletionCallback != null, "lifespanCompletionCallback must be set before enqueueing data"); // ignore pages after "no more pages" is set // this can happen with a limit query if (!state.get().canAddPages() || noMorePagesForLifespan.contains(lifespan)) { return; } ImmutableList.Builder<SerializedPageReference> references = ImmutableList.builderWithExpectedSize(pages.size()); long bytesAdded = 0; long rowCount = 0; for (SerializedPage page : pages) { long retainedSize = page.getRetainedSizeInBytes(); bytesAdded += retainedSize; rowCount += page.getPositionCount(); // create page reference counts with an initial single reference references.add(new SerializedPageReference(page, 1, () -> dereferencePage(page, lifespan))); } List<SerializedPageReference> serializedPageReferences = references.build(); // reserve memory memoryManager.updateMemoryUsage(bytesAdded); // update stats totalRowsAdded.addAndGet(rowCount); totalPagesAdded.addAndGet(serializedPageReferences.size()); outstandingPageCountPerLifespan.computeIfAbsent(lifespan, ignored -> new AtomicLong()).addAndGet(serializedPageReferences.size()); // add pages to the buffer (this will increase the reference count by one) masterBuffer.addPages(serializedPageReferences); // process any pending reads from the client buffers List<ClientBuffer> buffers = safeGetBuffersSnapshot(); if (buffers.isEmpty()) { return; } // handle potential for racy update of next index and client buffers present int index = nextClientBufferIndex.get() % buffers.size(); for (int i = 0; i < buffers.size(); i++) { if (masterBuffer.isEmpty()) { // Resume from the current client buffer on the next iteration nextClientBufferIndex.set(index); break; } buffers.get(index).loadPagesIfNecessary(masterBuffer); index = (index + 1) % buffers.size(); } } @Override public void enqueue(Lifespan lifespan, int partition, List<SerializedPage> pages) { checkState(partition == 0, "Expected partition number to be zero"); enqueue(lifespan, pages); } @Override public ListenableFuture<BufferResult> get(OutputBufferId bufferId, long startingSequenceId, DataSize maxSize) { checkState(!Thread.holdsLock(this), "Can not get pages while holding a lock on this"); requireNonNull(bufferId, "bufferId is null"); checkArgument(maxSize.toBytes() > 0, "maxSize must be at least 1 byte"); return getBuffer(bufferId).getPages(startingSequenceId, maxSize, Optional.of(masterBuffer)); } @Override public void acknowledge(OutputBufferId bufferId, long sequenceId) { checkState(!Thread.holdsLock(this), "Can not acknowledge pages while holding a lock on this"); requireNonNull(bufferId, "bufferId is null"); getBuffer(bufferId).acknowledgePages(sequenceId); } @Override public void abort(OutputBufferId bufferId) { checkState(!Thread.holdsLock(this), "Can not abort while holding a lock on this"); requireNonNull(bufferId, "bufferId is null"); getBuffer(bufferId).destroy(); checkFlushComplete(); } @Override public void setNoMorePages() { checkState(!Thread.holdsLock(this), "Can not set no more pages while holding a lock on this"); state.compareAndSet(OPEN, NO_MORE_PAGES); state.compareAndSet(NO_MORE_BUFFERS, FLUSHING); memoryManager.setNoBlockOnFull(); masterBuffer.setNoMorePages(); // process any pending reads from the client buffers for (ClientBuffer clientBuffer : safeGetBuffersSnapshot()) { clientBuffer.loadPagesIfNecessary(masterBuffer); } checkFlushComplete(); } @Override public void destroy() { checkState(!Thread.holdsLock(this), "Can not destroy while holding a lock on this"); // ignore destroy if the buffer already in a terminal state. if (state.setIf(FINISHED, oldState -> !oldState.isTerminal())) { noMoreBuffers(); masterBuffer.destroy(); safeGetBuffersSnapshot().forEach(ClientBuffer::destroy); memoryManager.setNoBlockOnFull(); forceFreeMemory(); } } @Override public void fail() { // ignore fail if the buffer already in a terminal state. if (state.setIf(FAILED, oldState -> !oldState.isTerminal())) { memoryManager.setNoBlockOnFull(); forceFreeMemory(); // DO NOT destroy buffers or set no more pages. The coordinator manages the teardown of failed queries. } } @Override public void setNoMorePagesForLifespan(Lifespan lifespan) { requireNonNull(lifespan, "lifespan is null"); noMorePagesForLifespan.add(lifespan); } @Override public boolean isFinishedForLifespan(Lifespan lifespan) { if (!noMorePagesForLifespan.contains(lifespan)) { return false; } AtomicLong outstandingPageCount = outstandingPageCountPerLifespan.get(lifespan); return outstandingPageCount == null || outstandingPageCount.get() == 0; } @Override public long getPeakMemoryUsage() { return memoryManager.getPeakMemoryUsage(); } @VisibleForTesting void forceFreeMemory() { memoryManager.close(); } private synchronized ClientBuffer getBuffer(OutputBufferId id) { ClientBuffer buffer = buffers.get(id); if (buffer != null) { return buffer; } // NOTE: buffers are allowed to be created in the FINISHED state because destroy() can move to the finished state // without a clean "no-more-buffers" message from the scheduler. This happens with limit queries and is ok because // the buffer will be immediately destroyed. checkState(state.get().canAddBuffers() || !outputBuffers.isNoMoreBufferIds(), "No more buffers already set"); // NOTE: buffers are allowed to be created before they are explicitly declared by setOutputBuffers // When no-more-buffers is set, we verify that all created buffers have been declared buffer = new ClientBuffer(taskInstanceId, id); // buffer may have finished immediately before calling this method if (state.get() == FINISHED) { buffer.destroy(); } buffers.put(id, buffer); return buffer; } private synchronized List<ClientBuffer> safeGetBuffersSnapshot() { return ImmutableList.copyOf(this.buffers.values()); } private synchronized void noMoreBuffers() { if (outputBuffers.isNoMoreBufferIds()) { // verify all created buffers have been declared SetView<OutputBufferId> undeclaredCreatedBuffers = Sets.difference(buffers.keySet(), outputBuffers.getBuffers().keySet()); checkState(undeclaredCreatedBuffers.isEmpty(), "Final output buffers does not contain all created buffer ids: %s", undeclaredCreatedBuffers); } } @GuardedBy("this") private void checkFlushComplete() { // This buffer type assigns each page to a single, arbitrary reader, // so we don't need to wait for no-more-buffers to finish the buffer. // Any readers added after finish will simply receive no data. BufferState state = this.state.get(); if ((state == FLUSHING) || ((state == NO_MORE_PAGES) && masterBuffer.isEmpty())) { if (safeGetBuffersSnapshot().stream().allMatch(ClientBuffer::isDestroyed)) { destroy(); } } } @ThreadSafe private static class MasterBuffer implements PagesSupplier { @GuardedBy("this") private final LinkedList<SerializedPageReference> masterBuffer = new LinkedList<>(); @GuardedBy("this") private boolean noMorePages; private final AtomicInteger bufferedPages = new AtomicInteger(); public synchronized void addPages(List<SerializedPageReference> pages) { masterBuffer.addAll(pages); bufferedPages.set(masterBuffer.size()); } public synchronized boolean isEmpty() { return masterBuffer.isEmpty(); } @Override public synchronized boolean mayHaveMorePages() { return !noMorePages || !masterBuffer.isEmpty(); } public synchronized void setNoMorePages() { this.noMorePages = true; } @Override public synchronized List<SerializedPageReference> getPages(DataSize maxSize) { long maxBytes = maxSize.toBytes(); List<SerializedPageReference> pages = new ArrayList<>(); long bytesRemoved = 0; while (true) { SerializedPageReference page = masterBuffer.peek(); if (page == null) { break; } bytesRemoved += page.getRetainedSizeInBytes(); // break (and don't add) if this page would exceed the limit if (!pages.isEmpty() && bytesRemoved > maxBytes) { break; } // this should not happen since we have a lock checkState(masterBuffer.poll() == page, "Master buffer corrupted"); pages.add(page); } bufferedPages.set(masterBuffer.size()); return ImmutableList.copyOf(pages); } public void destroy() { checkState(!Thread.holdsLock(this), "Can not destroy master buffer while holding a lock on this"); List<SerializedPageReference> pages; synchronized (this) { pages = ImmutableList.copyOf(masterBuffer); masterBuffer.clear(); bufferedPages.set(0); } // dereference outside of synchronized to avoid making a callback while holding a lock pages.forEach(SerializedPageReference::dereferencePage); } public int getBufferedPages() { return bufferedPages.get(); } @Override public String toString() { return toStringHelper(this) .add("bufferedPages", bufferedPages.get()) .toString(); } } @VisibleForTesting OutputBufferMemoryManager getMemoryManager() { return memoryManager; } private void dereferencePage(SerializedPage pageSplit, Lifespan lifespan) { long outstandingPageCount = outstandingPageCountPerLifespan.get(lifespan).decrementAndGet(); if (outstandingPageCount == 0 && noMorePagesForLifespan.contains(lifespan)) { checkState(lifespanCompletionCallback != null, "lifespanCompletionCallback is not null"); lifespanCompletionCallback.accept(lifespan); } memoryManager.updateMemoryUsage(-pageSplit.getRetainedSizeInBytes()); } }
apache-2.0
MReichenbach/visitmeta
dataservice/src/main/java/de/hshannover/f4/trust/visitmeta/ifmap/PollResult.java
2331
/* * #%L * ===================================================== * _____ _ ____ _ _ _ _ * |_ _|_ __ _ _ ___| |_ / __ \| | | | ___ | | | | * | | | '__| | | / __| __|/ / _` | |_| |/ __|| |_| | * | | | | | |_| \__ \ |_| | (_| | _ |\__ \| _ | * |_| |_| \__,_|___/\__|\ \__,_|_| |_||___/|_| |_| * \____/ * * ===================================================== * * Hochschule Hannover * (University of Applied Sciences and Arts, Hannover) * Faculty IV, Dept. of Computer Science * Ricklinger Stadtweg 118, 30459 Hannover, Germany * * Email: trust@f4-i.fh-hannover.de * Website: http://trust.f4.hs-hannover.de/ * * This file is part of visitmeta-dataservice, version 0.5.0, * implemented by the Trust@HsH research group at the Hochschule Hannover. * %% * Copyright (C) 2012 - 2015 Trust@HsH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package de.hshannover.f4.trust.visitmeta.ifmap; import java.util.ArrayList; import java.util.List; /** * Encapsulates the result of one if-MAP update */ public class PollResult { private final List<ResultItem> mResults; public PollResult(List<ResultItem> results) { mResults = results; } public List<ResultItem> getResults() { return mResults; } @Deprecated public List<ResultItem> getUpdates() { List<ResultItem> tmp = new ArrayList<ResultItem>(); for(ResultItem item : mResults) { if (item.getType() == ResultItemTypeEnum.UPDATE) { tmp.add(item); } } return tmp; } @Deprecated public List<ResultItem> getDeletes() { List<ResultItem> tmp = new ArrayList<ResultItem>(); for(ResultItem item : mResults) { if (item.getType() == ResultItemTypeEnum.DELETE) { tmp.add(item); } } return tmp; } }
apache-2.0
gbecares/bdt
src/main/java/com/stratio/qa/utils/CassandraQueryUtils.java
4153
/* * Copyright (C) 2014 Stratio (http://stratio.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stratio.qa.utils; import java.util.ArrayList; import java.util.Map; public class CassandraQueryUtils { public String insertData(String table, Map<String, Object> fields) { String query = "INSERT INTO " + table + " ("; for (int i = 0; i < fields.size() - 1; i++) { query += fields.keySet().toArray()[i] + ", "; } query += fields.keySet().toArray()[fields.size() - 1] + ") VALUES ("; for (int i = 0; i < fields.size() - 1; i++) { query += "" + fields.values().toArray()[i] + ", "; } query += "" + fields.values().toArray()[fields.size() - 1] + ");"; return query; } public String createTable(String table, Map<String, String> colums, ArrayList<String> primaryKey) { String query = "CREATE TABLE " + table + " ("; for (int i = 0; i < colums.size(); i++) { query += colums.keySet().toArray()[i] + " " + colums.values().toArray()[i] + ", "; } query = query + "PRIMARY KEY("; if (primaryKey.size() == 1) { query += primaryKey.get(0) + "));"; } else { for (int e = 0; e < primaryKey.size() - 1; e++) { query += primaryKey.get(e) + ", "; } query += primaryKey.get(primaryKey.size() - 1) + "));"; } return query; } public String useQuery(String keyspace) { return "USE " + keyspace + ";"; } public String createKeyspaceReplication(Map<String, String> replication) { StringBuilder result = new StringBuilder(); if (!replication.isEmpty()) { for (Map.Entry<String, String> entry : replication.entrySet()) { result.append(entry.getKey()).append(": ") .append(entry.getValue()).append(", "); } } return result.toString().substring(0, result.length() - 2); } public String createKeyspaceQuery(Boolean ifNotExists, String keyspaceName, String replication, String durableWrites) { String result = "CREATE KEYSPACE "; if (ifNotExists) { result = result + "IF NOT EXISTS "; } result = result + keyspaceName; if (!"".equals(replication) || !"".equals(durableWrites)) { result += " WITH "; if (!"".equals(replication)) { result += "REPLICATION = {" + replication + "}"; } if (!"".equals(durableWrites)) { if (!"".equals(replication)) { result += " AND "; } result += "durable_writes = " + durableWrites; } } result = result + ";"; return result; } public String dropKeyspaceQuery(Boolean ifExists, String keyspace) { String query = "DROP KEYSPACE "; if (ifExists) { query += "IF EXISTS "; } query = query + keyspace + ";"; return query; } public String dropTableQuery(Boolean ifExists, String table) { String query = "DROP TABLE "; if (ifExists) { query += "IF EXISTS "; } query = query + table + ";"; return query; } public String truncateTableQuery(Boolean ifExists, String table) { String query = "TRUNCATE TABLE "; if (ifExists) { query += "IF EXISTS "; } query = query + table + ";"; return query; } }
apache-2.0
bshp/midPoint
gui/admin-gui/src/main/java/com/evolveum/midpoint/web/boot/LdapSecurityConfig.java
3067
/* * Copyright (c) 2010-2017 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.web.boot; import com.evolveum.midpoint.model.api.authentication.MidPointLdapAuthenticationProvider; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.security.ldap.DefaultSpringSecurityContextSource; import org.springframework.security.ldap.authentication.BindAuthenticator; import org.springframework.security.ldap.search.FilterBasedLdapUserSearch; import org.springframework.security.ldap.userdetails.UserDetailsContextMapper; /** * Created by Viliam Repan (lazyman). */ @Profile("ldap") @Configuration public class LdapSecurityConfig { @Value("${auth.ldap.host}") private String ldapHost; @Value("${auth.ldap.manager:}") private String ldapUserDn; @Value("${auth.ldap.password:#{null}}") private String ldapUserPassword; @Value("${auth.ldap.dn.pattern:#{null}}") private String ldapDnPattern; @Value("${auth.ldap.search.pattern:#{null}}") private String ldapSearchPattern; @Value("${auth.ldap.search.subtree:true}") private boolean searchSubtree; @Bean public LdapContextSource contextSource() { DefaultSpringSecurityContextSource ctx = new DefaultSpringSecurityContextSource(ldapHost); ctx.setUserDn(ldapUserDn); ctx.setPassword(ldapUserPassword); return ctx; } @Bean public MidPointLdapAuthenticationProvider midPointAuthenticationProvider( @Qualifier("userDetailsService") UserDetailsContextMapper userDetailsContextMapper) { MidPointLdapAuthenticationProvider provider = new MidPointLdapAuthenticationProvider(bindAuthenticator()); provider.setUserDetailsContextMapper(userDetailsContextMapper); return provider; } @Bean public BindAuthenticator bindAuthenticator() { BindAuthenticator auth = new BindAuthenticator(contextSource()); if (StringUtils.isNotEmpty(ldapDnPattern)) { auth.setUserDnPatterns(new String[]{ldapDnPattern}); } if (StringUtils.isNotEmpty(ldapSearchPattern)) { auth.setUserSearch(userSearch()); } return auth; } @ConditionalOnProperty("auth.ldap.search.pattern") @Bean public FilterBasedLdapUserSearch userSearch() { FilterBasedLdapUserSearch search = new FilterBasedLdapUserSearch("", ldapSearchPattern, contextSource()); search.setSearchSubtree(searchSubtree); return search; } }
apache-2.0
apereo/cas
support/cas-server-support-events-redis/src/main/java/org/apereo/cas/support/events/redis/RedisCasEventRepository.java
4922
package org.apereo.cas.support.events.redis; import org.apereo.cas.redis.core.CasRedisTemplate; import org.apereo.cas.support.events.CasEventRepositoryFilter; import org.apereo.cas.support.events.dao.AbstractCasEventRepository; import org.apereo.cas.support.events.dao.CasEvent; import lombok.Getter; import lombok.ToString; import lombok.extern.slf4j.Slf4j; import lombok.val; import java.time.ZonedDateTime; import java.util.Objects; import java.util.stream.Stream; /** * This is {@link RedisCasEventRepository} that stores event data into a redis database. * * @author Misagh Moayyed * @since 6.4.0 */ @ToString @Getter @Slf4j public class RedisCasEventRepository extends AbstractCasEventRepository { private static final String KEY_SEPARATOR = ":"; private static final String CAS_PREFIX = RedisCasEventRepository.class.getSimpleName(); private final CasRedisTemplate<String, CasEvent> template; private final long scanCount; public RedisCasEventRepository(final CasEventRepositoryFilter eventRepositoryFilter, final CasRedisTemplate<String, CasEvent> redisTemplate, final long scanCount) { super(eventRepositoryFilter); this.template = redisTemplate; this.scanCount = scanCount; } private static String getKey(final String type, final String principal, final String timestamp) { return CAS_PREFIX + KEY_SEPARATOR + type + KEY_SEPARATOR + principal + KEY_SEPARATOR + timestamp; } @Override public Stream<? extends CasEvent> load() { val keys = getKeys("*", "*", "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull); } @Override public Stream<? extends CasEvent> load(final ZonedDateTime dateTime) { val keys = getKeys("*", "*", "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull) .filter(event -> event.getTimestamp() >= dateTime.toInstant().toEpochMilli()); } @Override public Stream<? extends CasEvent> getEventsOfTypeForPrincipal(final String type, final String principal) { val keys = getKeys(type, principal, "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull); } @Override public Stream<? extends CasEvent> getEventsOfTypeForPrincipal(final String type, final String principal, final ZonedDateTime dateTime) { val keys = getKeys(type, principal, "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull) .filter(event -> event.getTimestamp() >= dateTime.toInstant().toEpochMilli()); } @Override public Stream<? extends CasEvent> getEventsOfType(final String type) { val keys = getKeys(type, "*", "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull); } @Override public Stream<? extends CasEvent> getEventsOfType(final String type, final ZonedDateTime dateTime) { val keys = getKeys(type, "*", "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull) .filter(event -> event.getTimestamp() >= dateTime.toInstant().toEpochMilli()); } @Override public Stream<? extends CasEvent> getEventsForPrincipal(final String id) { val keys = getKeys("*", id, "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull); } @Override public Stream<? extends CasEvent> getEventsForPrincipal(final String principal, final ZonedDateTime dateTime) { val keys = getKeys("*", principal, "*"); return keys .map(key -> this.template.boundValueOps(key).get()) .filter(Objects::nonNull) .filter(event -> event.getTimestamp() >= dateTime.toInstant().toEpochMilli()); } @Override public CasEvent saveInternal(final CasEvent event) { val key = getKey(event.getType(), event.getPrincipalId(), String.valueOf(event.getTimestamp())); LOGGER.trace("Saving event record based on key [{}]", key); val ops = this.template.boundValueOps(key); ops.set(event); return event; } private Stream<String> getKeys(final String type, final String principal, final String timestamp) { val key = getKey(type, principal, timestamp); LOGGER.trace("Fetching records based on key [{}]", key); return template.keys(key, this.scanCount); } }
apache-2.0
dimagi/javarosa
javarosa/core/src/main/java/org/javarosa/core/model/instance/utils/FormLoadingUtils.java
1407
package org.javarosa.core.model.instance.utils; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.xml.ElementParser; import org.javarosa.xml.TreeElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; /** * Collection of static form loading methods * * @author Phillip Mates */ public class FormLoadingUtils { public static FormInstance loadFormInstance(String formFilepath) throws InvalidStructureException, IOException { TreeElement root = xmlToTreeElement(formFilepath); return new FormInstance(root, null); } public static TreeElement xmlToTreeElement(String xmlFilepath) throws InvalidStructureException, IOException { InputStream is = FormLoadingUtils.class.getResourceAsStream(xmlFilepath); TreeElementParser parser = new TreeElementParser(ElementParser.instantiateParser(is), 0, "instance"); try { return parser.parse(); } catch (XmlPullParserException e) { throw new IOException(e.getMessage()); } catch (UnfullfilledRequirementsException e) { throw new IOException(e.getMessage()); } } }
apache-2.0
alphallc/connectbot
src/org/alphallc/sshit/util/Encryptor.java
6172
/* * sshIt: simple, powerful, open-source SSH client for Android * Copyright 2014 Alpha LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.alphallc.sshit.util; /** * This class is from: * * Encryptor.java * Copyright 2008 Zach Scrivena * zachscrivena@gmail.com * http://zs.freeshell.org/ */ import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * Perform AES-128 encryption. */ public final class Encryptor { /** name of the character set to use for converting between characters and bytes */ private static final String CHARSET_NAME = "UTF-8"; /** random number generator algorithm */ private static final String RNG_ALGORITHM = "SHA1PRNG"; /** message digest algorithm (must be sufficiently long to provide the key and initialization vector) */ private static final String DIGEST_ALGORITHM = "SHA-256"; /** key algorithm (must be compatible with CIPHER_ALGORITHM) */ private static final String KEY_ALGORITHM = "AES"; /** cipher algorithm (must be compatible with KEY_ALGORITHM) */ private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; /** * Private constructor that should never be called. */ private Encryptor() {} /** * Encrypt the specified cleartext using the given password. * With the correct salt, number of iterations, and password, the decrypt() method reverses * the effect of this method. * This method generates and uses a random salt, and the user-specified number of iterations * and password to create a 16-byte secret key and 16-byte initialization vector. * The secret key and initialization vector are then used in the AES-128 cipher to encrypt * the given cleartext. * * @param salt * salt that was used in the encryption (to be populated) * @param iterations * number of iterations to use in salting * @param password * password to be used for encryption * @param cleartext * cleartext to be encrypted * @return * ciphertext * @throws Exception * on any error encountered in encryption */ public static byte[] encrypt( final byte[] salt, final int iterations, final String password, final byte[] cleartext) throws Exception { /* generate salt randomly */ SecureRandom.getInstance(RNG_ALGORITHM).nextBytes(salt); /* compute key and initialization vector */ final MessageDigest shaDigest = MessageDigest.getInstance(DIGEST_ALGORITHM); byte[] pw = password.getBytes(CHARSET_NAME); for (int i = 0; i < iterations; i++) { /* add salt */ final byte[] salted = new byte[pw.length + salt.length]; System.arraycopy(pw, 0, salted, 0, pw.length); System.arraycopy(salt, 0, salted, pw.length, salt.length); Arrays.fill(pw, (byte) 0x00); /* compute SHA-256 digest */ shaDigest.reset(); pw = shaDigest.digest(salted); Arrays.fill(salted, (byte) 0x00); } /* extract the 16-byte key and initialization vector from the SHA-256 digest */ final byte[] key = new byte[16]; final byte[] iv = new byte[16]; System.arraycopy(pw, 0, key, 0, 16); System.arraycopy(pw, 16, iv, 0, 16); Arrays.fill(pw, (byte) 0x00); /* perform AES-128 encryption */ final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init( Cipher.ENCRYPT_MODE, new SecretKeySpec(key, KEY_ALGORITHM), new IvParameterSpec(iv)); Arrays.fill(key, (byte) 0x00); Arrays.fill(iv, (byte) 0x00); return cipher.doFinal(cleartext); } /** * Decrypt the specified ciphertext using the given password. * With the correct salt, number of iterations, and password, this method reverses the effect * of the encrypt() method. * This method uses the user-specified salt, number of iterations, and password * to recreate the 16-byte secret key and 16-byte initialization vector. * The secret key and initialization vector are then used in the AES-128 cipher to decrypt * the given ciphertext. * * @param salt * salt to be used in decryption * @param iterations * number of iterations to use in salting * @param password * password to be used for decryption * @param ciphertext * ciphertext to be decrypted * @return * cleartext * @throws Exception * on any error encountered in decryption */ public static byte[] decrypt( final byte[] salt, final int iterations, final String password, final byte[] ciphertext) throws Exception { /* compute key and initialization vector */ final MessageDigest shaDigest = MessageDigest.getInstance(DIGEST_ALGORITHM); byte[] pw = password.getBytes(CHARSET_NAME); for (int i = 0; i < iterations; i++) { /* add salt */ final byte[] salted = new byte[pw.length + salt.length]; System.arraycopy(pw, 0, salted, 0, pw.length); System.arraycopy(salt, 0, salted, pw.length, salt.length); Arrays.fill(pw, (byte) 0x00); /* compute SHA-256 digest */ shaDigest.reset(); pw = shaDigest.digest(salted); Arrays.fill(salted, (byte) 0x00); } /* extract the 16-byte key and initialization vector from the SHA-256 digest */ final byte[] key = new byte[16]; final byte[] iv = new byte[16]; System.arraycopy(pw, 0, key, 0, 16); System.arraycopy(pw, 16, iv, 0, 16); Arrays.fill(pw, (byte) 0x00); /* perform AES-128 decryption */ final Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec(key, KEY_ALGORITHM), new IvParameterSpec(iv)); Arrays.fill(key, (byte) 0x00); Arrays.fill(iv, (byte) 0x00); return cipher.doFinal(ciphertext); } }
apache-2.0
zhongl/lab
benchmarker/src/test/java/com/github/zhongl/benchmarker/RandomOptionalFactoryTest.java
1903
package com.github.zhongl.benchmarker; import org.junit.Test; import java.util.concurrent.CountDownLatch; /** @author <a href="mailto:zhong.lunfu@gmail.com">zhongl<a> */ public class RandomOptionalFactoryTest { private final StatisticsCollector collector = new StatisticsCollector(); private final CountDownLatch latch = new CountDownLatch(1); @Test public void optionsWereCreated() throws Exception { AssertCreatedFactory f1 = new AssertCreatedFactory(); AssertCreatedFactory f2 = new AssertCreatedFactory(); RandomOptionalFactory randomOptionalFactory = new RandomOptionalFactory(f1, f2); for (int i = 0; i < 10; i++) { randomOptionalFactory.create(); } f1.assertCreated(); f2.assertCreated(); } @Test public void optionsWereCreatedByRatio() throws Exception { AssertCreatedFactory f1 = new AssertCreatedFactory(); AssertCreatedFactory f2 = new AssertCreatedFactory(); RandomOptionalFactory randomOptionalFactory = new RandomOptionalFactory(f1, f2, f1); for (int i = 0; i < 10; i++) { randomOptionalFactory.create(); } f1.assertCreatedGreaterThan(5); f2.assertCreatedGreaterThan(2); } @Test public void optionsWereCreatedByFix() throws Exception { AssertCreatedFactory af1 = new AssertCreatedFactory(); AssertCreatedFactory af2 = new AssertCreatedFactory(); CallableFactory f1 = new FixInstanceSizeFactory(5, af1); CallableFactory f2 = new FixInstanceSizeFactory(5, af2); RandomOptionalFactory randomOptionalFactory = new RandomOptionalFactory(f1, f2, f1); for (int i = 0; i < 10; i++) { randomOptionalFactory.create(); } af1.assertCreated(5); af2.assertCreated(5); } }
apache-2.0
andrasigneczi/TravelOptimizer
DataCollector/src/test/QueueHandlers/JMSPublisherTest.java
1980
package QueueHandlers; import org.junit.Test; import javax.jms.JMSException; import java.io.IOException; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.ArrayList; import static org.junit.Assert.*; /** * Created by Andras on 27/07/2016. */ public class JMSPublisherTest { public static class TestObject implements Serializable { private static final long serialVersionUID = 42L; private String mString = "Hello"; private int mId = 10; private static int mCounter = 0; public TestObject() { mId = mCounter++; } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeObject( mString ); out.writeInt( mId ); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { mString = (String)in.readObject(); mId = in.readInt(); } // private void readObjectNoData() // throws ObjectStreamException // { // // } @Override public String toString() { return mString + " " + mId; } } @Test public void OnePublisherMoreListenerQueue() throws JMSException, InterruptedException { final int LISTENER_COUNT = 10; JMSPublisher lPublisher = new JMSPublisher( "JMSTEST" ); lPublisher.Connect(); JMSListener[] listeners = new JMSListener[LISTENER_COUNT]; for( int i = 0; i < LISTENER_COUNT; i++ ) { listeners[ i ] = new JMSListener( "JMSTEST" ); listeners[ i ].Connect(); } for( int i = 0; i < LISTENER_COUNT; i++ ) lPublisher.Publish( new TestObject() ); Thread.sleep( 2000 ); lPublisher.Disconnect(); for( int i = 0; i < LISTENER_COUNT; i++ ) { TestObject lTestObject = (TestObject)listeners[ i ].Listen(); System.out.println( "Listener " + i + ": " + lTestObject ); } Thread.sleep( 2000 ); for( int i = 0; i < LISTENER_COUNT; i++ ) listeners[ i ].Disconnect(); } }
apache-2.0
rlugojr/incubator-eagle
eagle-security/eagle-security-maprfs-auditlog/src/main/java/org/apache/eagle/security/auditlog/MapRFSAuditLogProcessorMain.java
6554
/* * * * 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.security.auditlog; import backtype.storm.spout.SchemeAsMultiScheme; import com.typesafe.config.Config; import org.apache.commons.lang3.time.DateUtils; import org.apache.eagle.common.config.EagleConfigConstants; import org.apache.eagle.dataproc.impl.storm.kafka.KafkaSourcedSpoutProvider; import org.apache.eagle.dataproc.impl.storm.kafka.KafkaSourcedSpoutScheme; import org.apache.eagle.datastream.ExecutionEnvironments; import org.apache.eagle.datastream.core.StreamProducer; import org.apache.eagle.datastream.storm.StormExecutionEnvironment; import org.apache.eagle.partition.DataDistributionDao; import org.apache.eagle.partition.PartitionAlgorithm; import org.apache.eagle.partition.PartitionStrategy; import org.apache.eagle.partition.PartitionStrategyImpl; import org.apache.eagle.security.partition.DataDistributionDaoImpl; import org.apache.eagle.security.partition.GreedyPartitionAlgorithm; import java.util.Arrays; import java.util.List; import java.util.Map; public class MapRFSAuditLogProcessorMain { public static PartitionStrategy createStrategy(Config config) { // TODO: Refactor configuration structure to avoid repeated config processing configure ~ hao String host = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.HOST); Integer port = config.getInt(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PORT); String username = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.USERNAME); String password = config.getString(EagleConfigConstants.EAGLE_PROPS + "." + EagleConfigConstants.EAGLE_SERVICE + "." + EagleConfigConstants.PASSWORD); String topic = config.getString("dataSourceConfig.topic"); DataDistributionDao dao = new DataDistributionDaoImpl(host, port, username, password, topic); PartitionAlgorithm algorithm = new GreedyPartitionAlgorithm(); String key1 = EagleConfigConstants.EAGLE_PROPS + ".partitionRefreshIntervalInMin"; Integer partitionRefreshIntervalInMin = config.hasPath(key1) ? config.getInt(key1) : 60; String key2 = EagleConfigConstants.EAGLE_PROPS + ".kafkaStatisticRangeInMin"; Integer kafkaStatisticRangeInMin = config.hasPath(key2) ? config.getInt(key2) : 60; PartitionStrategy strategy = new PartitionStrategyImpl(dao, algorithm, partitionRefreshIntervalInMin * DateUtils.MILLIS_PER_MINUTE, kafkaStatisticRangeInMin * DateUtils.MILLIS_PER_MINUTE); return strategy; } public static KafkaSourcedSpoutProvider createProvider(Config config) { String deserClsName = config.getString("dataSourceConfig.deserializerClass"); final KafkaSourcedSpoutScheme scheme = new KafkaSourcedSpoutScheme(deserClsName, config) { @Override public List<Object> deserialize(byte[] ser) { Object tmp = deserializer.deserialize(ser); Map<String, Object> map = (Map<String, Object>)tmp; if(tmp == null) return null; return Arrays.asList(map.get("user"), tmp); } }; KafkaSourcedSpoutProvider provider = new KafkaSourcedSpoutProvider() { @Override public SchemeAsMultiScheme getStreamScheme(String deserClsName, Config context) { return new SchemeAsMultiScheme(scheme); } }; return provider; } @SuppressWarnings("unchecked") public static void execWithDefaultPartition(StormExecutionEnvironment env, KafkaSourcedSpoutProvider provider) { StreamProducer source = env.fromSpout(provider).withOutputFields(2).nameAs("kafkaMsgConsumer").groupBy(Arrays.asList(0)); //StreamProducer reassembler = source.flatMap(new HdfsUserCommandReassembler()).groupBy(Arrays.asList(0)); //source.streamUnion(reassembler) source.flatMap(new FileSensitivityDataJoinExecutor()).groupBy(Arrays.asList(0)) .flatMap(new IPZoneDataJoinExecutor()) .alertWithConsumer("maprFSAuditLogEventStream", "maprFSAuditLogAlertExecutor"); env.execute(); } @SuppressWarnings("unchecked") public static void execWithBalancedPartition(StormExecutionEnvironment env, KafkaSourcedSpoutProvider provider) { PartitionStrategy strategy = createStrategy(env.getConfig()); StreamProducer source = env.fromSpout(provider).withOutputFields(2).nameAs("kafkaMsgConsumer").groupBy(strategy); //StreamProducer reassembler = source.flatMap(new HdfsUserCommandReassembler()).groupBy(Arrays.asList(0)); //source.streamUnion(reassembler) source.flatMap(new FileSensitivityDataJoinExecutor()).groupBy(Arrays.asList(0)) .flatMap(new IPZoneDataJoinExecutor()) .alertWithConsumer("maprFSAuditLogEventStream", "maprFSAuditLogAlertExecutor"); env.execute(); } public static void main(String[] args) throws Exception{ StormExecutionEnvironment env = ExecutionEnvironments.getStorm(args); Config config = env.getConfig(); KafkaSourcedSpoutProvider provider = createProvider(env.getConfig()); Boolean balancePartition = config.hasPath("eagleProps.balancePartitionEnabled") && config.getBoolean("eagleProps.balancePartitionEnabled"); if (balancePartition) { execWithBalancedPartition(env, provider); } else { execWithDefaultPartition(env, provider); } } }
apache-2.0
inventiLT/inventi-wicket
inventi-wicket-resources/src/main/java/lt/inventi/apollo/wicket/theme/settings/ThemeSettings.java
1007
package lt.inventi.apollo.wicket.theme.settings; import lt.inventi.apollo.wicket.theme.ActiveSessionThemeProvider; import lt.inventi.apollo.wicket.theme.ActiveThemeProvider; import lt.inventi.apollo.wicket.theme.DefaultThemeRepository; import lt.inventi.apollo.wicket.theme.ITheme; import lt.inventi.apollo.wicket.theme.none.EmptyTheme; public final class ThemeSettings { private final ActiveThemeProvider provider; public ThemeSettings() { this(new EmptyTheme()); } public ThemeSettings(ITheme theme) { this.provider = new ActiveSessionThemeProvider(new DefaultThemeRepository(theme)); } public ThemeSettings(ITheme... themes) { DefaultThemeRepository repo = new DefaultThemeRepository(themes[0]); for (int i = 1; i < themes.length; i++) { repo.add(themes[i]); } this.provider = new ActiveSessionThemeProvider(repo); } public ActiveThemeProvider getActiveThemeProvider() { return provider; } }
apache-2.0
googleapis/java-contact-center-insights
samples/snippets/src/main/java/com/example/contactcenterinsights/CreateIssueModel.java
2347
/* * Copyright 2021 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.example.contactcenterinsights; // [START contactcenterinsights_create_issue_model] import com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsClient; import com.google.cloud.contactcenterinsights.v1.IssueModel; import com.google.cloud.contactcenterinsights.v1.LocationName; import java.io.IOException; public class CreateIssueModel { public static void main(String[] args) throws Exception, IOException { // TODO(developer): Replace this variable before running the sample. String projectId = "my_project_id"; createIssueModel(projectId); } public static IssueModel createIssueModel(String projectId) throws Exception, IOException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (ContactCenterInsightsClient client = ContactCenterInsightsClient.create()) { // Construct a parent resource. LocationName parent = LocationName.of(projectId, "us-central1"); // Construct an issue model. IssueModel issueModel = IssueModel.newBuilder() .setDisplayName("my-model") .setInputDataConfig( IssueModel.InputDataConfig.newBuilder().setFilter("medium=\"CHAT\"").build()) .build(); // Call the Insights client to create an issue model. IssueModel response = client.createIssueModelAsync(parent, issueModel).get(); System.out.printf("Created %s%n", response.getName()); return response; } } } // [END contactcenterinsights_create_issue_model]
apache-2.0
youngmonkeys/ezyfox
ezyfox-database/src/main/java/com/tvd12/ezyfox/database/service/EzyCrudService.java
181
package com.tvd12.ezyfox.database.service; public interface EzyCrudService<I,E> extends EzyCountSerivce, EzySaveService<E>, EzyFindService<I, E>, EzyDeleteService<I> { }
apache-2.0
weizh/geolocator-3.0
geolocator-3.0/src/Wordnet/SetUtil.java
3264
/** * * Copyright (c) 2012 - 2014 Carnegie Mellon University * 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. * * @author Chaitra Radhakrishna, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: wei.zhang@cs.cmu.edu * * */ package Wordnet; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Queue; //import java.util.Map; import java.util.Set; public class SetUtil { public static boolean calculauteIntersection(Set<String> wordList1, Set<String> wordList2) { Set<String> allWords = populateWordset(wordList1, wordList2); // int M11 = 0; Iterator<String> wordList = allWords.iterator(); while (wordList.hasNext()) { String word = wordList.next(); boolean freq1 = wordList1.contains(word); boolean freq2 = wordList2.contains(word); if (freq1 && freq2) { return true; } } return false; } public static Set<String> checkSet(Set<String> set) { if (set == null) set = new HashSet<String>(); return set; } static Set<String> populateWordset(Set<String> wordList1, Set<String> wordList2) { Set<String> allWords = new HashSet<String>(); Set<String> wordIterator = null; Iterator<String> iterator = null; // wordIterator = wordList1.keySet(); iterator = wordList1.iterator(); while (iterator.hasNext()) { allWords.add(iterator.next()); } // wordIterator = wordList2.keySet(); iterator = wordList2.iterator(); while (iterator.hasNext()) { allWords.add(iterator.next()); } return allWords; } public static Set<String> addStringArray(Set<String> set, String[] array) { set = checkSet(set); for (String string : array) { set.add(string); } return set; } public static Queue<String> addStringArraytoQueue(Queue<String> set , String[] array) { //set = checkSet(set); for (String string : array) { set.add(string); } return set; } public static Set<String> addStringList(Set<String> set, List<String> array) { set = checkSet(set); for (String string : array) { set.add(string); } return set; } public static List<String> setToList(Set<String> set)// List<String> array) { ArrayList<String> list = new ArrayList<String>(); set = checkSet(set); for (String string : set) { list.add(string); } return list; } }
apache-2.0
TeamSirius/MaraudersMapMultiUser
app/src/main/java/com/tylerlubeck/maraudersmapmultiuser/Models/MyLocation.java
1160
package com.tylerlubeck.maraudersmapmultiuser.Models; /** * Created by Tyler on 4/16/2015. */ public class MyLocation { String building_name; int floor_number; int x_coordinate; int y_coordinate; String image_url; public MyLocation() {} public MyLocation(String buildingName, int floorNumber, int x, int y, String imageUrl) { this.building_name = buildingName; this.floor_number = floorNumber; this.x_coordinate = x; this.y_coordinate = y; this.image_url = imageUrl; } public String getImageUrl() { return image_url; } public int getXCoordinate() { return x_coordinate; } public int getYCoordinate() { return y_coordinate; } public String getFloorName() { return String.format("%s Floor %d", building_name, floor_number); } public int getFloorNumber() { return this.floor_number; } public String toString() { return String.format("%s Floor %s: (%d, %d)", building_name, floor_number, x_coordinate, y_coordinate); } }
apache-2.0
acbellini/Singularity
SingularityService/src/main/java/com/hubspot/singularity/resources/HistoryResource.java
8756
package com.hubspot.singularity.resources; import static com.hubspot.singularity.WebExceptions.checkBadRequest; import java.util.List; 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 com.google.common.base.Optional; import com.google.inject.Inject; import com.hubspot.singularity.SingularityDeployHistory; import com.hubspot.singularity.SingularityDeployKey; import com.hubspot.singularity.SingularityRequestHistory; import com.hubspot.singularity.SingularityService; import com.hubspot.singularity.SingularityTaskHistory; import com.hubspot.singularity.SingularityTaskId; import com.hubspot.singularity.SingularityTaskIdHistory; import com.hubspot.singularity.SingularityUser; import com.hubspot.singularity.auth.SingularityAuthorizationHelper; import com.hubspot.singularity.data.DeployManager; import com.hubspot.singularity.data.TaskManager; import com.hubspot.singularity.data.history.DeployHistoryHelper; import com.hubspot.singularity.data.history.DeployTaskHistoryHelper; import com.hubspot.singularity.data.history.HistoryManager; import com.hubspot.singularity.data.history.RequestHistoryHelper; import com.hubspot.singularity.data.history.TaskHistoryHelper; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiParam; @Path(HistoryResource.PATH) @Produces({ MediaType.APPLICATION_JSON }) @Api(description = "Manages historical data for tasks, requests, and deploys.", value = HistoryResource.PATH) public class HistoryResource extends AbstractHistoryResource { public static final String PATH = SingularityService.API_BASE_PATH + "/history"; private final DeployHistoryHelper deployHistoryHelper; private final TaskHistoryHelper taskHistoryHelper; private final RequestHistoryHelper requestHistoryHelper; private final DeployTaskHistoryHelper deployTaskHistoryHelper; @Inject public HistoryResource(HistoryManager historyManager, TaskManager taskManager, DeployManager deployManager, DeployHistoryHelper deployHistoryHelper, TaskHistoryHelper taskHistoryHelper, RequestHistoryHelper requestHistoryHelper, SingularityAuthorizationHelper authorizationHelper, Optional<SingularityUser> user, DeployTaskHistoryHelper deployTaskHistoryHelper) { super(historyManager, taskManager, deployManager, authorizationHelper, user); this.requestHistoryHelper = requestHistoryHelper; this.deployHistoryHelper = deployHistoryHelper; this.taskHistoryHelper = taskHistoryHelper; this.deployTaskHistoryHelper = deployTaskHistoryHelper; } @GET @Path("/task/{taskId}") @ApiOperation("Retrieve the history for a specific task.") public SingularityTaskHistory getHistoryForTask(@ApiParam("Task ID to look up") @PathParam("taskId") String taskId) { SingularityTaskId taskIdObj = getTaskIdObject(taskId); return getTaskHistory(taskIdObj); } private Integer getLimitCount(Integer countParam) { if (countParam == null) { return 100; } checkBadRequest(countParam >= 0, "count param must be non-zero"); if (countParam > 1000) { return 1000; } return countParam; } private Integer getLimitStart(Integer limitCount, Integer pageParam) { if (pageParam == null) { return 0; } checkBadRequest(pageParam >= 1, "page param must be 1 or greater"); return limitCount * (pageParam - 1); } @GET @Path("/request/{requestId}/tasks/active") @ApiOperation("Retrieve the history for all active tasks of a specific request.") public List<SingularityTaskIdHistory> getTaskHistoryForRequest( @ApiParam("Request ID to look up") @PathParam("requestId") String requestId) { authorizationHelper.checkForAuthorizationByRequestId(requestId, user); List<SingularityTaskId> activeTaskIds = taskManager.getActiveTaskIdsForRequest(requestId); return taskHistoryHelper.getTaskHistoriesFor(taskManager, activeTaskIds); } @GET @Path("/request/{requestId}/deploy/{deployId}") @ApiOperation("Retrieve the history for a specific deploy.") public SingularityDeployHistory getDeploy(@ApiParam("Request ID for deploy") @PathParam("requestId") String requestId, @ApiParam("Deploy ID") @PathParam("deployId") String deployId) { return getDeployHistory(requestId, deployId); } @GET @Path("/request/{requestId}/deploy/{deployId}/tasks/active") @ApiOperation("Retrieve the task history for a specific deploy.") public List<SingularityTaskIdHistory> getActiveDeployTasks( @ApiParam("Request ID for deploy") @PathParam("requestId") String requestId, @ApiParam("Deploy ID") @PathParam("deployId") String deployId) { authorizationHelper.checkForAuthorizationByRequestId(requestId, user); List<SingularityTaskId> activeTaskIds = taskManager.getActiveTaskIdsForDeploy(requestId, deployId); return taskHistoryHelper.getTaskHistoriesFor(taskManager, activeTaskIds); } @GET @Path("/request/{requestId}/deploy/{deployId}/tasks/inactive") @ApiOperation("Retrieve the task history for a specific deploy.") public List<SingularityTaskIdHistory> getInactiveDeployTasks( @ApiParam("Request ID for deploy") @PathParam("requestId") String requestId, @ApiParam("Deploy ID") @PathParam("deployId") String deployId, @ApiParam("Maximum number of items to return") @QueryParam("count") Integer count, @ApiParam("Which page of items to view") @QueryParam("page") Integer page) { final Integer limitCount = getLimitCount(count); final Integer limitStart = getLimitStart(limitCount, page); authorizationHelper.checkForAuthorizationByRequestId(requestId, user); SingularityDeployKey key = new SingularityDeployKey(requestId, deployId); return deployTaskHistoryHelper.getBlendedHistory(key, limitStart, limitCount); } @GET @Path("/request/{requestId}/tasks") @ApiOperation("Retrieve the history for all tasks of a specific request.") public List<SingularityTaskIdHistory> getTaskHistoryForRequest( @ApiParam("Request ID to look up") @PathParam("requestId") String requestId, @ApiParam("Maximum number of items to return") @QueryParam("count") Integer count, @ApiParam("Which page of items to view") @QueryParam("page") Integer page) { final Integer limitCount = getLimitCount(count); final Integer limitStart = getLimitStart(limitCount, page); authorizationHelper.checkForAuthorizationByRequestId(requestId, user); return taskHistoryHelper.getBlendedHistory(requestId, limitStart, limitCount); } @GET @Path("/request/{requestId}/deploys") @ApiOperation("") public List<SingularityDeployHistory> getDeploys( @ApiParam("Request ID to look up") @PathParam("requestId") String requestId, @ApiParam("Maximum number of items to return") @QueryParam("count") Integer count, @ApiParam("Which page of items to view") @QueryParam("page") Integer page) { final Integer limitCount = getLimitCount(count); final Integer limitStart = getLimitStart(limitCount, page); authorizationHelper.checkForAuthorizationByRequestId(requestId, user); return deployHistoryHelper.getBlendedHistory(requestId, limitStart, limitCount); } @GET @Path("/request/{requestId}/requests") @ApiOperation("") public List<SingularityRequestHistory> getRequestHistoryForRequest( @ApiParam("Request ID to look up") @PathParam("requestId") String requestId, @ApiParam("Naximum number of items to return") @QueryParam("count") Integer count, @ApiParam("Which page of items to view") @QueryParam("page") Integer page) { final Integer limitCount = getLimitCount(count); final Integer limitStart = getLimitStart(limitCount, page); authorizationHelper.checkForAuthorizationByRequestId(requestId, user); return requestHistoryHelper.getBlendedHistory(requestId, limitStart, limitCount); } @GET @Path("/requests/search") @ApiOperation("Search for requests.") public Iterable<String> getRequestHistoryForRequestLike( @ApiParam("Request ID prefix to search for") @QueryParam("requestIdLike") String requestIdLike, @ApiParam("Maximum number of items to return") @QueryParam("count") Integer count, @ApiParam("Which page of items to view") @QueryParam("page") Integer page) { final Integer limitCount = getLimitCount(count); final Integer limitStart = getLimitStart(limitCount, page); List<String> requestIds = historyManager.getRequestHistoryLike(requestIdLike, limitStart, limitCount); return authorizationHelper.filterAuthorizedRequestIds(user, requestIds); // TODO: will this screw up pagination? } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-quicksight/src/main/java/com/amazonaws/services/quicksight/model/ThemeVersion.java
16672
/* * 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.quicksight.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * A version of a theme. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/quicksight-2018-04-01/ThemeVersion" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ThemeVersion implements Serializable, Cloneable, StructuredPojo { /** * <p> * The version number of the theme. * </p> */ private Long versionNumber; /** * <p> * The Amazon Resource Name (ARN) of the resource. * </p> */ private String arn; /** * <p> * The description of the theme. * </p> */ private String description; /** * <p> * The Amazon QuickSight-defined ID of the theme that a custom theme inherits from. All themes initially inherit * from a default Amazon QuickSight theme. * </p> */ private String baseThemeId; /** * <p> * The date and time that this theme version was created. * </p> */ private java.util.Date createdTime; /** * <p> * The theme configuration, which contains all the theme display properties. * </p> */ private ThemeConfiguration configuration; /** * <p> * Errors associated with the theme. * </p> */ private java.util.List<ThemeError> errors; /** * <p> * The status of the theme version. * </p> */ private String status; /** * <p> * The version number of the theme. * </p> * * @param versionNumber * The version number of the theme. */ public void setVersionNumber(Long versionNumber) { this.versionNumber = versionNumber; } /** * <p> * The version number of the theme. * </p> * * @return The version number of the theme. */ public Long getVersionNumber() { return this.versionNumber; } /** * <p> * The version number of the theme. * </p> * * @param versionNumber * The version number of the theme. * @return Returns a reference to this object so that method calls can be chained together. */ public ThemeVersion withVersionNumber(Long versionNumber) { setVersionNumber(versionNumber); return this; } /** * <p> * The Amazon Resource Name (ARN) of the resource. * </p> * * @param arn * The Amazon Resource Name (ARN) of the resource. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The Amazon Resource Name (ARN) of the resource. * </p> * * @return The Amazon Resource Name (ARN) of the resource. */ public String getArn() { return this.arn; } /** * <p> * The Amazon Resource Name (ARN) of the resource. * </p> * * @param arn * The Amazon Resource Name (ARN) of the resource. * @return Returns a reference to this object so that method calls can be chained together. */ public ThemeVersion withArn(String arn) { setArn(arn); return this; } /** * <p> * The description of the theme. * </p> * * @param description * The description of the theme. */ public void setDescription(String description) { this.description = description; } /** * <p> * The description of the theme. * </p> * * @return The description of the theme. */ public String getDescription() { return this.description; } /** * <p> * The description of the theme. * </p> * * @param description * The description of the theme. * @return Returns a reference to this object so that method calls can be chained together. */ public ThemeVersion withDescription(String description) { setDescription(description); return this; } /** * <p> * The Amazon QuickSight-defined ID of the theme that a custom theme inherits from. All themes initially inherit * from a default Amazon QuickSight theme. * </p> * * @param baseThemeId * The Amazon QuickSight-defined ID of the theme that a custom theme inherits from. All themes initially * inherit from a default Amazon QuickSight theme. */ public void setBaseThemeId(String baseThemeId) { this.baseThemeId = baseThemeId; } /** * <p> * The Amazon QuickSight-defined ID of the theme that a custom theme inherits from. All themes initially inherit * from a default Amazon QuickSight theme. * </p> * * @return The Amazon QuickSight-defined ID of the theme that a custom theme inherits from. All themes initially * inherit from a default Amazon QuickSight theme. */ public String getBaseThemeId() { return this.baseThemeId; } /** * <p> * The Amazon QuickSight-defined ID of the theme that a custom theme inherits from. All themes initially inherit * from a default Amazon QuickSight theme. * </p> * * @param baseThemeId * The Amazon QuickSight-defined ID of the theme that a custom theme inherits from. All themes initially * inherit from a default Amazon QuickSight theme. * @return Returns a reference to this object so that method calls can be chained together. */ public ThemeVersion withBaseThemeId(String baseThemeId) { setBaseThemeId(baseThemeId); return this; } /** * <p> * The date and time that this theme version was created. * </p> * * @param createdTime * The date and time that this theme version was created. */ public void setCreatedTime(java.util.Date createdTime) { this.createdTime = createdTime; } /** * <p> * The date and time that this theme version was created. * </p> * * @return The date and time that this theme version was created. */ public java.util.Date getCreatedTime() { return this.createdTime; } /** * <p> * The date and time that this theme version was created. * </p> * * @param createdTime * The date and time that this theme version was created. * @return Returns a reference to this object so that method calls can be chained together. */ public ThemeVersion withCreatedTime(java.util.Date createdTime) { setCreatedTime(createdTime); return this; } /** * <p> * The theme configuration, which contains all the theme display properties. * </p> * * @param configuration * The theme configuration, which contains all the theme display properties. */ public void setConfiguration(ThemeConfiguration configuration) { this.configuration = configuration; } /** * <p> * The theme configuration, which contains all the theme display properties. * </p> * * @return The theme configuration, which contains all the theme display properties. */ public ThemeConfiguration getConfiguration() { return this.configuration; } /** * <p> * The theme configuration, which contains all the theme display properties. * </p> * * @param configuration * The theme configuration, which contains all the theme display properties. * @return Returns a reference to this object so that method calls can be chained together. */ public ThemeVersion withConfiguration(ThemeConfiguration configuration) { setConfiguration(configuration); return this; } /** * <p> * Errors associated with the theme. * </p> * * @return Errors associated with the theme. */ public java.util.List<ThemeError> getErrors() { return errors; } /** * <p> * Errors associated with the theme. * </p> * * @param errors * Errors associated with the theme. */ public void setErrors(java.util.Collection<ThemeError> errors) { if (errors == null) { this.errors = null; return; } this.errors = new java.util.ArrayList<ThemeError>(errors); } /** * <p> * Errors associated with the theme. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setErrors(java.util.Collection)} or {@link #withErrors(java.util.Collection)} if you want to override the * existing values. * </p> * * @param errors * Errors associated with the theme. * @return Returns a reference to this object so that method calls can be chained together. */ public ThemeVersion withErrors(ThemeError... errors) { if (this.errors == null) { setErrors(new java.util.ArrayList<ThemeError>(errors.length)); } for (ThemeError ele : errors) { this.errors.add(ele); } return this; } /** * <p> * Errors associated with the theme. * </p> * * @param errors * Errors associated with the theme. * @return Returns a reference to this object so that method calls can be chained together. */ public ThemeVersion withErrors(java.util.Collection<ThemeError> errors) { setErrors(errors); return this; } /** * <p> * The status of the theme version. * </p> * * @param status * The status of the theme version. * @see ResourceStatus */ public void setStatus(String status) { this.status = status; } /** * <p> * The status of the theme version. * </p> * * @return The status of the theme version. * @see ResourceStatus */ public String getStatus() { return this.status; } /** * <p> * The status of the theme version. * </p> * * @param status * The status of the theme version. * @return Returns a reference to this object so that method calls can be chained together. * @see ResourceStatus */ public ThemeVersion withStatus(String status) { setStatus(status); return this; } /** * <p> * The status of the theme version. * </p> * * @param status * The status of the theme version. * @return Returns a reference to this object so that method calls can be chained together. * @see ResourceStatus */ public ThemeVersion withStatus(ResourceStatus status) { this.status = status.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 (getVersionNumber() != null) sb.append("VersionNumber: ").append(getVersionNumber()).append(","); if (getArn() != null) sb.append("Arn: ").append(getArn()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getBaseThemeId() != null) sb.append("BaseThemeId: ").append(getBaseThemeId()).append(","); if (getCreatedTime() != null) sb.append("CreatedTime: ").append(getCreatedTime()).append(","); if (getConfiguration() != null) sb.append("Configuration: ").append(getConfiguration()).append(","); if (getErrors() != null) sb.append("Errors: ").append(getErrors()).append(","); if (getStatus() != null) sb.append("Status: ").append(getStatus()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ThemeVersion == false) return false; ThemeVersion other = (ThemeVersion) obj; if (other.getVersionNumber() == null ^ this.getVersionNumber() == null) return false; if (other.getVersionNumber() != null && other.getVersionNumber().equals(this.getVersionNumber()) == false) return false; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getBaseThemeId() == null ^ this.getBaseThemeId() == null) return false; if (other.getBaseThemeId() != null && other.getBaseThemeId().equals(this.getBaseThemeId()) == false) return false; if (other.getCreatedTime() == null ^ this.getCreatedTime() == null) return false; if (other.getCreatedTime() != null && other.getCreatedTime().equals(this.getCreatedTime()) == false) return false; if (other.getConfiguration() == null ^ this.getConfiguration() == null) return false; if (other.getConfiguration() != null && other.getConfiguration().equals(this.getConfiguration()) == false) return false; if (other.getErrors() == null ^ this.getErrors() == null) return false; if (other.getErrors() != null && other.getErrors().equals(this.getErrors()) == false) return false; if (other.getStatus() == null ^ this.getStatus() == null) return false; if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getVersionNumber() == null) ? 0 : getVersionNumber().hashCode()); hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getBaseThemeId() == null) ? 0 : getBaseThemeId().hashCode()); hashCode = prime * hashCode + ((getCreatedTime() == null) ? 0 : getCreatedTime().hashCode()); hashCode = prime * hashCode + ((getConfiguration() == null) ? 0 : getConfiguration().hashCode()); hashCode = prime * hashCode + ((getErrors() == null) ? 0 : getErrors().hashCode()); hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode()); return hashCode; } @Override public ThemeVersion clone() { try { return (ThemeVersion) 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.quicksight.model.transform.ThemeVersionMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
gravitee-io/graviteeio-access-management
gravitee-am-gateway/gravitee-am-gateway-handler/gravitee-am-gateway-handler-common/src/main/java/io/gravitee/am/gateway/handler/common/vertx/web/handler/AuthenticationFlowContextHandler.java
3713
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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.gravitee.am.gateway.handler.common.vertx.web.handler; import io.gravitee.am.gateway.handler.common.utils.ConstantKeys; import io.gravitee.am.gateway.handler.common.vertx.web.handler.impl.CookieSession; import io.gravitee.am.service.AuthenticationFlowContextService; import io.vertx.core.Handler; import io.vertx.reactivex.ext.web.RoutingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import static io.gravitee.am.gateway.handler.common.utils.ConstantKeys.AUTH_FLOW_CONTEXT_VERSION_KEY; import static java.util.Optional.ofNullable; /** * @author Eric LELEU (eric.leleu at graviteesource.com) * @author GraviteeSource Team */ public class AuthenticationFlowContextHandler implements Handler<RoutingContext> { private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationFlowContextHandler.class); private AuthenticationFlowContextService authenticationFlowContextService; private final boolean exitOnError; public AuthenticationFlowContextHandler(AuthenticationFlowContextService authenticationFlowContextService, Environment env) { this.authenticationFlowContextService = authenticationFlowContextService; this.exitOnError = env.getProperty("authenticationFlow.exitOnError", Boolean.class, Boolean.FALSE); } @Override public void handle(RoutingContext context) { CookieSession session = (CookieSession) context.session().getDelegate(); if (session != null && !session.isDestroyed()) { final String transactionId = session.get(ConstantKeys.TRANSACTION_ID_KEY); final int version = ofNullable((Number) session.get(AUTH_FLOW_CONTEXT_VERSION_KEY)).map(Number::intValue).orElse(1); authenticationFlowContextService.loadContext(transactionId, version) .subscribe( ctx -> { // store the AuthenticationFlowContext in order to provide all related information about this context context.put(ConstantKeys.AUTH_FLOW_CONTEXT_KEY, ctx); // store only the AuthenticationFlowContext.data attributes in order to simplify EL templating // and provide an up to date set of data if the enrichAuthFlow Policy ius used multiple time in a step // {#context.attributes['authFlow']['entry']} context.put(ConstantKeys.AUTH_FLOW_CONTEXT_ATTRIBUTES_KEY, ctx.getData()); context.next(); }, error -> { LOGGER.warn("AuthenticationFlowContext can't be loaded", error); if (exitOnError) { context.fail(error); } else { context.next(); } }); } } }
apache-2.0
amirakhmedov/ignite
modules/ml/src/main/java/org/apache/ignite/ml/tree/randomforest/RandomForestClassifierTrainer.java
4400
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.ml.tree.randomforest; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.ignite.ml.composition.ModelsComposition; import org.apache.ignite.ml.composition.predictionsaggregator.OnMajorityPredictionsAggregator; import org.apache.ignite.ml.dataset.Dataset; import org.apache.ignite.ml.dataset.feature.FeatureMeta; import org.apache.ignite.ml.dataset.feature.ObjectHistogram; import org.apache.ignite.ml.dataset.impl.bootstrapping.BootstrappedDatasetPartition; import org.apache.ignite.ml.dataset.impl.bootstrapping.BootstrappedVector; import org.apache.ignite.ml.dataset.primitive.context.EmptyContext; import org.apache.ignite.ml.tree.randomforest.data.TreeRoot; import org.apache.ignite.ml.tree.randomforest.data.impurity.GiniHistogram; import org.apache.ignite.ml.tree.randomforest.data.impurity.GiniHistogramsComputer; import org.apache.ignite.ml.tree.randomforest.data.impurity.ImpurityHistogramsComputer; import org.apache.ignite.ml.tree.randomforest.data.statistics.ClassifierLeafValuesComputer; import org.apache.ignite.ml.tree.randomforest.data.statistics.LeafValuesComputer; /** * Classifier trainer based on RandomForest algorithm. */ public class RandomForestClassifierTrainer extends RandomForestTrainer<ObjectHistogram<BootstrappedVector>, GiniHistogram, RandomForestClassifierTrainer> { /** Label mapping. */ private Map<Double, Integer> lblMapping = new HashMap<>(); /** * Constructs an instance of RandomForestClassifierTrainer. * * @param meta Features meta. */ public RandomForestClassifierTrainer(List<FeatureMeta> meta) { super(meta); } /** {@inheritDoc} */ @Override protected RandomForestClassifierTrainer instance() { return this; } /** * Aggregates all unique labels from dataset and assigns integer id value for each label. * This id can be used as index in arrays or lists. * * @param dataset Dataset. * @return true if initialization was done. */ @Override protected boolean init(Dataset<EmptyContext, BootstrappedDatasetPartition> dataset) { Set<Double> uniqLabels = dataset.compute( x -> { Set<Double> labels = new HashSet<>(); for (int i = 0; i < x.getRowsCount(); i++) labels.add(x.getRow(i).label()); return labels; }, (l, r) -> { if (l == null) return r; if (r == null) return l; Set<Double> lbls = new HashSet<>(); lbls.addAll(l); lbls.addAll(r); return lbls; } ); if(uniqLabels == null) return false; int i = 0; for (Double label : uniqLabels) lblMapping.put(label, i++); return super.init(dataset); } /** {@inheritDoc} */ @Override protected ModelsComposition buildComposition(List<TreeRoot> models) { return new ModelsComposition(models, new OnMajorityPredictionsAggregator()); } /** {@inheritDoc} */ @Override protected ImpurityHistogramsComputer<GiniHistogram> createImpurityHistogramsComputer() { return new GiniHistogramsComputer(lblMapping); } /** {@inheritDoc} */ @Override protected LeafValuesComputer<ObjectHistogram<BootstrappedVector>> createLeafStatisticsAggregator() { return new ClassifierLeafValuesComputer(lblMapping); } }
apache-2.0
intel-hadoop/hbase-rhino
hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/TestRegionMergeTransaction.java
18314
/** * Copyright The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.apache.hadoop.hbase.regionserver; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CoordinatedStateManager; import org.apache.hadoop.hbase.CoordinatedStateManagerFactory; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.Server; import org.apache.hadoop.hbase.SmallTests; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Durability; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.regionserver.wal.HLog; import org.apache.hadoop.hbase.regionserver.wal.HLogFactory; import org.apache.hadoop.hbase.util.Bytes; import org.apache.zookeeper.KeeperException; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; import com.google.common.collect.ImmutableList; /** * Test the {@link RegionMergeTransaction} class against two HRegions (as * opposed to running cluster). */ @Category(SmallTests.class) public class TestRegionMergeTransaction { private final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); private final Path testdir = TEST_UTIL.getDataTestDir(this.getClass() .getName()); private HRegion region_a; private HRegion region_b; private HRegion region_c; private HLog wal; private FileSystem fs; // Start rows of region_a,region_b,region_c private static final byte[] STARTROW_A = new byte[] { 'a', 'a', 'a' }; private static final byte[] STARTROW_B = new byte[] { 'g', 'g', 'g' }; private static final byte[] STARTROW_C = new byte[] { 'w', 'w', 'w' }; private static final byte[] ENDROW = new byte[] { '{', '{', '{' }; private static final byte[] CF = HConstants.CATALOG_FAMILY; @Before public void setup() throws IOException { this.fs = FileSystem.get(TEST_UTIL.getConfiguration()); this.fs.delete(this.testdir, true); this.wal = HLogFactory.createHLog(fs, this.testdir, "logs", TEST_UTIL.getConfiguration()); this.region_a = createRegion(this.testdir, this.wal, STARTROW_A, STARTROW_B); this.region_b = createRegion(this.testdir, this.wal, STARTROW_B, STARTROW_C); this.region_c = createRegion(this.testdir, this.wal, STARTROW_C, ENDROW); assert region_a != null && region_b != null && region_c != null; TEST_UTIL.getConfiguration().setBoolean("hbase.testing.nocluster", true); } @After public void teardown() throws IOException { for (HRegion region : new HRegion[] { region_a, region_b, region_c }) { if (region != null && !region.isClosed()) region.close(); if (this.fs.exists(region.getRegionFileSystem().getRegionDir()) && !this.fs.delete(region.getRegionFileSystem().getRegionDir(), true)) { throw new IOException("Failed deleting of " + region.getRegionFileSystem().getRegionDir()); } } if (this.wal != null) this.wal.closeAndDelete(); this.fs.delete(this.testdir, true); } /** * Test straight prepare works. Tries to merge on {@link #region_a} and * {@link #region_b} * @throws IOException */ @Test public void testPrepare() throws IOException { prepareOnGoodRegions(); } private RegionMergeTransaction prepareOnGoodRegions() throws IOException { RegionMergeTransaction mt = new RegionMergeTransaction(region_a, region_b, false); RegionMergeTransaction spyMT = Mockito.spy(mt); doReturn(false).when(spyMT).hasMergeQualifierInMeta(null, region_a.getRegionName()); doReturn(false).when(spyMT).hasMergeQualifierInMeta(null, region_b.getRegionName()); assertTrue(spyMT.prepare(null)); return spyMT; } /** * Test merging the same region */ @Test public void testPrepareWithSameRegion() throws IOException { RegionMergeTransaction mt = new RegionMergeTransaction(this.region_a, this.region_a, true); assertFalse("should not merge the same region even if it is forcible ", mt.prepare(null)); } /** * Test merging two not adjacent regions under a common merge */ @Test public void testPrepareWithRegionsNotAdjacent() throws IOException { RegionMergeTransaction mt = new RegionMergeTransaction(this.region_a, this.region_c, false); assertFalse("should not merge two regions if they are adjacent except it is forcible", mt.prepare(null)); } /** * Test merging two not adjacent regions under a compulsory merge */ @Test public void testPrepareWithRegionsNotAdjacentUnderCompulsory() throws IOException { RegionMergeTransaction mt = new RegionMergeTransaction(region_a, region_c, true); RegionMergeTransaction spyMT = Mockito.spy(mt); doReturn(false).when(spyMT).hasMergeQualifierInMeta(null, region_a.getRegionName()); doReturn(false).when(spyMT).hasMergeQualifierInMeta(null, region_c.getRegionName()); assertTrue("Since focible is true, should merge two regions even if they are not adjacent", spyMT.prepare(null)); } /** * Pass a reference store */ @Test public void testPrepareWithRegionsWithReference() throws IOException { HStore storeMock = Mockito.mock(HStore.class); when(storeMock.hasReferences()).thenReturn(true); when(storeMock.getFamily()).thenReturn(new HColumnDescriptor("cf")); when(storeMock.close()).thenReturn(ImmutableList.<StoreFile>of()); this.region_a.stores.put(Bytes.toBytes(""), storeMock); RegionMergeTransaction mt = new RegionMergeTransaction(this.region_a, this.region_b, false); assertFalse( "a region should not be mergeable if it has instances of store file references", mt.prepare(null)); } @Test public void testPrepareWithClosedRegion() throws IOException { this.region_a.close(); RegionMergeTransaction mt = new RegionMergeTransaction(this.region_a, this.region_b, false); assertFalse(mt.prepare(null)); } /** * Test merging regions which are merged regions and has reference in hbase:meta all * the same */ @Test public void testPrepareWithRegionsWithMergeReference() throws IOException { RegionMergeTransaction mt = new RegionMergeTransaction(region_a, region_b, false); RegionMergeTransaction spyMT = Mockito.spy(mt); doReturn(true).when(spyMT).hasMergeQualifierInMeta(null, region_a.getRegionName()); doReturn(true).when(spyMT).hasMergeQualifierInMeta(null, region_b.getRegionName()); assertFalse(spyMT.prepare(null)); } @Test public void testWholesomeMerge() throws IOException, InterruptedException { final int rowCountOfRegionA = loadRegion(this.region_a, CF, true); final int rowCountOfRegionB = loadRegion(this.region_b, CF, true); assertTrue(rowCountOfRegionA > 0 && rowCountOfRegionB > 0); assertEquals(rowCountOfRegionA, countRows(this.region_a)); assertEquals(rowCountOfRegionB, countRows(this.region_b)); // Start transaction. RegionMergeTransaction mt = prepareOnGoodRegions(); // Run the execute. Look at what it returns. TEST_UTIL.getConfiguration().setInt(HConstants.REGIONSERVER_PORT, 0); CoordinatedStateManager cp = CoordinatedStateManagerFactory.getCoordinatedStateManager( TEST_UTIL.getConfiguration()); Server mockServer = new HRegionServer(TEST_UTIL.getConfiguration(), cp); HRegion mergedRegion = mt.execute(mockServer, null); // Do some assertions about execution. assertTrue(this.fs.exists(mt.getMergesDir())); // Assert region_a and region_b is closed. assertTrue(region_a.isClosed()); assertTrue(region_b.isClosed()); // Assert mergedir is empty -- because its content will have been moved out // to be under the merged region dirs. assertEquals(0, this.fs.listStatus(mt.getMergesDir()).length); // Check merged region have correct key span. assertTrue(Bytes.equals(this.region_a.getStartKey(), mergedRegion.getStartKey())); assertTrue(Bytes.equals(this.region_b.getEndKey(), mergedRegion.getEndKey())); // Count rows. merged region are already open try { int mergedRegionRowCount = countRows(mergedRegion); assertEquals((rowCountOfRegionA + rowCountOfRegionB), mergedRegionRowCount); } finally { HRegion.closeHRegion(mergedRegion); } // Assert the write lock is no longer held on region_a and region_b assertTrue(!this.region_a.lock.writeLock().isHeldByCurrentThread()); assertTrue(!this.region_b.lock.writeLock().isHeldByCurrentThread()); } @Test public void testRollback() throws IOException, InterruptedException { final int rowCountOfRegionA = loadRegion(this.region_a, CF, true); final int rowCountOfRegionB = loadRegion(this.region_b, CF, true); assertTrue(rowCountOfRegionA > 0 && rowCountOfRegionB > 0); assertEquals(rowCountOfRegionA, countRows(this.region_a)); assertEquals(rowCountOfRegionB, countRows(this.region_b)); // Start transaction. RegionMergeTransaction mt = prepareOnGoodRegions(); when(mt.createMergedRegionFromMerges(region_a, region_b, mt.getMergedRegionInfo())).thenThrow( new MockedFailedMergedRegionCreation()); // Run the execute. Look at what it returns. boolean expectedException = false; TEST_UTIL.getConfiguration().setInt(HConstants.REGIONSERVER_PORT, 0); CoordinatedStateManager cp = CoordinatedStateManagerFactory.getCoordinatedStateManager( TEST_UTIL.getConfiguration()); Server mockServer = new HRegionServer(TEST_UTIL.getConfiguration(), cp); try { mt.execute(mockServer, null); } catch (MockedFailedMergedRegionCreation e) { expectedException = true; } assertTrue(expectedException); // Run rollback assertTrue(mt.rollback(null, null)); // Assert I can scan region_a and region_b. int rowCountOfRegionA2 = countRows(this.region_a); assertEquals(rowCountOfRegionA, rowCountOfRegionA2); int rowCountOfRegionB2 = countRows(this.region_b); assertEquals(rowCountOfRegionB, rowCountOfRegionB2); // Assert rollback cleaned up stuff in fs assertTrue(!this.fs.exists(HRegion.getRegionDir(this.testdir, mt.getMergedRegionInfo()))); assertTrue(!this.region_a.lock.writeLock().isHeldByCurrentThread()); assertTrue(!this.region_b.lock.writeLock().isHeldByCurrentThread()); // Now retry the merge but do not throw an exception this time. assertTrue(mt.prepare(null)); HRegion mergedRegion = mt.execute(mockServer, null); // Count rows. daughters are already open // Count rows. merged region are already open try { int mergedRegionRowCount = countRows(mergedRegion); assertEquals((rowCountOfRegionA + rowCountOfRegionB), mergedRegionRowCount); } finally { HRegion.closeHRegion(mergedRegion); } // Assert the write lock is no longer held on region_a and region_b assertTrue(!this.region_a.lock.writeLock().isHeldByCurrentThread()); assertTrue(!this.region_b.lock.writeLock().isHeldByCurrentThread()); } @Test public void testFailAfterPONR() throws IOException, KeeperException, InterruptedException { final int rowCountOfRegionA = loadRegion(this.region_a, CF, true); final int rowCountOfRegionB = loadRegion(this.region_b, CF, true); assertTrue(rowCountOfRegionA > 0 && rowCountOfRegionB > 0); assertEquals(rowCountOfRegionA, countRows(this.region_a)); assertEquals(rowCountOfRegionB, countRows(this.region_b)); // Start transaction. RegionMergeTransaction mt = prepareOnGoodRegions(); Mockito.doThrow(new MockedFailedMergedRegionOpen()) .when(mt) .openMergedRegion((Server) Mockito.anyObject(), (RegionServerServices) Mockito.anyObject(), (HRegion) Mockito.anyObject()); // Run the execute. Look at what it returns. boolean expectedException = false; TEST_UTIL.getConfiguration().setInt(HConstants.REGIONSERVER_PORT, 0); CoordinatedStateManager cp = CoordinatedStateManagerFactory.getCoordinatedStateManager( TEST_UTIL.getConfiguration()); Server mockServer = new HRegionServer(TEST_UTIL.getConfiguration(), cp); try { mt.execute(mockServer, null); } catch (MockedFailedMergedRegionOpen e) { expectedException = true; } assertTrue(expectedException); // Run rollback returns false that we should restart. assertFalse(mt.rollback(null, null)); // Make sure that merged region is still in the filesystem, that // they have not been removed; this is supposed to be the case if we go // past point of no return. Path tableDir = this.region_a.getRegionFileSystem().getRegionDir() .getParent(); Path mergedRegionDir = new Path(tableDir, mt.getMergedRegionInfo() .getEncodedName()); assertTrue(TEST_UTIL.getTestFileSystem().exists(mergedRegionDir)); } @Test public void testMeregedRegionBoundary() { TableName tableName = TableName.valueOf("testMeregedRegionBoundary"); byte[] a = Bytes.toBytes("a"); byte[] b = Bytes.toBytes("b"); byte[] z = Bytes.toBytes("z"); HRegionInfo r1 = new HRegionInfo(tableName); HRegionInfo r2 = new HRegionInfo(tableName, a, z); HRegionInfo m = RegionMergeTransaction.getMergedRegionInfo(r1, r2); assertTrue(Bytes.equals(m.getStartKey(), r1.getStartKey()) && Bytes.equals(m.getEndKey(), r1.getEndKey())); r1 = new HRegionInfo(tableName, null, a); r2 = new HRegionInfo(tableName, a, z); m = RegionMergeTransaction.getMergedRegionInfo(r1, r2); assertTrue(Bytes.equals(m.getStartKey(), r1.getStartKey()) && Bytes.equals(m.getEndKey(), r2.getEndKey())); r1 = new HRegionInfo(tableName, null, a); r2 = new HRegionInfo(tableName, z, null); m = RegionMergeTransaction.getMergedRegionInfo(r1, r2); assertTrue(Bytes.equals(m.getStartKey(), r1.getStartKey()) && Bytes.equals(m.getEndKey(), r2.getEndKey())); r1 = new HRegionInfo(tableName, a, z); r2 = new HRegionInfo(tableName, z, null); m = RegionMergeTransaction.getMergedRegionInfo(r1, r2); assertTrue(Bytes.equals(m.getStartKey(), r1.getStartKey()) && Bytes.equals(m.getEndKey(), r2.getEndKey())); r1 = new HRegionInfo(tableName, a, b); r2 = new HRegionInfo(tableName, b, z); m = RegionMergeTransaction.getMergedRegionInfo(r1, r2); assertTrue(Bytes.equals(m.getStartKey(), r1.getStartKey()) && Bytes.equals(m.getEndKey(), r2.getEndKey())); } /** * Exception used in this class only. */ @SuppressWarnings("serial") private class MockedFailedMergedRegionCreation extends IOException { } @SuppressWarnings("serial") private class MockedFailedMergedRegionOpen extends IOException { } private HRegion createRegion(final Path testdir, final HLog wal, final byte[] startrow, final byte[] endrow) throws IOException { // Make a region with start and end keys. HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("table")); HColumnDescriptor hcd = new HColumnDescriptor(CF); htd.addFamily(hcd); HRegionInfo hri = new HRegionInfo(htd.getTableName(), startrow, endrow); HRegion a = HRegion.createHRegion(hri, testdir, TEST_UTIL.getConfiguration(), htd); HRegion.closeHRegion(a); return HRegion.openHRegion(testdir, hri, htd, wal, TEST_UTIL.getConfiguration()); } private int countRows(final HRegion r) throws IOException { int rowcount = 0; InternalScanner scanner = r.getScanner(new Scan()); try { List<Cell> kvs = new ArrayList<Cell>(); boolean hasNext = true; while (hasNext) { hasNext = scanner.next(kvs); if (!kvs.isEmpty()) rowcount++; } } finally { scanner.close(); } return rowcount; } /** * Load region with rows from 'aaa' to 'zzz', skip the rows which are out of * range of the region * @param r Region * @param f Family * @param flush flush the cache if true * @return Count of rows loaded. * @throws IOException */ private int loadRegion(final HRegion r, final byte[] f, final boolean flush) throws IOException { byte[] k = new byte[3]; int rowCount = 0; for (byte b1 = 'a'; b1 <= 'z'; b1++) { for (byte b2 = 'a'; b2 <= 'z'; b2++) { for (byte b3 = 'a'; b3 <= 'z'; b3++) { k[0] = b1; k[1] = b2; k[2] = b3; if (!HRegion.rowIsInRange(r.getRegionInfo(), k)) { continue; } Put put = new Put(k); put.add(f, null, k); if (r.getLog() == null) put.setDurability(Durability.SKIP_WAL); r.put(put); rowCount++; } } if (flush) { r.flushcache(); } } return rowCount; } }
apache-2.0
V119/spidersManager
src/com/sicdlib/dao/pyhtonDAO/imple/MOEDataDAO.java
690
package com.sicdlib.dao.pyhtonDAO.imple; import com.sicdlib.dao.IBaseDAO; import com.sicdlib.dao.pyhtonDAO.IMOEDataDAO; import com.sicdlib.dto.entity.MoeDataEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * Created by init on 2017/6/4. */ @Repository("moeDataDAO") public class MOEDataDAO implements IMOEDataDAO{ @Autowired private IBaseDAO baseDAO; @Override public Boolean saveMOEData(MoeDataEntity moeData) { try{ baseDAO.save(moeData); return true; }catch (Exception e){ e.printStackTrace(); return false; } } }
apache-2.0
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_4430.java
151
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_4430 { }
apache-2.0
spdx/tools
src/org/spdx/compare/SpdxSnippetComparer.java
9956
/** * Copyright (c) 2016 Source Auditor Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.spdx.compare; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.spdx.rdfparser.InvalidSPDXAnalysisException; import org.spdx.rdfparser.model.SpdxDocument; import org.spdx.rdfparser.model.SpdxFile; import org.spdx.rdfparser.model.SpdxItem; import org.spdx.rdfparser.model.SpdxSnippet; import com.google.common.base.Objects; import com.google.common.collect.Maps; /** * Compares two SPDX snippets. The <code>compare(snippetA, snippetB)</code> method will perform the comparison and * store the results. <code>isDifferenceFound()</code> will return true of any * differences were found. * @author Gary O'Neall * */ public class SpdxSnippetComparer extends SpdxItemComparer { private boolean inProgress = false; private boolean differenceFound = false; private boolean byteRangeEquals = true; private boolean lineRangeEquals = true; private boolean snippetFromFilesEquals = true; private boolean nameEquals = true; /** * Map of any difference between snippet from files where the file names are equal */ Map<SpdxDocument, Map<SpdxDocument, SpdxFileDifference>> snippetFromFileDifferences = Maps.newHashMap(); /** * Map of snippetFromFiles where the file names are different (and therefore considered a unique file) */ Map<SpdxDocument, Map<SpdxDocument, SpdxFile>> uniqueSnippetFromFile = Maps.newHashMap(); /** * @param extractedLicenseIdMap map of all extracted license IDs for any SPDX documents to be added to the comparer */ public SpdxSnippetComparer(Map<SpdxDocument, Map<SpdxDocument, Map<String, String>>> extractedLicenseIdMap) { super(extractedLicenseIdMap); } /** * Add a snippet to the comparer and performs the comparison to any existing documents * @param spdxDocument document containing the package * @param snippet snippet to be added * @param licenseXlationMap A mapping between the license IDs from licenses in fileA to fileB * @throws SpdxCompareException * @param spdxDocument * @param snippet */ public void addDocumentSnippet(SpdxDocument spdxDocument, SpdxSnippet snippet) throws SpdxCompareException { checkInProgress(); if (this.name == null) { this.name = snippet.toString(); } inProgress = true; Iterator<Entry<SpdxDocument, SpdxItem>> iter = this.documentItem.entrySet().iterator(); SpdxSnippet snippet2 = null; SpdxDocument document2 = null; while (iter.hasNext() && snippet2 == null) { Entry<SpdxDocument, SpdxItem> entry = iter.next(); if (entry.getValue() instanceof SpdxSnippet) { snippet2 = (SpdxSnippet)entry.getValue(); document2 = entry.getKey(); } } if (snippet2 != null) { try { if (!snippet2.equivalentConsideringNull(snippet2.getByteRange(), snippet.getByteRange())) { this.byteRangeEquals = false; this.differenceFound = true; } } catch (InvalidSPDXAnalysisException e) { throw(new SpdxCompareException("SPDX error getting byte range: "+e.getMessage())); } try { if (!snippet2.equivalentConsideringNull(snippet2.getLineRange(), snippet.getLineRange())) { this.lineRangeEquals = false; this.differenceFound = true; } } catch (InvalidSPDXAnalysisException e) { throw(new SpdxCompareException("SPDX error getting line range: "+e.getMessage())); } try { SpdxFile fromFile = snippet.getSnippetFromFile(); SpdxFile fromFile2 = snippet2.getSnippetFromFile(); compareSnippetFromFiles(spdxDocument, fromFile, document2, fromFile2); } catch (InvalidSPDXAnalysisException e) { throw(new SpdxCompareException("SPDX error getting snippet from file: "+e.getMessage())); } if (!SpdxComparer.stringsEqual(snippet2.getName(), snippet.getName())) { this.nameEquals = false; this.differenceFound = true; } } inProgress = false; super.addDocumentItem(spdxDocument, snippet); } /** * Compares the snippetFromFiles and updates the properties isSnippetFromFilesEquals, * uniqueSnippetFromFiles, and snippetFromFilesDifferences * @param fromFile * @param fromFile2 * @throws SpdxCompareException */ private void compareSnippetFromFiles(SpdxDocument spdxDocument, SpdxFile fromFile, SpdxDocument document2, SpdxFile fromFile2) throws SpdxCompareException { if (fromFile == null) { if (fromFile2 != null) { Map<SpdxDocument, SpdxFile> unique = this.uniqueSnippetFromFile.get(document2); if (unique == null) { unique = Maps.newHashMap(); this.uniqueSnippetFromFile.put(document2, unique); } unique.put(spdxDocument, fromFile2); this.snippetFromFilesEquals = false; } } else if (fromFile2 == null) { Map<SpdxDocument, SpdxFile> unique = this.uniqueSnippetFromFile.get(spdxDocument); if (unique == null) { unique = Maps.newHashMap(); this.uniqueSnippetFromFile.put(spdxDocument, unique); } unique.put(document2, fromFile); this.snippetFromFilesEquals = false; } else if (!Objects.equal(fromFile2.getName(), fromFile.getName())) { Map<SpdxDocument, SpdxFile> unique = this.uniqueSnippetFromFile.get(spdxDocument); if (unique == null) { unique = Maps.newHashMap(); this.uniqueSnippetFromFile.put(spdxDocument, unique); } unique.put(document2, fromFile); Map<SpdxDocument, SpdxFile> unique2 = this.uniqueSnippetFromFile.get(document2); if (unique2 == null) { unique2 = Maps.newHashMap(); this.uniqueSnippetFromFile.put(document2, unique2); } unique2.put(spdxDocument, fromFile2); this.snippetFromFilesEquals = false; } else { SpdxFileComparer fileCompare = new SpdxFileComparer(this.extractedLicenseIdMap); fileCompare.addDocumentFile(spdxDocument, fromFile); fileCompare.addDocumentFile(document2, fromFile2); if (fileCompare.isDifferenceFound()) { this.snippetFromFilesEquals = false; Map<SpdxDocument, SpdxFileDifference> comparerMap = Maps.newHashMap(); this.snippetFromFileDifferences.put(spdxDocument, comparerMap); Map<SpdxDocument, SpdxFileDifference> comparerMap2 = this.snippetFromFileDifferences.get(document2); if (comparerMap2 == null) { comparerMap2 = Maps.newHashMap(); this.snippetFromFileDifferences.put(document2, comparerMap2); } comparerMap.put(document2, fileCompare.getFileDifference(spdxDocument, document2)); comparerMap2.put(spdxDocument, fileCompare.getFileDifference(document2, spdxDocument)); } } if (!this.snippetFromFilesEquals) { this.differenceFound = true; } } /** * @return the differenceFound * @throws SpdxCompareException */ @Override public boolean isDifferenceFound() throws SpdxCompareException { checkInProgress(); return differenceFound || super.isDifferenceFound(); } /** * checks to make sure there is not a compare in progress * @throws SpdxCompareException * */ @Override protected void checkInProgress() throws SpdxCompareException { if (inProgress) { throw(new SpdxCompareException("File compare in progress - can not obtain compare results until compare has completed")); } super.checkInProgress(); } /** * Get any file difference for the Spdx Snippet From File between the two SPDX documents * If the fileName is different, the they are considered unique files and the getUniqueSnippetFromFile should be called * to obtain the unique file * @param docA * @param docB * @return the file difference or null if there is no file difference */ public SpdxFileDifference getSnippetFromFileDifference(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); Map<SpdxDocument, SpdxFileDifference> differenceMap = this.snippetFromFileDifferences.get(docA); if (differenceMap == null) { return null; } return differenceMap.get(docB); } /** * @return the byteRangeEquals */ public boolean isByteRangeEquals() throws SpdxCompareException { checkInProgress(); return byteRangeEquals; } /** * @return the lineRangeEquals */ public boolean isLineRangeEquals() throws SpdxCompareException { checkInProgress(); return lineRangeEquals; } /** * The snippetFromFiles can be true if there are some unique snippetFromFiles or differences between the snippetFromFiles (or both) * @return the snippetFromFilesEquals */ public boolean isSnippetFromFilesEquals() throws SpdxCompareException { checkInProgress(); return snippetFromFilesEquals; } /** * @return the nameEquals */ public boolean isNameEquals() throws SpdxCompareException { checkInProgress(); return nameEquals; } /** * Get an SpdxFile that only exists in docA but not docB * @param docA * @param docB * @return */ public SpdxFile getUniqueSnippetFromFile(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); Map<SpdxDocument, SpdxFile> docMap = this.uniqueSnippetFromFile.get(docA); if (docMap == null) { return null; } return docMap.get(docB); } /** * @return Total number of snippets */ public int getNumSnippets() { return this.documentItem.size(); } /** * @param spdxDocument * @return */ public SpdxSnippet getDocSnippet(SpdxDocument spdxDocument) { SpdxItem retItem = this.documentItem.get(spdxDocument); if (retItem != null && retItem instanceof SpdxSnippet) { return (SpdxSnippet)retItem; } else { return null; } } }
apache-2.0
Praveen2112/presto
core/trino-main/src/main/java/io/trino/execution/AddColumnTask.java
5732
/* * 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.trino.execution; import com.google.common.util.concurrent.ListenableFuture; import io.trino.Session; import io.trino.connector.CatalogName; import io.trino.execution.warnings.WarningCollector; import io.trino.metadata.Metadata; import io.trino.metadata.QualifiedObjectName; import io.trino.metadata.TableHandle; import io.trino.security.AccessControl; import io.trino.spi.connector.ColumnHandle; import io.trino.spi.connector.ColumnMetadata; import io.trino.spi.type.Type; import io.trino.spi.type.TypeNotFoundException; import io.trino.sql.tree.AddColumn; import io.trino.sql.tree.ColumnDefinition; import io.trino.sql.tree.Expression; import io.trino.transaction.TransactionManager; import java.util.List; import java.util.Map; import java.util.Optional; import static com.google.common.util.concurrent.Futures.immediateVoidFuture; import static io.trino.metadata.MetadataUtil.createQualifiedObjectName; import static io.trino.metadata.MetadataUtil.getRequiredCatalogHandle; import static io.trino.spi.StandardErrorCode.COLUMN_ALREADY_EXISTS; import static io.trino.spi.StandardErrorCode.COLUMN_TYPE_UNKNOWN; import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED; import static io.trino.spi.StandardErrorCode.TABLE_NOT_FOUND; import static io.trino.spi.StandardErrorCode.TYPE_NOT_FOUND; import static io.trino.spi.connector.ConnectorCapabilities.NOT_NULL_COLUMN_CONSTRAINT; import static io.trino.sql.NodeUtils.mapFromProperties; import static io.trino.sql.ParameterUtils.parameterExtractor; import static io.trino.sql.analyzer.SemanticExceptions.semanticException; import static io.trino.sql.analyzer.TypeSignatureTranslator.toTypeSignature; import static io.trino.type.UnknownType.UNKNOWN; import static java.util.Locale.ENGLISH; public class AddColumnTask implements DataDefinitionTask<AddColumn> { @Override public String getName() { return "ADD COLUMN"; } @Override public ListenableFuture<Void> execute( AddColumn statement, TransactionManager transactionManager, Metadata metadata, AccessControl accessControl, QueryStateMachine stateMachine, List<Expression> parameters, WarningCollector warningCollector) { Session session = stateMachine.getSession(); QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getName()); Optional<TableHandle> tableHandle = metadata.getTableHandle(session, tableName); if (tableHandle.isEmpty()) { if (!statement.isTableExists()) { throw semanticException(TABLE_NOT_FOUND, statement, "Table '%s' does not exist", tableName); } return immediateVoidFuture(); } CatalogName catalogName = getRequiredCatalogHandle(metadata, session, statement, tableName.getCatalogName()); accessControl.checkCanAddColumns(session.toSecurityContext(), tableName); Map<String, ColumnHandle> columnHandles = metadata.getColumnHandles(session, tableHandle.get()); ColumnDefinition element = statement.getColumn(); Type type; try { type = metadata.getType(toTypeSignature(element.getType())); } catch (TypeNotFoundException e) { throw semanticException(TYPE_NOT_FOUND, element, "Unknown type '%s' for column '%s'", element.getType(), element.getName()); } if (type.equals(UNKNOWN)) { throw semanticException(COLUMN_TYPE_UNKNOWN, element, "Unknown type '%s' for column '%s'", element.getType(), element.getName()); } if (columnHandles.containsKey(element.getName().getValue().toLowerCase(ENGLISH))) { if (!statement.isColumnNotExists()) { throw semanticException(COLUMN_ALREADY_EXISTS, statement, "Column '%s' already exists", element.getName()); } return immediateVoidFuture(); } if (!element.isNullable() && !metadata.getConnectorCapabilities(session, catalogName).contains(NOT_NULL_COLUMN_CONSTRAINT)) { throw semanticException(NOT_SUPPORTED, element, "Catalog '%s' does not support NOT NULL for column '%s'", catalogName.getCatalogName(), element.getName()); } Map<String, Expression> sqlProperties = mapFromProperties(element.getProperties()); Map<String, Object> columnProperties = metadata.getColumnPropertyManager().getProperties( catalogName, tableName.getCatalogName(), sqlProperties, session, metadata, accessControl, parameterExtractor(statement, parameters), true); ColumnMetadata column = ColumnMetadata.builder() .setName(element.getName().getValue()) .setType(type) .setNullable(element.isNullable()) .setComment(element.getComment()) .setProperties(columnProperties) .build(); metadata.addColumn(session, tableHandle.get(), column); return immediateVoidFuture(); } }
apache-2.0
pac4j/pac4j
pac4j-cas/src/main/java/org/pac4j/cas/authorization/DefaultCasAuthorizationGenerator.java
1548
package org.pac4j.cas.authorization; import org.pac4j.cas.client.CasClient; import org.pac4j.core.authorization.generator.AuthorizationGenerator; import org.pac4j.core.context.WebContext; import org.pac4j.core.context.session.SessionStore; import org.pac4j.core.profile.UserProfile; import java.util.Optional; /** * Default {@link AuthorizationGenerator} implementation for a {@link CasClient} which is able * to retrieve the isRemembered status from the CAS response and put it in the profile. * * @author Michael Remond * @since 1.5.1 */ public class DefaultCasAuthorizationGenerator implements AuthorizationGenerator { public static final String DEFAULT_REMEMBER_ME_ATTRIBUTE_NAME = "longTermAuthenticationRequestTokenUsed"; // default name of the CAS attribute for remember me authentication (CAS 3.4.10+) protected String rememberMeAttributeName = DEFAULT_REMEMBER_ME_ATTRIBUTE_NAME; public DefaultCasAuthorizationGenerator() { } public DefaultCasAuthorizationGenerator(final String rememberMeAttributeName) { this.rememberMeAttributeName = rememberMeAttributeName; } @Override public Optional<UserProfile> generate(final WebContext context, final SessionStore sessionStore, final UserProfile profile) { final var rememberMeValue = (String) profile.getAttribute(rememberMeAttributeName); final var isRemembered = rememberMeValue != null && Boolean.parseBoolean(rememberMeValue); profile.setRemembered(isRemembered); return Optional.of(profile); } }
apache-2.0
zohar-mizrahi/flink
flink-libraries/flink-gelly/src/test/java/org/apache/flink/graph/library/metric/ChecksumHashCodeTest.java
1616
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.graph.library.metric; import org.apache.flink.graph.Graph; import org.apache.flink.graph.asm.AsmTestBase; import org.apache.flink.graph.asm.dataset.ChecksumHashCode.Checksum; import org.apache.flink.graph.test.TestGraphUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Tests for {@link ChecksumHashCode}. */ public class ChecksumHashCodeTest extends AsmTestBase { @Test public void testSmallGraph() throws Exception { Graph<Long, Long, Long> graph = Graph.fromDataSet( TestGraphUtils.getLongLongVertexData(env), TestGraphUtils.getLongLongEdgeData(env), env); Checksum checksum = graph .run(new ChecksumHashCode<>()) .execute(); assertEquals(checksum.getCount(), 12L); assertEquals(checksum.getChecksum(), 19665L); } }
apache-2.0
fredvos/meet
src/main/java/org/mokolo/meet/Sample.java
2296
package org.mokolo.meet; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import lombok.Getter; import lombok.Setter; /** * Single sample from meter * */ public class Sample { @Getter @Setter private Long timestamp; @Getter private Map<Pricing, Float> electricityTotalKWHInMap; @Getter private Map<Pricing, Float> electricityTotalKWHOutMap; @Getter Float electricityCurrentKWIn; @Getter Float electricityCurrentKWOut; @Getter Float gasTotalM3In; private static SimpleDateFormat isoDateHourGMTFormat = new SimpleDateFormat("yyyy-MM-dd:HHZ"); static { isoDateHourGMTFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } public Sample() { this.electricityTotalKWHInMap = new HashMap<>(); this.electricityTotalKWHOutMap = new HashMap<>(); } public void put(String key, Float value) { if (key.equals("EIT1") || key.equals("ElAfnCum1")) this.electricityTotalKWHInMap.put(Pricing.LOW, value); else if (key.equals("EIT2") || key.equals("ElAfnCum2")) this.electricityTotalKWHInMap.put(Pricing.HIGH, value); else if (key.equals("EOT1") || key.equals("ElLevCum1")) this.electricityTotalKWHOutMap.put(Pricing.LOW, value); else if (key.equals("EOT2") || key.equals("ElLevCum2")) this.electricityTotalKWHOutMap.put(Pricing.HIGH, value); else if (key.equals("EIC") || key.equals("ElAfnCur")) this.electricityCurrentKWIn = value; else if (key.equals("EOC") || key.equals("ElLevCur")) this.electricityCurrentKWOut = value; else if (key.equals("GIT") || key.equals("GasAfnCum")) this.gasTotalM3In = value; } public Float getElectricityTotalKWHIn() { return sum(this.electricityTotalKWHInMap.values()); } public Float getElectricityTotalKWHOut() { return sum(this.electricityTotalKWHOutMap.values()); } public static Float sum(Collection<Float> values) { if (values == null || values.isEmpty()) return null; else { Float f = new Float(0.0); for (Float entry : values) f += entry; return f; } } public SampleStatistics getSampleStatistics() { return new SampleStatistics(this.timestamp, this.electricityCurrentKWIn, this.electricityCurrentKWOut); } }
apache-2.0
calinrc/hdfs_wfx
java/wfx_launcher/src/main/java/org/cgc/wfx/Progress.java
790
/* * Progress.java file written and maintained by Calin Cocan * Created on: Oct 16, 2015 * * This work is free: you can redistribute it and/or modify it under the terms of Apache License Version 2.0 * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the License for more details. * You should have received a copy of the License along with this program. If not, see <http://choosealicense.com/licenses/apache-2.0/>. ********************************************************************************************************************* */ package org.cgc.wfx; public interface Progress { boolean notifyProgress(int progressVal); }
apache-2.0
baksoy/Sunshine2
app/src/main/java/com/baksoy/sunshine/data/WeatherProvider.java
14334
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baksoy.sunshine.data; import android.annotation.TargetApi; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class WeatherProvider extends ContentProvider { // The URI Matcher used by this content provider. private static final UriMatcher sUriMatcher = buildUriMatcher(); private WeatherDbHelper mOpenHelper; static final int WEATHER = 100; static final int WEATHER_WITH_LOCATION = 101; static final int WEATHER_WITH_LOCATION_AND_DATE = 102; static final int LOCATION = 300; private static final SQLiteQueryBuilder sWeatherByLocationSettingQueryBuilder; static{ sWeatherByLocationSettingQueryBuilder = new SQLiteQueryBuilder(); //This is an inner join which looks like //weather INNER JOIN location ON weather.location_id = location._id sWeatherByLocationSettingQueryBuilder.setTables( WeatherContract.WeatherEntry.TABLE_NAME + " INNER JOIN " + WeatherContract.LocationEntry.TABLE_NAME + " ON " + WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry.COLUMN_LOC_KEY + " = " + WeatherContract.LocationEntry.TABLE_NAME + "." + WeatherContract.LocationEntry._ID); } //location.location_setting = ? private static final String sLocationSettingSelection = WeatherContract.LocationEntry.TABLE_NAME+ "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? "; //location.location_setting = ? AND date >= ? private static final String sLocationSettingWithStartDateSelection = WeatherContract.LocationEntry.TABLE_NAME+ "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " + WeatherContract.WeatherEntry.COLUMN_DATE + " >= ? "; //location.location_setting = ? AND date = ? private static final String sLocationSettingAndDaySelection = WeatherContract.LocationEntry.TABLE_NAME + "." + WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ? AND " + WeatherContract.WeatherEntry.COLUMN_DATE + " = ? "; private Cursor getWeatherByLocationSetting(Uri uri, String[] projection, String sortOrder) { String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri); long startDate = WeatherContract.WeatherEntry.getStartDateFromUri(uri); String[] selectionArgs; String selection; if (startDate == 0) { selection = sLocationSettingSelection; selectionArgs = new String[]{locationSetting}; } else { selectionArgs = new String[]{locationSetting, Long.toString(startDate)}; selection = sLocationSettingWithStartDateSelection; } return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(), projection, selection, selectionArgs, null, null, sortOrder ); } private Cursor getWeatherByLocationSettingAndDate( Uri uri, String[] projection, String sortOrder) { String locationSetting = WeatherContract.WeatherEntry.getLocationSettingFromUri(uri); long date = WeatherContract.WeatherEntry.getDateFromUri(uri); return sWeatherByLocationSettingQueryBuilder.query(mOpenHelper.getReadableDatabase(), projection, sLocationSettingAndDaySelection, new String[]{locationSetting, Long.toString(date)}, null, null, sortOrder ); } /* Students: Here is where you need to create the UriMatcher. This UriMatcher will match each URI to the WEATHER, WEATHER_WITH_LOCATION, WEATHER_WITH_LOCATION_AND_DATE, and LOCATION integer constants defined above. You can test this by uncommenting the testUriMatcher test within TestUriMatcher. */ static UriMatcher buildUriMatcher() { // I know what you're thinking. Why create a UriMatcher when you can use regular // expressions instead? Because you're not crazy, that's why. // All paths added to the UriMatcher have a corresponding code to return when a match is // found. The code passed into the constructor represents the code to return for the root // URI. It's common to use NO_MATCH as the code for this case. final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = WeatherContract.CONTENT_AUTHORITY; // For each type of URI you want to add, create a corresponding code. matcher.addURI(authority, WeatherContract.PATH_WEATHER, WEATHER); matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*", WEATHER_WITH_LOCATION); matcher.addURI(authority, WeatherContract.PATH_WEATHER + "/*/#", WEATHER_WITH_LOCATION_AND_DATE); matcher.addURI(authority, WeatherContract.PATH_LOCATION, LOCATION); return matcher; } /* Students: We've coded this for you. We just create a new WeatherDbHelper for later use here. */ @Override public boolean onCreate() { mOpenHelper = new WeatherDbHelper(getContext()); return true; } /* Students: Here's where you'll code the getType function that uses the UriMatcher. You can test this by uncommenting testGetType in TestProvider. */ @Override public String getType(Uri uri) { // Use the Uri Matcher to determine what kind of URI this is. final int match = sUriMatcher.match(uri); switch (match) { // Student: Uncomment and fill out these two cases case WEATHER_WITH_LOCATION_AND_DATE: return WeatherContract.WeatherEntry.CONTENT_ITEM_TYPE; case WEATHER_WITH_LOCATION: return WeatherContract.WeatherEntry.CONTENT_TYPE; case WEATHER: return WeatherContract.WeatherEntry.CONTENT_TYPE; case LOCATION: return WeatherContract.LocationEntry.CONTENT_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Here's the switch statement that, given a URI, will determine what kind of request it is, // and query the database accordingly. Cursor retCursor; switch (sUriMatcher.match(uri)) { // "weather/*/*" case WEATHER_WITH_LOCATION_AND_DATE: { retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder); break; } // "weather/*" case WEATHER_WITH_LOCATION: { retCursor = getWeatherByLocationSetting(uri, projection, sortOrder); break; } // "weather" case WEATHER: { retCursor = mOpenHelper.getReadableDatabase().query( WeatherContract.WeatherEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ); break; } // "location" case LOCATION: { retCursor = mOpenHelper.getReadableDatabase().query( WeatherContract.LocationEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder ); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } retCursor.setNotificationUri(getContext().getContentResolver(), uri); return retCursor; } /* Student: Add the ability to insert Locations to the implementation of this function. */ @Override public Uri insert(Uri uri, ContentValues values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); Uri returnUri; switch (match) { case WEATHER: { normalizeDate(values); long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, values); if ( _id > 0 ) returnUri = WeatherContract.WeatherEntry.buildWeatherUri(_id); else throw new android.database.SQLException("Failed to insert row into " + uri); break; } case LOCATION: { long _id = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, values); if ( _id > 0 ) returnUri = WeatherContract.LocationEntry.buildLocationUri(_id); else throw new android.database.SQLException("Failed to insert row into " + uri); break; } default: throw new UnsupportedOperationException("Unknown uri: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return returnUri; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int rowsDeleted; // this makes delete all rows return the number of rows deleted if ( null == selection ) selection = "1"; switch (match) { case WEATHER: rowsDeleted = db.delete( WeatherContract.WeatherEntry.TABLE_NAME, selection, selectionArgs); break; case LOCATION: rowsDeleted = db.delete( WeatherContract.LocationEntry.TABLE_NAME, selection, selectionArgs); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } // Because a null deletes all rows if (rowsDeleted != 0) { getContext().getContentResolver().notifyChange(uri, null); } return rowsDeleted; } private void normalizeDate(ContentValues values) { // normalize the date value if (values.containsKey(WeatherContract.WeatherEntry.COLUMN_DATE)) { long dateValue = values.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE); values.put(WeatherContract.WeatherEntry.COLUMN_DATE, WeatherContract.normalizeDate(dateValue)); } } @Override public int update( Uri uri, ContentValues values, String selection, String[] selectionArgs) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); int rowsUpdated; switch (match) { case WEATHER: normalizeDate(values); rowsUpdated = db.update(WeatherContract.WeatherEntry.TABLE_NAME, values, selection, selectionArgs); break; case LOCATION: rowsUpdated = db.update(WeatherContract.LocationEntry.TABLE_NAME, values, selection, selectionArgs); break; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } if (rowsUpdated != 0) { getContext().getContentResolver().notifyChange(uri, null); } return rowsUpdated; } @Override public int bulkInsert(Uri uri, ContentValues[] values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { case WEATHER: db.beginTransaction(); int returnCount = 0; try { for (ContentValues value : values) { normalizeDate(value); long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value); if (_id != -1) { returnCount++; } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } getContext().getContentResolver().notifyChange(uri, null); return returnCount; default: return super.bulkInsert(uri, values); } } // You do not need to call this method. This is a method specifically to assist the testing // framework in running smoothly. You can read more at: // http://developer.android.com/reference/android/content/ContentProvider.html#shutdown() @Override @TargetApi(11) public void shutdown() { mOpenHelper.close(); super.shutdown(); } }
apache-2.0
BVier/Taskana
rest/taskana-rest-spring/src/test/java/pro/taskana/rest/ClassificationControllerIntTest.java
12241
package pro.taskana.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.hateoas.Link; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import pro.taskana.RestHelper; import pro.taskana.TaskanaSpringBootTest; import pro.taskana.rest.resource.ClassificationResource; import pro.taskana.rest.resource.ClassificationSummaryListResource; import pro.taskana.rest.resource.ClassificationSummaryResource; /** * Test ClassificationController. * * @author bbr */ @TaskanaSpringBootTest class ClassificationControllerIntTest { static RestTemplate template = RestHelper.getRestTemplate(); @Autowired RestHelper restHelper; @Test void testGetAllClassifications() { ResponseEntity<ClassificationSummaryListResource> response = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); assertNotNull(response.getBody().getLink(Link.REL_SELF)); } @Test void testGetAllClassificationsFilterByCustomAttribute() { ResponseEntity<ClassificationSummaryListResource> response = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_A&custom-1-like=RVNR", HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); assertNotNull(response.getBody().getLink(Link.REL_SELF)); assertEquals(13, response.getBody().getContent().size()); } @Test void testGetAllClassificationsKeepingFilters() { ResponseEntity<ClassificationSummaryListResource> response = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_A&sort-by=key&order=asc", HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); assertNotNull(response.getBody().getLink(Link.REL_SELF)); assertTrue( response .getBody() .getLink(Link.REL_SELF) .getHref() .endsWith("/api/v1/classifications?domain=DOMAIN_A&sort-by=key&order=asc")); assertEquals(17, response.getBody().getContent().size()); assertEquals("A12", response.getBody().getContent().iterator().next().key); } @Test void testGetSecondPageSortedByKey() { ResponseEntity<ClassificationSummaryListResource> response = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS) + "?domain=DOMAIN_A&sort-by=key&order=asc&page=2&page-size=5", HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); assertEquals(5, response.getBody().getContent().size()); assertEquals("L1050", response.getBody().getContent().iterator().next().key); assertNotNull(response.getBody().getLink(Link.REL_SELF)); assertTrue( response .getBody() .getLink(Link.REL_SELF) .getHref() .endsWith( "/api/v1/classifications?" + "domain=DOMAIN_A&sort-by=key&order=asc&page=2&page-size=5")); assertNotNull(response.getBody().getLink(Link.REL_FIRST)); assertNotNull(response.getBody().getLink(Link.REL_LAST)); assertNotNull(response.getBody().getLink(Link.REL_NEXT)); assertNotNull(response.getBody().getLink(Link.REL_PREVIOUS)); } @Test @DirtiesContext void testCreateClassification() { String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\"," + "\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS\"," + "\"name\":\"new classification\",\"type\":\"TASK\"}"; ResponseEntity<ClassificationResource> responseEntity = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class)); assertNotNull(responseEntity); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\"," + "\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS_2\"," + "\"name\":\"new classification\",\"type\":\"TASK\"}"; responseEntity = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class)); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); } @Test @DirtiesContext void testCreateClassificationWithParentId() { String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\"," + "\"domain\":\"DOMAIN_B\",\"key\":\"NEW_CLASS_P1\"," + "\"name\":\"new classification\",\"type\":\"TASK\"," + "\"parentId\":\"CLI:200000000000000000000000000000000015\"}"; ResponseEntity<ClassificationResource> responseEntity = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class)); assertNotNull(responseEntity); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); } @Test @DirtiesContext @SuppressWarnings("checkstyle:LineLength") void testCreateClassificationWithParentKey() { String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_B\"," + "\"key\":\"NEW_CLASS_P2\",\"name\":\"new classification\"," + "\"type\":\"TASK\",\"parentKey\":\"T2100\"}"; ResponseEntity<ClassificationResource> responseEntity = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class)); assertNotNull(responseEntity); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); } @Test @DirtiesContext void testCreateClassificationWithParentKeyInDomain_aShouldCreateAClassificationInRootDomain() throws IOException { String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_A\"," + "\"key\":\"NEW_CLASS_P2\",\"name\":\"new classification\"," + "\"type\":\"TASK\",\"parentKey\":\"T2100\"}"; ResponseEntity<ClassificationResource> responseEntity = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class)); assertNotNull(responseEntity); assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); ResponseEntity<ClassificationSummaryListResource> response = template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.GET, restHelper.defaultRequest(), ParameterizedTypeReference.forType(ClassificationSummaryListResource.class)); assertNotNull(response.getBody().getLink(Link.REL_SELF)); boolean foundClassificationCreated = false; for (ClassificationSummaryResource classification : response.getBody().getContent()) { if ("NEW_CLASS_P2".equals(classification.getKey()) && "".equals(classification.getDomain()) && "T2100".equals(classification.getParentKey())) { foundClassificationCreated = true; } } assertEquals(true, foundClassificationCreated); } @Test @DirtiesContext void testReturn400IfCreateClassificationWithIncompatibleParentIdAndKey() throws IOException { String newClassification = "{\"classificationId\":\"\",\"category\":\"MANUAL\",\"domain\":\"DOMAIN_B\"," + "\"key\":\"NEW_CLASS_P3\",\"name\":\"new classification\"," + "\"type\":\"TASK\",\"parentId\":\"CLI:200000000000000000000000000000000015\"," + "\"parentKey\":\"T2000\"}"; HttpClientErrorException e = Assertions.assertThrows( HttpClientErrorException.class, () -> template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class))); assertNotNull(e); assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); } @Test @DirtiesContext void testCreateClassificationWithClassificationIdReturnsError400() throws IOException { String newClassification = "{\"classificationId\":\"someId\",\"category\":\"MANUAL\"," + "\"domain\":\"DOMAIN_A\",\"key\":\"NEW_CLASS\"," + "\"name\":\"new classification\",\"type\":\"TASK\"}"; HttpClientErrorException e = Assertions.assertThrows( HttpClientErrorException.class, () -> template.exchange( restHelper.toUrl(Mapping.URL_CLASSIFICATIONS), HttpMethod.POST, new HttpEntity<>(newClassification, restHelper.getHeaders()), ParameterizedTypeReference.forType(ClassificationResource.class))); assertNotNull(e); assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode()); } @Test void testGetClassificationWithSpecialCharacter() { HttpEntity<String> request = new HttpEntity<String>(restHelper.getHeadersAdmin()); ResponseEntity<ClassificationSummaryResource> response = template.exchange( restHelper.toUrl( Mapping.URL_CLASSIFICATIONS_ID, "CLI:100000000000000000000000000000000009"), HttpMethod.GET, request, ParameterizedTypeReference.forType(ClassificationSummaryResource.class)); assertEquals("Zustimmungserklärung", response.getBody().name); } @Test @DirtiesContext void testDeleteClassification() { HttpEntity<String> request = new HttpEntity<String>(restHelper.getHeaders()); ResponseEntity<ClassificationSummaryResource> response = template.exchange( restHelper.toUrl( Mapping.URL_CLASSIFICATIONS_ID, "CLI:200000000000000000000000000000000004"), HttpMethod.DELETE, request, ParameterizedTypeReference.forType(ClassificationSummaryResource.class)); assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); assertThrows( HttpClientErrorException.class, () -> { template.exchange( restHelper.toUrl( Mapping.URL_CLASSIFICATIONS_ID, "CLI:200000000000000000000000000000000004"), HttpMethod.GET, request, ParameterizedTypeReference.forType(ClassificationSummaryResource.class)); }); } }
apache-2.0
orsjb/HappyBrackets
HappyBrackets/src/test/java/net/happybrackets/develop/CassetteTapeMachine.java
7101
package net.happybrackets.develop; import net.beadsproject.beads.data.Sample; import net.beadsproject.beads.data.SampleManager; import net.beadsproject.beads.ugens.*; import net.happybrackets.core.HBAction; import net.happybrackets.device.HB; import net.happybrackets.device.sensors.*; import net.happybrackets.device.sensors.sensor_types.AccelerometerSensor; import net.happybrackets.device.sensors.sensor_types.GyroscopeSensor; import java.lang.invoke.MethodHandles; import java.util.LinkedList; public class CassetteTapeMachine implements HBAction { // final static int FFSPEED = 8; final static float FFSPEED = 0.08f; final static float FFATTEN = 0.5f; enum State { PLAY, STOP, FREE, REV, FF, RW; } long timeOfLastStopToPlay = 0, timeOfLastPlayToStop = 0; float newLoopStart = 0; State currentState = State.STOP, previousState = State.STOP; Glide rateEnv, rateMod, gainEnv, loopStart, loopEnd; SamplePlayer sp; LinkedList<double[]> sensorHistory; int count = 0; @Override public void action(HB hb) { hb.reset(); //audio stuff gainEnv = new Glide(hb.ac, 1f, 500); Gain g = new Gain(hb.ac, 1, gainEnv); rateEnv = new Glide(hb.ac, 0, 200); rateMod = new Glide(hb.ac, 0, 200); Function rate = new Function(rateEnv, rateMod) { @Override public float calculate() { return x[0] + x[1]; } }; SampleManager.setVerbose(true); String sample_name = "data/audio/Nylon_Guitar/Clean_A_harm.wav"; //sample_name = "data/audio/hiphop.wav"; Sample sample = SampleManager.sample(sample_name); System.out.println("Is sample loaded or null? " + sample_name); if (sample == null) { hb.setStatus("Unable to load sample " ); } else { sp = new SamplePlayer(hb.ac, sample); sp.setRate(rate); sp.setLoopType(SamplePlayer.LoopType.LOOP_FORWARDS); loopStart = new Glide(hb.ac, 0, 500); loopEnd = new Glide(hb.ac, (float) sp.getSample().getLength(), 500); sp.setLoopStart(loopStart); sp.setLoopEnd(loopEnd); g.addInput(sp); BiquadFilter bf = new BiquadFilter(hb.ac, 1, BiquadFilter.HP); bf.setFrequency(100); bf.addInput(g); hb.sound(bf); //sensor averaging sensorHistory = new LinkedList<double[]>(); for (int i = 0; i < 10; i++) { sensorHistory.add(new double[]{0, 0, 0}); } } //set up sensor // AccelerometerListener sensor = (MiniMU)hb.getSensor(MiniMU.class); Accelerometer accel_sensor = (Accelerometer)hb.getSensor(Accelerometer.class); if (accel_sensor != null) { accel_sensor.addListener(new SensorUpdateListener() { @Override public void sensorUpdated() { count++; //state stuff, with averaging double[] accel = accel_sensor.getAccelerometerData(); sensorHistory.removeFirst(); sensorHistory.add(accel); double xsmooth = 0, ysmooth = 0, zsmooth = 0; for (double[] histValue : sensorHistory) { xsmooth += histValue[0] / sensorHistory.size(); ysmooth += histValue[1] / sensorHistory.size(); zsmooth += histValue[2] / sensorHistory.size(); } if (count % 1 == 0) { // System.out.println(xsmooth + " " + ysmooth + " " + zsmooth); } if ((Math.abs(xsmooth) > Math.abs(ysmooth)) && (Math.abs(xsmooth) > Math.abs(zsmooth))) { if (xsmooth > 0) currentState = State.FF; else currentState = State.RW; } else if (Math.abs(ysmooth) > Math.abs(zsmooth)) { if (ysmooth > 0) currentState = State.PLAY; else currentState = State.FREE; } else { if (zsmooth > 0) currentState = State.STOP; else currentState = State.REV; } if (currentState != previousState) { changeState(); } } }); } Gyroscope gyroscope = (Gyroscope)hb.getSensor(Gyroscope.class); if (gyroscope != null){ gyroscope.addListener(new SensorUpdateListener() { @Override public void sensorUpdated() { double[] gyr = gyroscope.getGyroscopeData(); //magnitude double mag = Math.sqrt(gyr[0] * gyr[0] + gyr[1] * gyr[1] + gyr[2] * gyr[2]); double thresh = 2; System.out.println(mag); if (mag > thresh) rateMod.setValue((float) (mag - thresh) / 2f); else rateMod.setValue(0); } }); } } public void changeState() { System.out.println("State changed to " + currentState); switch(currentState) { case RW: rateEnv.setValue(-FFSPEED); gainEnv.setValue(FFATTEN); break; case FF: rateEnv.setValue(FFSPEED); gainEnv.setValue(FFATTEN); break; case PLAY: rateEnv.setValue(1); gainEnv.setValue(1f); break; case STOP: rateEnv.setValue(0); gainEnv.setValue(1); break; case REV: rateEnv.setValue(-1); gainEnv.setValue(1f); break; } if(previousState == State.STOP && currentState == State.PLAY) { System.out.println("STOP TO PLAY TRANSITION"); if(timeOfLastPlayToStop != 0 && timeOfLastStopToPlay != 0) { float duration = timeOfLastPlayToStop - timeOfLastStopToPlay; loopStart.setValue(newLoopStart); loopEnd.setValue(newLoopStart + duration); System.out.println("Setting loop start " + newLoopStart + ", loop end " + (newLoopStart + duration)); newLoopStart = (float)sp.getPosition(); } timeOfLastStopToPlay = System.currentTimeMillis(); } else if(previousState == State.PLAY && currentState == State.STOP) { System.out.println("PLAY TO STOP TRANSITION"); timeOfLastPlayToStop = System.currentTimeMillis(); } previousState = currentState; } public static void main(String[] args) { try { HB.runDebug(MethodHandles.lookup().lookupClass()); } catch (Exception e) { e.printStackTrace(); } } }
apache-2.0
webos21/xi
java/jcl/src/java/org/apache/harmony/security/provider/crypto/DSAKeyFactoryImpl.java
6772
/* * 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.harmony.security.provider.crypto; import java.math.BigInteger; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactorySpi; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.DSAParams; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class DSAKeyFactoryImpl extends KeyFactorySpi { /** * This method generates a DSAPrivateKey object from the provided key * specification. * * @param keySpec * - the specification (key material) for the DSAPrivateKey. * * @return a DSAPrivateKey object * * @throws InvalidKeySpecException * if "keySpec" is neither DSAPrivateKeySpec nor * PKCS8EncodedKeySpec */ protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws InvalidKeySpecException { if (keySpec != null) { if (keySpec instanceof DSAPrivateKeySpec) { return new DSAPrivateKeyImpl((DSAPrivateKeySpec) keySpec); } if (keySpec instanceof PKCS8EncodedKeySpec) { return new DSAPrivateKeyImpl((PKCS8EncodedKeySpec) keySpec); } } throw new InvalidKeySpecException( "'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec"); } /** * This method generates a DSAPublicKey object from the provided key * specification. * * @param keySpec * - the specification (key material) for the DSAPublicKey. * * @return a DSAPublicKey object * * @throws InvalidKeySpecException * if "keySpec" is neither DSAPublicKeySpec nor * X509EncodedKeySpec */ protected PublicKey engineGeneratePublic(KeySpec keySpec) throws InvalidKeySpecException { if (keySpec != null) { if (keySpec instanceof DSAPublicKeySpec) { return new DSAPublicKeyImpl((DSAPublicKeySpec) keySpec); } if (keySpec instanceof X509EncodedKeySpec) { return new DSAPublicKeyImpl((X509EncodedKeySpec) keySpec); } } throw new InvalidKeySpecException( "'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec"); } /** * This method returns a specification for the supplied key. * * The specification will be returned in the form of an object of the type * specified by keySpec. * * @param key * - either DSAPrivateKey or DSAPublicKey * @param keySpec * - either DSAPrivateKeySpec.class or DSAPublicKeySpec.class * * @return either a DSAPrivateKeySpec or a DSAPublicKeySpec * * @throws InvalidKeySpecException * if "keySpec" is not a specification for DSAPublicKey or * DSAPrivateKey */ protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec) throws InvalidKeySpecException { BigInteger p, q, g, x, y; if (key != null) { if (keySpec == null) { throw new NullPointerException("keySpec == null"); } if (key instanceof DSAPrivateKey) { DSAPrivateKey privateKey = (DSAPrivateKey) key; if (keySpec.equals(DSAPrivateKeySpec.class)) { x = privateKey.getX(); DSAParams params = privateKey.getParams(); p = params.getP(); q = params.getQ(); g = params.getG(); return (T) (new DSAPrivateKeySpec(x, p, q, g)); } if (keySpec.equals(PKCS8EncodedKeySpec.class)) { return (T) (new PKCS8EncodedKeySpec(key.getEncoded())); } throw new InvalidKeySpecException( "'keySpec' is neither DSAPrivateKeySpec nor PKCS8EncodedKeySpec"); } if (key instanceof DSAPublicKey) { DSAPublicKey publicKey = (DSAPublicKey) key; if (keySpec.equals(DSAPublicKeySpec.class)) { y = publicKey.getY(); DSAParams params = publicKey.getParams(); p = params.getP(); q = params.getQ(); g = params.getG(); return (T) (new DSAPublicKeySpec(y, p, q, g)); } if (keySpec.equals(X509EncodedKeySpec.class)) { return (T) (new X509EncodedKeySpec(key.getEncoded())); } throw new InvalidKeySpecException( "'keySpec' is neither DSAPublicKeySpec nor X509EncodedKeySpec"); } } throw new InvalidKeySpecException( "'key' is neither DSAPublicKey nor DSAPrivateKey"); } /** * The method generates a DSAPublicKey object from the provided key. * * @param key * - a DSAPublicKey object or DSAPrivateKey object. * * @return object of the same type as the "key" argument * * @throws InvalidKeyException * if "key" is neither DSAPublicKey nor DSAPrivateKey */ protected Key engineTranslateKey(Key key) throws InvalidKeyException { if (key != null) { if (key instanceof DSAPrivateKey) { DSAPrivateKey privateKey = (DSAPrivateKey) key; DSAParams params = privateKey.getParams(); try { return engineGeneratePrivate(new DSAPrivateKeySpec( privateKey.getX(), params.getP(), params.getQ(), params.getG())); } catch (InvalidKeySpecException e) { // Actually this exception shouldn't be thrown throw new InvalidKeyException( "ATTENTION: InvalidKeySpecException: " + e); } } if (key instanceof DSAPublicKey) { DSAPublicKey publicKey = (DSAPublicKey) key; DSAParams params = publicKey.getParams(); try { return engineGeneratePublic(new DSAPublicKeySpec( publicKey.getY(), params.getP(), params.getQ(), params.getG())); } catch (InvalidKeySpecException e) { // Actually this exception shouldn't be thrown throw new InvalidKeyException( "ATTENTION: InvalidKeySpecException: " + e); } } } throw new InvalidKeyException( "'key' is neither DSAPublicKey nor DSAPrivateKey"); } }
apache-2.0
triathematician/blaisemath
blaise-common/src/main/java/com/googlecode/blaisemath/primitive/Markers.java
17804
package com.googlecode.blaisemath.primitive; /*- * #%L * blaise-common * -- * Copyright (C) 2014 - 2021 Elisha Peterson * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Arc2D; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.Collections; import java.util.List; import java.util.ServiceLoader; /** * Provides several custom shapes that can be used to draw points. * * @author Elisha Peterson */ public final class Markers { /** Caches markers loaded from resources file. */ private static final List<Marker> MARKER_CACHE = Lists.newArrayList(); /** Singleton for empty path. */ private static final GeneralPath EMPTY_PATH = new GeneralPath(); //region STATIC INSTANCES public static final BlankMarker BLANK = new BlankMarker(); public static final CircleMarker CIRCLE = new CircleMarker(); public static final SquareMarker SQUARE = new SquareMarker(); public static final DiamondMarker DIAMOND = new DiamondMarker(); public static final TriangleMarker TRIANGLE = new TriangleMarker(); public static final StarMarker5 STAR = new StarMarker5(); public static final StarMarker7 STAR7 = new StarMarker7(); public static final StarMarker11 STAR11 = new StarMarker11(); public static final PlusMarker PLUS = new PlusMarker(); public static final CrossMarker CROSS = new CrossMarker(); public static final TargetMarker TARGET = new TargetMarker(); public static final ArrowMarker ARROW = new ArrowMarker(); public static final GapArrowMarker GAP_ARROW = new GapArrowMarker(); public static final ThickArrowMarker THICK_ARROW = new ThickArrowMarker(); public static final ChevronMarker CHEVRON_MARKER = new ChevronMarker(); public static final TriangleMarkerForward TRIANGLE_ARROW = new TriangleMarkerForward(); public static final ArrowheadMarker ARROWHEAD = new ArrowheadMarker(); public static final TeardropMarker TEARDROP = new TeardropMarker(); public static final HappyFaceMarker HAPPYFACE = new HappyFaceMarker(); public static final HouseMarker HOUSE = new HouseMarker(); //endregion /** * Utility class */ private Markers() { } /** * Retrieve list of available shapes. * @return list of marker constants */ public static List<Marker> getAvailableMarkers() { if (MARKER_CACHE.isEmpty()) { ServiceLoader<Marker> loader = ServiceLoader.load(Marker.class); Iterables.addAll(MARKER_CACHE, loader); } return Collections.unmodifiableList(MARKER_CACHE); } /** * Blank marker. */ public static class BlankMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { return EMPTY_PATH; } } /** * Circle marker. */ public static class CircleMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { return new Ellipse2D.Double(p.getX() - radius, p.getY() - radius, 2 * radius, 2 * radius); } } /** * Square marker. */ public static class SquareMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { return new Rectangle2D.Double( p.getX() - radius / Math.sqrt(2), p.getY() - radius / Math.sqrt(2), 2 * radius / Math.sqrt(2), 2 * radius / Math.sqrt(2)); } } /** * Diamond marker. */ public static class DiamondMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); path.lineTo((float) (x - radius), (float) y); path.lineTo((float) x, (float) (y + radius)); path.lineTo((float) (x + radius), (float) y); path.closePath(); return path; } } /** * Triangle marker, pointing up. */ public static class TriangleMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); path.lineTo((float) (x + radius * Math.cos(Math.PI * 1.16667)), (float) (y - radius * Math.sin(Math.PI * 1.16667))); path.lineTo((float) (x + radius * Math.cos(Math.PI * 1.83333)), (float) (y - radius * Math.sin(Math.PI * 1.83333))); path.closePath(); return path; } } /** * Five point star marker. */ public static class StarMarker5 implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); for (int i = 0; i < 5; i++) { double theta = Math.PI / 2 + 2 * Math.PI * i / 5; path.lineTo((float) (x + radius * Math.cos(theta)), (float) (y - radius * Math.sin(theta))); theta += Math.PI / 5; path.lineTo((float) (x + radius / Math.sqrt(8) * Math.cos(theta)), (float) (y - radius / Math.sqrt(8) * Math.sin(theta))); } path.closePath(); return path; } } /** * Seven point star marker. */ public static class StarMarker7 implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); for (int i = 0; i < 7; i++) { double theta = Math.PI / 2 + 2 * Math.PI * i / 7; path.lineTo((float) (x + radius * Math.cos(theta)), (float) (y - radius * Math.sin(theta))); theta += Math.PI / 7; path.lineTo((float) (x + radius / 2 * Math.cos(theta)), (float) (y - radius / 2 * Math.sin(theta))); } path.closePath(); return path; } } /** * Eleven point star marker. */ public static class StarMarker11 implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); for (int i = 0; i < 11; i++) { double theta = Math.PI / 2 + 2 * Math.PI * i / 11; path.lineTo((float) (x + radius * Math.cos(theta)), (float) (y - radius * Math.sin(theta))); theta += Math.PI / 11; path.lineTo((float) (x + radius / 1.5 * Math.cos(theta)), (float) (y - radius / 1.5 * Math.sin(theta))); } path.closePath(); return path; } } /** * Plus marker. */ public static class PlusMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); path.lineTo((float) x, (float) (y + radius)); path.moveTo((float) (x - radius), (float) y); path.lineTo((float) (x + radius), (float) y); return new Area(new BasicStroke(radius/3).createStrokedShape(path)); } } /** * Cross marker. */ public static class CrossMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); double r2 = 0.7 * radius; path.moveTo((float) (x - r2), (float) (y - r2)); path.lineTo((float) (x + r2), (float) (y + r2)); path.moveTo((float) (x - r2), (float) (y + r2)); path.lineTo((float) (x + r2), (float) (y - r2)); return new Area(new BasicStroke(radius/3).createStrokedShape(path)); } } /** * Target marker (with circle and crosshairs). */ public static class TargetMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) x, (float) (y - radius)); path.lineTo((float) x, (float) (y + radius)); path.moveTo((float) (x - radius), (float) y); path.lineTo((float) (x + radius), (float) y); path.append(new Ellipse2D.Double(x - .6 * radius, y - .6 * radius, 1.2 * radius, 1.2 * radius), false); return new Area(new BasicStroke(radius/6).createStrokedShape(path)); } } /** * Arrow marker, pointing forward. */ public static class GapArrowMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) (x + .5 * radius), (float) (y - .5 * radius)); path.lineTo((float) (x + radius), (float) y); path.lineTo((float) (x + .5*radius), (float) (y + .5*radius)); path.moveTo((float) (x + .4*radius), (float) y); path.lineTo((float) (x - radius), (float) y); Shape wideShape = new Area(new BasicStroke(radius/4).createStrokedShape(path)); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(wideShape); } } /** * Arrow marker, pointing forward. */ public static class ArrowMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) (x + .5 * radius), (float) (y - .5 * radius)); path.lineTo((float) (x + radius), (float) y); path.lineTo((float) (x + .5*radius), (float) (y + .5*radius)); path.moveTo((float) (x + .8*radius), (float) y); path.lineTo((float) (x - radius), (float) y); Shape wideShape = new Area(new BasicStroke(radius/4).createStrokedShape(path)); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(wideShape); } } /** * Thicker arrow marker, pointing forward. */ public static class ThickArrowMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(); double y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) (x + .5 * radius), (float) (y - .5 * radius)); path.lineTo((float) (x + radius), (float) y); path.lineTo((float) (x + .5*radius), (float) (y + .5*radius)); path.moveTo((float) (x + .6*radius), (float) y); path.lineTo((float) (x - radius), (float) y); Shape wideShape = new Area(new BasicStroke(radius/2).createStrokedShape(path)); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(wideShape); } } /** * Chevron marker, pointing forward. */ public static class ChevronMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) (x + .3 * radius), (float) (y - .5 * radius)); path.lineTo((float) (x + .8 * radius), (float) y); path.lineTo((float) (x + .3 * radius), (float) (y + .5 * radius)); path.moveTo((float) (x - .7 * radius), (float) (y - .5 * radius)); path.lineTo((float) (x - .2 * radius), (float) y); path.lineTo((float) (x - .7 * radius), (float) (y + .5 * radius)); Shape wideShape = new Area(new BasicStroke(radius/4).createStrokedShape(path)); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(wideShape); } } /** * Triangle marker, pointing forward. */ public static class TriangleMarkerForward implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); GeneralPath path = new GeneralPath(); path.moveTo((float) (x + radius), (float) y); path.lineTo((float) (x + radius * Math.cos(Math.PI * 0.6667)), (float) (y - radius * Math.sin(Math.PI * 0.6667))); path.lineTo((float) (x + radius * Math.cos(Math.PI * 1.3333)), (float) (y - radius * Math.sin(Math.PI * 1.3333))); path.closePath(); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(path); } } /** * Arrowhead marker, pointing forward. */ public static class ArrowheadMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); GeneralPath gp10 = new GeneralPath(); gp10.moveTo((float) (x + radius), (float) y); gp10.lineTo((float) (x - radius), (float) (y + radius)); gp10.lineTo((float) (x - .5 * radius), (float) y); gp10.lineTo((float) (x - radius), (float) (y - radius)); gp10.closePath(); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(gp10); } } /** * Teardrop marker, pointing forward. */ public static class TeardropMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); GeneralPath gp11 = new GeneralPath(); gp11.moveTo(-.25f, -.5f); gp11.curveTo(-1f, -.5f, -1f, .5f, -.25f, .5f); gp11.curveTo(.5f, .5f, .5f, 0, 1f, 0); gp11.curveTo(.5f, 0, .5f, -.5f, -.2f, -.5f); gp11.closePath(); gp11.transform(new AffineTransform(radius, 0, 0, radius, x, y)); return AffineTransform.getRotateInstance(angle, x, y).createTransformedShape(gp11); } } /** * Happy face marker. */ public static class HappyFaceMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); Area a = new Area(new Ellipse2D.Double(x - radius, y - radius, 2 * radius, 2 * radius)); a.subtract(new Area(new Ellipse2D.Double(x - radius / 3 - radius / 6, y - radius / 2, radius / 3, radius / 3))); a.subtract(new Area(new Ellipse2D.Double(x + radius / 3 - radius / 6, y - radius / 2, radius / 3, radius / 3))); a.subtract(new Area(new Arc2D.Double(x - radius / 2, y - radius / 2, radius, radius, 200, 140, Arc2D.CHORD))); return a; } } /** * House-shaped marker. */ public static class HouseMarker implements Marker { @Override public Shape create(Point2D p, double angle, float radius) { double x = p.getX(), y = p.getY(); GeneralPath gp13 = new GeneralPath(); gp13.moveTo(-.9f, -.9f); gp13.lineTo(.9f, -.9f); gp13.lineTo(.9f, .4f); gp13.lineTo(1f, .4f); gp13.lineTo(.75f, .625f); gp13.lineTo(.75f, 1f); gp13.lineTo(.5f, 1f); gp13.lineTo(.5f, .75f); gp13.lineTo(0f, 1f); gp13.lineTo(-1f, .4f); gp13.lineTo(-.9f, .4f); gp13.lineTo(-.9f, -.9f); gp13.closePath(); gp13.transform(new AffineTransform(radius, 0, 0, -radius, x, y)); return gp13; } } }
apache-2.0
samskivert/robovm-samples
Tabster/src/main/java/org/robovm/samples/tabster/viewcontrollers/FourViewController.java
2319
/* * Copyright (C) 2013-2015 RoboVM AB * * 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. * * Portions of this code is based on Apple Inc's PhotoPicker sample (v2.0) * which is copyright (C) 2010-2013 Apple Inc. */ package org.robovm.samples.tabster.viewcontrollers; import org.robovm.apple.uikit.UIImage; import org.robovm.apple.uikit.UILabel; import org.robovm.apple.uikit.UINavigationController; import org.robovm.apple.uikit.UITabBarItem; import org.robovm.apple.uikit.UIViewController; import org.robovm.objc.annotation.CustomClass; import org.robovm.objc.annotation.IBOutlet; @CustomClass("FourViewController") public class FourViewController extends UIViewController { private UILabel titleLabel; /** * this is called when the UITabBarController loads it's views at launch * time */ @Override public void awakeFromNib() { // make our tabbar icon a custom one; // we could do it in Interface Builder, but this is just to illustrate a // point about using awakeFromNib vs. viewDidLoad. UITabBarItem customTab = new UITabBarItem("Four", UIImage.create("tab4.png"), 0); setTabBarItem(customTab); } @Override public void viewWillAppear(boolean animated) { super.viewWillAppear(animated); // if we were navigated to through the More screen table, then we have a // navigation bar which also means we have a title. So hide the title // label in this case, otherwise, we need it if (getParentViewController() instanceof UINavigationController) { titleLabel.setHidden(true); } else { titleLabel.setHidden(false); } } @IBOutlet private void setTitleLabel(UILabel titleLabel) { this.titleLabel = titleLabel; } }
apache-2.0
splunk/minecraft-app
shared-mc/src/main/java/com/splunk/sharedmc/loggable_events/LoggableEventType.java
389
package com.splunk.sharedmc.loggable_events; /** * Categories of loggable events. */ public enum LoggableEventType { PLAYER("PlayerEvent"), BLOCK("BlockEvent"), DEATH("DeathEvent"); private final String eventName; LoggableEventType(String eventName) { this.eventName = eventName; } public String getEventName() { return eventName; } }
apache-2.0
gravitee-io/graviteeio-access-management
gravitee-am-management-api/gravitee-am-management-api-rest/src/main/java/io/gravitee/am/management/handlers/management/api/authentication/handler/CustomAuthenticationSuccessHandler.java
2923
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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.gravitee.am.management.handlers.management.api.authentication.handler; import io.gravitee.am.identityprovider.api.User; import io.gravitee.am.management.handlers.management.api.authentication.provider.generator.JWTGenerator; import io.gravitee.am.management.handlers.management.api.authentication.service.AuthenticationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static io.gravitee.am.management.handlers.management.api.authentication.provider.generator.RedirectCookieGenerator.DEFAULT_REDIRECT_COOKIE_NAME; /** * @author Titouan COMPIEGNE (titouan.compiegne at graviteesource.com) * @author GraviteeSource Team */ public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { protected final Logger logger = LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class); @Autowired private JWTGenerator jwtGenerator; @Autowired private AuthenticationService authenticationService; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { String redirectUri = (String) request.getAttribute(DEFAULT_REDIRECT_COOKIE_NAME); // finish authentication and get an enhanced principal with user information. User principal = authenticationService.onAuthenticationSuccess(authentication); // store jwt authentication cookie to secure management restricted operations Cookie jwtAuthenticationCookie = jwtGenerator.generateCookie(principal); response.addCookie(jwtAuthenticationCookie); // Replay the original request. logger.debug("Redirecting to Url: " + redirectUri); getRedirectStrategy().sendRedirect(request, response, redirectUri); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-emr/src/main/java/com/amazonaws/services/elasticmapreduce/model/RemoveTagsResult.java
2404
/* * 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.elasticmapreduce.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * This output indicates the result of removing tags from a resource. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/elasticmapreduce-2009-03-31/RemoveTags" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RemoveTagsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * 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("{"); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RemoveTagsResult == false) return false; RemoveTagsResult other = (RemoveTagsResult) obj; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; return hashCode; } @Override public RemoveTagsResult clone() { try { return (RemoveTagsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
hazendaz/assertj-core
src/test/java/org/assertj/core/api/classes/ClassAssert_hasDeclaredFields_Test.java
1264
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.api.classes; import static org.mockito.Mockito.verify; import org.assertj.core.api.ClassAssert; import org.assertj.core.api.ClassAssertBaseTest; /** * Tests for <code>{@link org.assertj.core.api.ClassAssert#hasDeclaredFields(String...)}</code>. * * @author William Delanoue */ class ClassAssert_hasDeclaredFields_Test extends ClassAssertBaseTest { @Override protected ClassAssert invoke_api_method() { return assertions.hasDeclaredFields("field"); } @Override protected void verify_internal_effects() { verify(classes).assertHasDeclaredFields(getInfo(assertions), getActual(assertions), "field"); } }
apache-2.0
Skullabs/kikaha
kikaha-modules/kikaha-cloud-aws-lambda/tests/kikaha/cloud/aws/lambda/AmazonLambdaRequestSerializationTest.java
699
package kikaha.cloud.aws.lambda; import kikaha.core.test.KikahaRunner; import kikaha.core.util.SystemResource; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import static org.junit.Assert.assertNotNull; @RunWith(KikahaRunner.class) public class AmazonLambdaRequestSerializationTest { @Inject AmazonLambdaSerializer serializer; @Test public void canDeserializeRequestFromJSON(){ final String requestAsString = SystemResource.readFileAsString( "aws-lambda-request.json", "UTF-8" ); final AmazonLambdaRequest request = serializer.fromString( requestAsString, AmazonLambdaRequest.class ); assertNotNull( request ); } }
apache-2.0
bingoogolapple/J2EENote
EJB/EntityBean/src/cn/wh/bean/Person.java
1405
package cn.wh.bean; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="person") public class Person implements Serializable { private static final long serialVersionUID = 8648652046877078029L; private Integer id; private String name; public Person() {} public Person(String name) { this.name = name; } @Id @Column(name="id") @GeneratedValue(strategy=GenerationType.AUTO) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="name",length=20,nullable=false) public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.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; Person other = (Person) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
apache-2.0
vahpetr/microapp
geolocation/src/main/java/com/microexample/geolocation/GeolocationApplication.java
2396
package com.microexample.geolocation; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.*; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.EnvironmentVariableCredentialsProvider; import com.amazonaws.services.dynamodbv2.*; import com.microexample.geolocation.contracts.*; import com.microexample.geolocation.factories.*; import com.microexample.geolocation.repositories.*; import com.microexample.geolocation.services.*; @SpringBootApplication @Configuration public class GeolocationApplication { public static void main(String[] args) { SpringApplication.run(GeolocationApplication.class, args); } // usealy api use "request" Scope /** * Coordinates service resolver */ @Bean(destroyMethod = "dispose") @Scope("singleton") public ICoordinatesService coordinatesService() { ICoordinatesRepository coordinatesRepository = coordinatesRepository(); return new CoordinatesService(coordinatesRepository); } /** * Coordinates repository resolver */ @Bean @Scope("singleton") public ICoordinatesRepository coordinatesRepository() { AmazonDynamoDB dbContext = amazonDynamoDB(); return new CoordinatesRepository(dbContext); } /** * Amazon db context resolver */ @Bean(destroyMethod = "shutdown") @Scope("singleton") public AmazonDynamoDB amazonDynamoDB() { IFactory<AmazonDynamoDB> dbContextFactory = dynamoDbFactory(); AmazonDynamoDB dbContext = dbContextFactory.create(); return dbContext; } /** * Amazon dynamo db factory resolver */ @Bean @Scope("singleton") public IFactory<AmazonDynamoDB> dynamoDbFactory() { AWSCredentialsProvider awsCredentialsProvider = AWSCredentialsProvider(); IFactory<AmazonDynamoDB> dbContextFactory = new AmazonDynamoDbFactory(awsCredentialsProvider); return dbContextFactory; } /** * Amazon credentials provider resolver */ @Bean @Scope("singleton") public AWSCredentialsProvider AWSCredentialsProvider() { EnvironmentVariableCredentialsProvider awsCredentialsProvider = new EnvironmentVariableCredentialsProvider(); return awsCredentialsProvider; } }
apache-2.0
ephemeralin/java-training
chapter_006/src/main/java/ru/job4j/sqlxmlxsltjdbc/util/package-info.java
192
/** * Package for utils in "Sql-xml-xslt-jdbc" task. * * @author Viacheslav Piliugin (mailto:ephemeralin@gmail.com) * @version $Id$ * @since 0.1 */ package ru.job4j.sqlxmlxsltjdbc.util;
apache-2.0
yan74/afplib
org.afplib/src/main/java/org/afplib/afplib/impl/BRGImpl.java
5195
/** */ package org.afplib.afplib.impl; import java.util.Collection; import org.afplib.afplib.AfplibPackage; import org.afplib.afplib.BRG; import org.afplib.base.Triplet; import org.afplib.base.impl.SFImpl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>BRG</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.afplib.afplib.impl.BRGImpl#getRGrpName <em>RGrp Name</em>}</li> * <li>{@link org.afplib.afplib.impl.BRGImpl#getTriplets <em>Triplets</em>}</li> * </ul> * * @generated */ public class BRGImpl extends SFImpl implements BRG { /** * The default value of the '{@link #getRGrpName() <em>RGrp Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRGrpName() * @generated * @ordered */ protected static final String RGRP_NAME_EDEFAULT = null; /** * The cached value of the '{@link #getRGrpName() <em>RGrp Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRGrpName() * @generated * @ordered */ protected String rGrpName = RGRP_NAME_EDEFAULT; /** * The cached value of the '{@link #getTriplets() <em>Triplets</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTriplets() * @generated * @ordered */ protected EList<Triplet> triplets; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BRGImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return AfplibPackage.eINSTANCE.getBRG(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getRGrpName() { return rGrpName; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRGrpName(String newRGrpName) { String oldRGrpName = rGrpName; rGrpName = newRGrpName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.BRG__RGRP_NAME, oldRGrpName, rGrpName)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Triplet> getTriplets() { if (triplets == null) { triplets = new EObjectContainmentEList.Resolving<Triplet>(Triplet.class, this, AfplibPackage.BRG__TRIPLETS); } return triplets; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case AfplibPackage.BRG__TRIPLETS: return ((InternalEList<?>)getTriplets()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: return getRGrpName(); case AfplibPackage.BRG__TRIPLETS: return getTriplets(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: setRGrpName((String)newValue); return; case AfplibPackage.BRG__TRIPLETS: getTriplets().clear(); getTriplets().addAll((Collection<? extends Triplet>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: setRGrpName(RGRP_NAME_EDEFAULT); return; case AfplibPackage.BRG__TRIPLETS: getTriplets().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.BRG__RGRP_NAME: return RGRP_NAME_EDEFAULT == null ? rGrpName != null : !RGRP_NAME_EDEFAULT.equals(rGrpName); case AfplibPackage.BRG__TRIPLETS: return triplets != null && !triplets.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (RGrpName: "); result.append(rGrpName); result.append(')'); return result.toString(); } } //BRGImpl
apache-2.0
yippeesoft/NotifyTools
beanutils/src/main/java/org/apache/commons/beanutils/LazyDynaClass.java
13983
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.beanutils; /** * <p>DynaClass which implements the <code>MutableDynaClass</code> interface.</p> * * <p>A <code>MutableDynaClass</code> is a specialized extension to <code>DynaClass</code> * that allows properties to be added or removed dynamically.</p> * * <p>This implementation has one slightly unusual default behaviour - calling * the <code>getDynaProperty(name)</code> method for a property which doesn't * exist returns a <code>DynaProperty</code> rather than <code>null</code>. The * reason for this is that <code>BeanUtils</code> calls this method to check if * a property exists before trying to set the value. This would defeat the object * of the <code>LazyDynaBean</code> which automatically adds missing properties * when any of its <code>set()</code> methods are called. For this reason the * <code>isDynaProperty(name)</code> method has been added to this implementation * in order to determine if a property actually exists. If the more <i>normal</i> * behaviour of returning <code>null</code> is required, then this can be achieved * by calling the <code>setReturnNull(true)</code>.</p> * * <p>The <code>add(name, type, readable, writable)</code> method is not implemented * and always throws an <code>UnsupportedOperationException</code>. I believe * this attributes need to be added to the <code>DynaProperty</code> class * in order to control read/write facilities.</p> * * @version $Id: LazyDynaClass.java 1747095 2016-06-07 00:27:52Z ggregory $ * @see LazyDynaBean */ public class LazyDynaClass extends BasicDynaClass implements MutableDynaClass { /** * Controls whether changes to this DynaClass's properties are allowed. */ protected boolean restricted; /** * <p>Controls whether the <code>getDynaProperty()</code> method returns * null if a property doesn't exist - or creates a new one.</p> * * <p>Default is <code>false</code>. */ protected boolean returnNull = false; /** * Construct a new LazyDynaClass with default parameters. */ public LazyDynaClass() { this(null, (DynaProperty[])null); } /** * Construct a new LazyDynaClass with the specified name. * * @param name Name of this DynaBean class */ public LazyDynaClass(final String name) { this(name, (DynaProperty[])null); } /** * Construct a new LazyDynaClass with the specified name and DynaBean class. * * @param name Name of this DynaBean class * @param dynaBeanClass The implementation class for new instances */ public LazyDynaClass(final String name, final Class<?> dynaBeanClass) { this(name, dynaBeanClass, null); } /** * Construct a new LazyDynaClass with the specified name and properties. * * @param name Name of this DynaBean class * @param properties Property descriptors for the supported properties */ public LazyDynaClass(final String name, final DynaProperty[] properties) { this(name, LazyDynaBean.class, properties); } /** * Construct a new LazyDynaClass with the specified name, DynaBean class and properties. * * @param name Name of this DynaBean class * @param dynaBeanClass The implementation class for new instances * @param properties Property descriptors for the supported properties */ public LazyDynaClass(final String name, final Class<?> dynaBeanClass, final DynaProperty properties[]) { super(name, dynaBeanClass, properties); } /** * <p>Is this DynaClass currently restricted.</p> * <p>If restricted, no changes to the existing registration of * property names, data types, readability, or writeability are allowed.</p> * @return <code>true</code> if this {@link MutableDynaClass} cannot be changed * otherwise <code>false</code> */ public boolean isRestricted() { return restricted; } /** * <p>Set whether this DynaClass is currently restricted.</p> * <p>If restricted, no changes to the existing registration of * property names, data types, readability, or writeability are allowed.</p> * @param restricted <code>true</code> if this {@link MutableDynaClass} cannot * be changed otherwise <code>false</code> */ public void setRestricted(final boolean restricted) { this.restricted = restricted; } /** * Should this DynaClass return a <code>null</code> from * the <code>getDynaProperty(name)</code> method if the property * doesn't exist. * * @return <code>true</code> if a <code>null</code> {@link DynaProperty} * should be returned if the property doesn't exist, otherwise * <code>false</code> if a new {@link DynaProperty} should be created. */ public boolean isReturnNull() { return returnNull; } /** * Set whether this DynaClass should return a <code>null</code> from * the <code>getDynaProperty(name)</code> method if the property * doesn't exist. * @param returnNull <code>true</code> if a <code>null</code> {@link DynaProperty} * should be returned if the property doesn't exist, otherwise * <code>false</code> if a new {@link DynaProperty} should be created. */ public void setReturnNull(final boolean returnNull) { this.returnNull = returnNull; } /** * Add a new dynamic property with no restrictions on data type, * readability, or writeability. * * @param name Name of the new dynamic property * * @throws IllegalArgumentException if name is null * @throws IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ public void add(final String name) { add(new DynaProperty(name)); } /** * Add a new dynamic property with the specified data type, but with * no restrictions on readability or writeability. * * @param name Name of the new dynamic property * @param type Data type of the new dynamic property (null for no * restrictions) * * @throws IllegalArgumentException if name is null * @throws IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ public void add(final String name, final Class<?> type) { if (type == null) { add(name); } else { add(new DynaProperty(name, type)); } } /** * <p>Add a new dynamic property with the specified data type, readability, * and writeability.</p> * * <p><strong>N.B.</strong>Support for readable/writeable properties has not been implemented * and this method always throws a <code>UnsupportedOperationException</code>.</p> * * <p>I'm not sure the intention of the original authors for this method, but it seems to * me that readable/writable should be attributes of the <code>DynaProperty</code> class * (which they are not) and is the reason this method has not been implemented.</p> * * @param name Name of the new dynamic property * @param type Data type of the new dynamic property (null for no * restrictions) * @param readable Set to <code>true</code> if this property value * should be readable * @param writeable Set to <code>true</code> if this property value * should be writeable * * @throws UnsupportedOperationException anytime this method is called */ public void add(final String name, final Class<?> type, final boolean readable, final boolean writeable) { throw new java.lang.UnsupportedOperationException("readable/writable properties not supported"); } /** * Add a new dynamic property. * * @param property Property the new dynamic property to add. * * @throws IllegalArgumentException if name is null * @throws IllegalStateException if this DynaClass is currently * restricted, so no new properties can be added */ protected void add(final DynaProperty property) { if (property.getName() == null) { throw new IllegalArgumentException("Property name is missing."); } if (isRestricted()) { throw new IllegalStateException("DynaClass is currently restricted. No new properties can be added."); } // Check if property already exists if (propertiesMap.get(property.getName()) != null) { return; } // Create a new property array with the specified property final DynaProperty[] oldProperties = getDynaProperties(); final DynaProperty[] newProperties = new DynaProperty[oldProperties.length+1]; System.arraycopy(oldProperties, 0, newProperties, 0, oldProperties.length); newProperties[oldProperties.length] = property; // Update the properties setProperties(newProperties); } /** * Remove the specified dynamic property, and any associated data type, * readability, and writeability, from this dynamic class. * <strong>NOTE</strong> - This does <strong>NOT</strong> cause any * corresponding property values to be removed from DynaBean instances * associated with this DynaClass. * * @param name Name of the dynamic property to remove * * @throws IllegalArgumentException if name is null * @throws IllegalStateException if this DynaClass is currently * restricted, so no properties can be removed */ public void remove(final String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } if (isRestricted()) { throw new IllegalStateException("DynaClass is currently restricted. No properties can be removed."); } // Ignore if property doesn't exist if (propertiesMap.get(name) == null) { return; } // Create a new property array of without the specified property final DynaProperty[] oldProperties = getDynaProperties(); final DynaProperty[] newProperties = new DynaProperty[oldProperties.length-1]; int j = 0; for (int i = 0; i < oldProperties.length; i++) { if (!(name.equals(oldProperties[i].getName()))) { newProperties[j] = oldProperties[i]; j++; } } // Update the properties setProperties(newProperties); } /** * <p>Return a property descriptor for the specified property.</p> * * <p>If the property is not found and the <code>returnNull</code> indicator is * <code>true</code>, this method always returns <code>null</code>.</p> * * <p>If the property is not found and the <code>returnNull</code> indicator is * <code>false</code> a new property descriptor is created and returned (although * its not actually added to the DynaClass's properties). This is the default * beahviour.</p> * * <p>The reason for not returning a <code>null</code> property descriptor is that * <code>BeanUtils</code> uses this method to check if a property exists * before trying to set it - since these <i>Lazy</i> implementations automatically * add any new properties when they are set, returning <code>null</code> from * this method would defeat their purpose.</p> * * @param name Name of the dynamic property for which a descriptor * is requested * @return The dyna property for the specified name * * @throws IllegalArgumentException if no property name is specified */ @Override public DynaProperty getDynaProperty(final String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } DynaProperty dynaProperty = propertiesMap.get(name); // If it doesn't exist and returnNull is false // create a new DynaProperty if (dynaProperty == null && !isReturnNull() && !isRestricted()) { dynaProperty = new DynaProperty(name); } return dynaProperty; } /** * <p>Indicate whether a property actually exists.</p> * * <p><strong>N.B.</strong> Using <code>getDynaProperty(name) == null</code> * doesn't work in this implementation because that method might * return a DynaProperty if it doesn't exist (depending on the * <code>returnNull</code> indicator).</p> * * @param name The name of the property to check * @return <code>true</code> if there is a property of the * specified name, otherwise <code>false</code> * @throws IllegalArgumentException if no property name is specified */ public boolean isDynaProperty(final String name) { if (name == null) { throw new IllegalArgumentException("Property name is missing."); } return propertiesMap.get(name) == null ? false : true; } }
apache-2.0
skinzer/async-google-pubsub-client
src/test/java/com/spotify/google/cloud/pubsub/client/integration/ProgressMeter.java
3190
/* * Copyright (c) 2011-2015 Spotify AB * * 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.spotify.google.cloud.pubsub.client.integration; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import static com.google.common.util.concurrent.MoreExecutors.getExitingScheduledExecutorService; class ProgressMeter implements Runnable { private static final double NANOS_PER_MS = TimeUnit.MILLISECONDS.toNanos(1); private static final long NANOS_PER_S = TimeUnit.SECONDS.toNanos(1); private final AtomicLong totalLatency = new AtomicLong(); private final AtomicLong totalOperations = new AtomicLong(); private final String unit; private final boolean reportLatency; private long startTime; private long lastRows; private long lastTime; private long lastLatency; private static final ScheduledExecutorService EXECUTOR = getExitingScheduledExecutorService( new ScheduledThreadPoolExecutor(1)); public ProgressMeter(final String unit) { this(unit, false); } public ProgressMeter(final String unit, final boolean reportLatency) { this.unit = unit; this.reportLatency = reportLatency; this.startTime = System.nanoTime(); this.lastTime = startTime; EXECUTOR.scheduleAtFixedRate(this, 1, 1, TimeUnit.SECONDS); } public void inc() { this.totalOperations.incrementAndGet(); } public void inc(final long ops) { this.totalOperations.addAndGet(ops); } public void inc(final long ops, final long latency) { this.totalOperations.addAndGet(ops); this.totalLatency.addAndGet(latency); } @Override public void run() { final long now = System.nanoTime(); final long totalOperations = this.totalOperations.get(); final long totalLatency = this.totalLatency.get(); final long deltaOps = totalOperations - lastRows; final long deltaTime = now - lastTime; final long deltaLatency = totalLatency - lastLatency; lastRows = totalOperations; lastTime = now; lastLatency = totalLatency; final long operations = (deltaTime == 0) ? 0 : (NANOS_PER_S * deltaOps) / deltaTime; final double avgLatency = (deltaOps == 0) ? 0 : deltaLatency / (NANOS_PER_MS * deltaOps); final long seconds = TimeUnit.NANOSECONDS.toSeconds(now - startTime); System.out.printf("%,4ds: %,12d %s/s.", seconds, operations, unit); if (reportLatency) { System.out.printf(" %,10.3f ms avg latency.", avgLatency); } System.out.printf(" (total: %,12d)\n", totalOperations); System.out.flush(); } }
apache-2.0
alanfgates/hive
llap-common/src/java/org/apache/hadoop/hive/llap/metrics/ReadWriteLockMetrics.java
15607
/* * 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 a * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.llap.metrics; import avro.shaded.com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.metrics2.MetricsCollector; import org.apache.hadoop.metrics2.MetricsInfo; import org.apache.hadoop.metrics2.MetricsSource; import org.apache.hadoop.metrics2.annotation.Metric; import org.apache.hadoop.metrics2.annotation.Metrics; import org.apache.hadoop.metrics2.lib.MutableCounterLong; /** * Wrapper around a read/write lock to collect the lock wait times. * Instances of this wrapper class can be used to collect/accumulate the wai * times around R/W locks. This is helpful if the source of a performance issue * might be related to lock contention and you need to identify the actual * locks. Instances of this class can be wrapped around any <code>ReadWriteLock * </code> implementation. */ public class ReadWriteLockMetrics implements ReadWriteLock { private LockWrapper readLock; ///< wrapper around original read lock private LockWrapper writeLock; ///< wrapper around original write lock /** * Helper class to compare two <code>LockMetricSource</code> instances. * This <code>Comparator</code> class can be used to sort a list of <code> * LockMetricSource</code> instances in descending order by their total lock * wait time. */ public static class MetricsComparator implements Comparator<MetricsSource>, Serializable { private static final long serialVersionUID = -1; @Override public int compare(MetricsSource o1, MetricsSource o2) { if (o1 != null && o2 != null && o1 instanceof LockMetricSource && o2 instanceof LockMetricSource) { LockMetricSource lms1 = (LockMetricSource)o1; LockMetricSource lms2 = (LockMetricSource)o2; long totalMs1 = (lms1.readLockWaitTimeTotal.value() / 1000000L) + (lms1.writeLockWaitTimeTotal.value() / 1000000L); long totalMs2 = (lms2.readLockWaitTimeTotal.value() / 1000000L) + (lms2.writeLockWaitTimeTotal.value() / 1000000L); // sort descending by total lock time if (totalMs1 < totalMs2) { return 1; } if (totalMs1 > totalMs2) { return -1; } // sort by label (ascending) if lock time is the same return lms1.lockLabel.compareTo(lms2.lockLabel); } return 0; } } /** * Wraps a <code>ReadWriteLock</code> into a monitored lock if required by * configuration. This helper is checking the <code> * hive.llap.lockmetrics.collect</code> configuration option and wraps the * passed in <code>ReadWriteLock</code> into a monitoring container if the * option is set to <code>true</code>. Otherwise, the original (passed in) * lock instance is returned unmodified. * * @param conf Configuration instance to check for LLAP conf options * @param lock The <code>ReadWriteLock</code> to wrap for monitoring * @param metrics The target container for locking metrics * @see #createLockMetricsSource */ public static ReadWriteLock wrap(Configuration conf, ReadWriteLock lock, MetricsSource metrics) { Preconditions.checkNotNull(lock, "Caller has to provide valid input lock"); boolean needsWrap = false; if (null != conf) { needsWrap = HiveConf.getBoolVar(conf, HiveConf.ConfVars.LLAP_COLLECT_LOCK_METRICS); } if (false == needsWrap) { return lock; } Preconditions.checkNotNull(metrics, "Caller has to procide group specific metrics source"); return new ReadWriteLockMetrics(lock, metrics); } /** * Factory method for new metric collections. * You can create and use a single <code>MetricsSource</code> collection for * multiple R/W locks. This makes sense if several locks belong to a single * group and you're then interested in the accumulated values for the whole * group, rather than the single lock instance. The passed in label is * supposed to identify the group uniquely. * * @param label The group identifier for lock statistics */ public static MetricsSource createLockMetricsSource(String label) { Preconditions.checkNotNull(label); Preconditions.checkArgument(!label.contains("\""), "Label can't contain quote (\")"); return new LockMetricSource(label); } /** * Returns a list with all created <code>MetricsSource</code> instances for * the R/W lock metrics. The returned list contains the instances that were * previously created via the <code>createLockMetricsSource</code> function. * * @return A list of all R/W lock based metrics sources */ public static List<MetricsSource> getAllMetricsSources() { ArrayList<MetricsSource> ret = null; synchronized (LockMetricSource.allInstances) { ret = new ArrayList<>(LockMetricSource.allInstances); } return ret; } /// Enumeration of metric info names and descriptions @VisibleForTesting public enum LockMetricInfo implements MetricsInfo { ReadLockWaitTimeTotal("The total wait time for read locks in nanoseconds"), ReadLockWaitTimeMax("The maximum wait time for a read lock in nanoseconds"), ReadLockCount("Total amount of read lock requests"), WriteLockWaitTimeTotal( "The total wait time for write locks in nanoseconds"), WriteLockWaitTimeMax( "The maximum wait time for a write lock in nanoseconds"), WriteLockCount("Total amount of write lock requests"); private final String description; ///< metric description /** * Creates a new <code>MetricsInfo</code> with the given description. * * @param desc The description of the info */ private LockMetricInfo(String desc) { description = desc; } @Override public String description() { return this.description; } } /** * Source of the accumulated lock times and counts. * Instances of this <code>MetricSource</code> can be created via the static * factory method <code>createLockMetricsSource</code> and shared across * multiple instances of the outer <code>ReadWriteLockMetric</code> class. */ @Metrics(about = "Lock Metrics", context = "locking") private static class LockMetricSource implements MetricsSource { private static final ArrayList<MetricsSource> allInstances = new ArrayList<>(); private final String lockLabel; ///< identifier for the group of locks /// accumulated wait time for read locks @Metric MutableCounterLong readLockWaitTimeTotal; /// highest wait time for read locks @Metric MutableCounterLong readLockWaitTimeMax; /// total number of read lock calls @Metric MutableCounterLong readLockCounts; /// accumulated wait time for write locks @Metric MutableCounterLong writeLockWaitTimeTotal; /// highest wait time for write locks @Metric MutableCounterLong writeLockWaitTimeMax; /// total number of write lock calls @Metric MutableCounterLong writeLockCounts; /** * Creates a new metrics collection instance. * Several locks can share a single <code>MetricsSource</code> instances * where all of them increment the metrics counts together. This can be * interesting to have a single instance for a group of related locks. The * group should then be identified by the label. * * @param label The identifier of the metrics collection */ private LockMetricSource(String label) { lockLabel = label; readLockWaitTimeTotal = new MutableCounterLong(LockMetricInfo.ReadLockWaitTimeTotal, 0); readLockWaitTimeMax = new MutableCounterLong(LockMetricInfo.ReadLockWaitTimeMax, 0); readLockCounts = new MutableCounterLong(LockMetricInfo.ReadLockCount, 0); writeLockWaitTimeTotal = new MutableCounterLong(LockMetricInfo.WriteLockWaitTimeTotal, 0); writeLockWaitTimeMax = new MutableCounterLong(LockMetricInfo.WriteLockWaitTimeMax, 0); writeLockCounts = new MutableCounterLong(LockMetricInfo.WriteLockCount, 0); synchronized (allInstances) { allInstances.add(this); } } @Override public void getMetrics(MetricsCollector collector, boolean all) { collector.addRecord(this.lockLabel) .setContext("Locking") .addCounter(LockMetricInfo.ReadLockWaitTimeTotal, readLockWaitTimeTotal.value()) .addCounter(LockMetricInfo.ReadLockWaitTimeMax, readLockWaitTimeMax.value()) .addCounter(LockMetricInfo.ReadLockCount, readLockCounts.value()) .addCounter(LockMetricInfo.WriteLockWaitTimeTotal, writeLockWaitTimeTotal.value()) .addCounter(LockMetricInfo.WriteLockWaitTimeMax, writeLockWaitTimeMax.value()) .addCounter(LockMetricInfo.WriteLockCount, writeLockCounts.value()); } @Override public String toString() { long avgRead = 0L; long avgWrite = 0L; long totalMillis = 0L; if (0 < readLockCounts.value()) { avgRead = readLockWaitTimeTotal.value() / readLockCounts.value(); } if (0 < writeLockCounts.value()) { avgWrite = writeLockWaitTimeTotal.value() / writeLockCounts.value(); } totalMillis = (readLockWaitTimeTotal.value() / 1000000L) + (writeLockWaitTimeTotal.value() / 1000000L); StringBuffer sb = new StringBuffer(); sb.append("{ \"type\" : \"R/W Lock Stats\", \"label\" : \""); sb.append(lockLabel); sb.append("\", \"totalLockWaitTimeMillis\" : "); sb.append(totalMillis); sb.append(", \"readLock\" : { \"count\" : "); sb.append(readLockCounts.value()); sb.append(", \"avgWaitTimeNanos\" : "); sb.append(avgRead); sb.append(", \"maxWaitTimeNanos\" : "); sb.append(readLockWaitTimeMax.value()); sb.append(" }, \"writeLock\" : { \"count\" : "); sb.append(writeLockCounts.value()); sb.append(", \"avgWaitTimeNanos\" : "); sb.append(avgWrite); sb.append(", \"maxWaitTimeNanos\" : "); sb.append(writeLockWaitTimeMax.value()); sb.append(" } }"); return sb.toString(); } } /** * Inner helper class to wrap the original lock with a monitored one. * This inner class is delegating all actual locking operations to the wrapped * lock, while itself is only responsible to measure the time that it took to * acquire a specific lock. */ private static class LockWrapper implements Lock { /// the lock to delegate the work to private final Lock wrappedLock; /// total lock wait time in nanos private final MutableCounterLong lockWaitTotal; /// highest lock wait time (max) private final MutableCounterLong lockWaitMax; /// number of lock counts private final MutableCounterLong lockWaitCount; /** * Creates a new wrapper around an existing lock. * * @param original The original lock to wrap by this monitoring lock * @param total The (atomic) counter to increment for total lock wait time * @param max The (atomic) counter to adjust to the maximum wait time * @param cnt The (atomic) counter to increment with each lock call */ LockWrapper(Lock original, MutableCounterLong total, MutableCounterLong max, MutableCounterLong cnt) { wrappedLock = original; this.lockWaitTotal = total; this.lockWaitMax = max; this.lockWaitCount = cnt; } @Override public void lock() { long start = System.nanoTime(); wrappedLock.lock(); incrementBy(System.nanoTime() - start); } @Override public void lockInterruptibly() throws InterruptedException { long start = System.nanoTime(); wrappedLock.lockInterruptibly(); incrementBy(System.nanoTime() - start); } @Override public boolean tryLock() { return wrappedLock.tryLock(); } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { long start = System.nanoTime(); boolean ret = wrappedLock.tryLock(time, unit); incrementBy(System.nanoTime() - start); return ret; } @Override public void unlock() { wrappedLock.unlock(); } @Override public Condition newCondition() { return wrappedLock.newCondition(); } /** * Helper to increment the monitoring counters. * Called from the lock implementations to increment the total/max/coun * values of the monitoring counters. * * @param waitTime The actual wait time (in nanos) for the lock operation */ private void incrementBy(long waitTime) { this.lockWaitTotal.incr(waitTime); this.lockWaitCount.incr(); if (waitTime > this.lockWaitMax.value()) { this.lockWaitMax.incr(waitTime - this.lockWaitMax.value()); } } } /** * Creates a new monitoring wrapper around a R/W lock. * The so created wrapper instance can be used instead of the original R/W * lock, which then automatically updates the monitoring values in the <code> * MetricsSource</code>. This allows easy "slide in" of lock monitoring where * originally only a standard R/W lock was used. * * @param lock The original R/W lock to wrap for monitoring * @param metrics The target for lock monitoring */ private ReadWriteLockMetrics(ReadWriteLock lock, MetricsSource metrics) { Preconditions.checkNotNull(lock); Preconditions.checkArgument(metrics instanceof LockMetricSource, "Invalid MetricsSource"); LockMetricSource lms = (LockMetricSource)metrics; readLock = new LockWrapper(lock.readLock(), lms.readLockWaitTimeTotal, lms.readLockWaitTimeMax, lms.readLockCounts); writeLock = new LockWrapper(lock.writeLock(), lms.writeLockWaitTimeTotal, lms.writeLockWaitTimeMax, lms.writeLockCounts); } @Override public Lock readLock() { return readLock; } @Override public Lock writeLock() { return writeLock; } }
apache-2.0
pistolove/Lettcode
lettcode/src/leetcode/Counting_Bits.java
1193
package leetcode; /** * Given a non negative integer number num. For every numbers i in the range 0 ≤ * i ≤ num calculate the number of 1's in their binary representation and return * them as an array. * Example: * For num = 5 you should return [0,1,1,2,1,2]. * Follow up: * It is very easy to come up with a solution with run time * O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a * single pass? * Space complexity should be O(n). * Can you do it like a boss? Do it without using any builtin function like * __builtin_popcount in c++ or in any other language. * Show Hint */ public class Counting_Bits { public static void main(String[] args) { // 110 010 // System.err.println(3 & 2); System.err.println(countBits(100000000).toString()); } public static int[] countBits(int num) { int[] rt = new int[num]; for (int i = 0; i < num; i++) { int count = 0; int j = i; while(j != 0) { j = j & (j-1); count ++; } rt[i] = count; } return rt; } }
apache-2.0
logangorence/Aluminum
src/main/java/org/directcode/ide/core/Aluminum.java
2738
package org.directcode.ide.core; import lombok.Getter; import org.directcode.ide.api.*; import org.directcode.ide.api.MenuBar; import org.directcode.ide.plugins.PluginManager; import org.directcode.ide.util.Logger; import org.directcode.ide.window.EditorWindow; import org.directcode.ide.window.laf.LookAndFeelManager; import javax.swing.*; import javax.swing.plaf.nimbus.NimbusLookAndFeel; import java.awt.*; import java.io.File; /** * Main Entrypoint for the IDE * @since 0.0.1 */ public class Aluminum { /** * Primary Instance of our IDE. */ @Getter private static Aluminum IDE; /** * Tab size for the IDE. */ public static int tabSize = 4; /** * Location of the plugins directory. */ public static File pluginsDir; /** * The primary window for our application. */ @Getter private EditorWindow editor; /** * Logger for the application. */ private static Logger logger; /** * PluginManager for our IDE. */ private PluginManager pluginManager; /** * Start the application. */ private void start() { // Initialize the look and feel initializeLookAndFeel(); // Start the GUI createGui(); logger = new Logger("Aluminum"); logger.info("Starting"); // Initialize the Plugin Manager pluginManager = new PluginManager(); pluginManager.start(); } /** * Create the GUI. */ private void createGui() { editor = new EditorWindow(); } /** * Initialize the Look and Feel for our application. */ private void initializeLookAndFeel() { LookAndFeelManager lookAndFeelManager = new LookAndFeelManager(new NimbusLookAndFeel()); lookAndFeelManager.setLAF(); } /** * Initiate a shutdown of Aluminum. */ public void stop() { logger.info("Stopping"); pluginManager.stop(); System.exit(0); } /** * Main entrypoint. * * @param args Arguments for application in a String array */ public static void main(String[] args) { long startTime = System.currentTimeMillis(); // Ensure the IDE isn't running on a headless system. if (GraphicsEnvironment.isHeadless()) { throw new HeadlessException("Unable to detect display"); } // Initialize the plugins directory if it does not exist pluginsDir = new File("plugins/"); pluginsDir.mkdir(); // Initialize the class, and start IDE = new Aluminum(); IDE.start(); long endStartTime = System.currentTimeMillis(); logger.debug("Startup time: " + ((endStartTime - startTime))); MenuBar.addMenuItem(0, new JMenu("Test")); } }
apache-2.0
getlantern/lantern-common
src/main/java/org/lantern/monitoring/StatshubAPI.java
4868
package org.lantern.monitoring; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.IOUtils; import org.lantern.HttpURLClient; import org.lantern.JsonUtils; import org.lantern.LanternConstants; /** * API for posting and querying stats to/from statshub. */ public class StatshubAPI extends HttpURLClient { public StatshubAPI() { this(null); } public StatshubAPI(InetSocketAddress proxyAddress) { super(proxyAddress); } /** * Submit stats for an instance to statshub. * * @param instanceId * @param userGuid * @param countryCode * @param isFallback * @param stats * @throws Exception */ public void postInstanceStats( String instanceId, String userGuid, String countryCode, boolean isFallback, Stats stats) throws Exception { postStats("instance_" + instanceId, userGuid, countryCode, isFallback, stats, null); } /** * Submit stats for a user to statshub. * * @param userGuid * @param countryCode * @param stats * @throws Exception */ public void postUserStats( String userGuid, String countryCode, Stats stats) throws Exception { postStats("user_" + userGuid, userGuid, countryCode, false, stats, null); } /** * Submits stats to statshub. * * @param id * the stat id (instanceId or userId) * @param userGuid * the userId (if applicable) * @param countryCode * the countryCode * @param addFallbackDim * if true, the id will be added to the dims as "fallback" * @param stats * the stats * @param dims * additional dimensions to post with the stats */ public void postStats( String id, String userGuid, String countryCode, boolean addFallbackDim, Stats stats, Map<String, String> additionalDims) throws Exception { Map<String, Object> request = new HashMap<String, Object>(); Map<String, String> dims = new HashMap<String, String>(); if (additionalDims != null) { dims.putAll(additionalDims); } dims.put("user", userGuid); dims.put("country", countryCode); if (addFallbackDim) { dims.put("fallback", id); } request.put("dims", dims); request.put("counters", stats.getCounters()); request.put("increments", stats.getIncrements()); request.put("gauges", stats.getGauges()); request.put("members", stats.getMembers()); HttpURLConnection conn = null; OutputStream out = null; try { String url = urlFor(id); conn = newConn(url); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/json"); out = conn.getOutputStream(); JsonUtils.OBJECT_MAPPER.writeValue(out, request); int code = conn.getResponseCode(); if (code != 200) { // will be logged below throw new Exception("Got " + code + " response for " + url + ":\n" + conn.getResponseMessage()); } } finally { IOUtils.closeQuietly(out); if (conn != null) { conn.disconnect(); } } } public StatsResponse getStats(final String dimension) throws IOException { HttpURLConnection conn = null; InputStream in = null; try { String url = urlFor(dimension + "/"); conn = newConn(url); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/json"); in = conn.getInputStream(); int code = conn.getResponseCode(); if (code != 200) { // will be logged below throw new IOException("Got " + code + " response for " + url + ":\n" + conn.getResponseMessage()); } return JsonUtils.decode(in, StatsResponse.class); } finally { IOUtils.closeQuietly(in); if (conn != null) { conn.disconnect(); } } } private String urlFor(String instanceId) { return LanternConstants.statshubBaseAddress + instanceId; } }
apache-2.0
Domuska/GildedRose
src/fi/oulu/tol/sqat/ConjuredItem.java
174
package fi.oulu.tol.sqat; public class ConjuredItem extends Item{ public ConjuredItem(String name, int sellIn, int quality){ super(name, sellIn, quality); } }
apache-2.0
mbudiu-vmw/hiero
platform/src/main/java/org/hillview/table/filters/RangeFilterArrayDescription.java
1601
/* * Copyright (c) 2020 VMware Inc. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 * * 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.hillview.table.filters; import org.hillview.table.api.ITable; import org.hillview.table.api.ITableFilter; import org.hillview.table.api.ITableFilterDescription; import org.hillview.utils.Linq; /** * Describes an array of RangeFilters and an optional complement. */ @SuppressWarnings("CanBeFinal") public class RangeFilterArrayDescription implements ITableFilterDescription { public RangeFilterDescription[] filters = new RangeFilterDescription[0]; public boolean complement; @Override public ITableFilter getFilter(ITable table) { String[] cols = Linq.map(this.filters, f -> f.cd.name, String.class); table.getLoadedColumns(cols); ITableFilter[] filters = Linq.map(this.filters, f -> f.getFilter(table), ITableFilter.class); ITableFilter result = new AndFilter(filters); if (this.complement) result = new NotFilter(result); return result; } }
apache-2.0
ExplorViz/ExplorViz
src/explorviz/shared/usertracking/records/application/BackToLandscapeRecord.java
243
package explorviz.shared.usertracking.records.application; import explorviz.shared.usertracking.UsertrackingRecord; public class BackToLandscapeRecord extends UsertrackingRecord { @Override public String csvSerialize() { return ""; } }
apache-2.0
kjetilv/vanadis
launcher/src/main/java/vanadis/launcher/AbstractOSGiLauncher.java
12772
/* * Copyright 2009 Kjetil Valstadsve * * 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 vanadis.launcher; import org.osgi.framework.*; import org.osgi.service.packageadmin.PackageAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import vanadis.blueprints.BundleResolver; import vanadis.blueprints.BundleSpecification; import vanadis.blueprints.SystemSpecification; import vanadis.core.collections.Generic; import vanadis.common.io.Location; import vanadis.core.lang.EntryPoint; import vanadis.core.lang.Not; import vanadis.core.lang.VarArgs; import vanadis.common.time.TimeSpan; import java.io.PrintStream; import java.net.URI; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; @EntryPoint("Subclasses discovered at runtime") public abstract class AbstractOSGiLauncher implements OSGiLauncher { private final AtomicBoolean launched = new AtomicBoolean(false); private final AtomicBoolean failedLaunch = new AtomicBoolean(false); private final AtomicBoolean closed = new AtomicBoolean(false); private URI home; private Location location; private List<BundleResolver> bundleResolvers; private SystemSpecification systemSpecification; private final List<ServiceRegistration> bundleRegistrations = Generic.list(); private final List<ServiceRegistration> moduleRegistrations = Generic.list(); private LaunchResult launchResult; private BundleContext bundleContext; private long bootstrapId; private Dictionary<?, ?> bundleHeaders; @Override public final LaunchResult getLaunchResult() { requireLaunched(); return launchResult; } @Override public final void close(PrintStream stream) { if (!closed.getAndSet(true)) { unregisterAll(stream); stopFramework(); } } @Override public final String getProviderInfo() { requireLaunched(); return bundleHeaders.get(Constants.BUNDLE_SYMBOLICNAME) + " " + bundleHeaders.get(Constants.BUNDLE_VERSION); } @SuppressWarnings({"ThrowCaughtLocally"}) @Override public final LaunchResult launch(URI home, Location location, List<BundleResolver> bundleResolvers, SystemSpecification systemSpecification) { setLaunchState(home, location, bundleResolvers, systemSpecification); try { assertPrelaunchState(this.bundleContext == null); BundleContext bundleContext = launchedBundleContext(); if (bundleContext == null) { throw new IllegalStateException(this + " produced null bundle context!"); } List<Bundle> bundles = startAutoBundles(bundleContext); setLaunchResultState(bundleContext, bundles); registerBundles(); registerModules(); return launchResult; } catch (RuntimeException e) { failedLaunch.set(true); throw e; } } private void setLaunchResultState(BundleContext bundleContext, List<Bundle> bundles) { this.launchResult = new LaunchResult(bundleContext, bundles); this.bundleContext = launchResult.getBundleContext(); Bundle bundle = this.bundleContext.getBundle(); this.bootstrapId = bundle.getBundleId(); this.bundleHeaders = bundle.getHeaders(); } @Override public final boolean isLaunched() { return launched.get() && !failedLaunch.get(); } @Override public final URI getHome() { requireLaunched(); return home; } @Override public final URI getRepo() { return systemSpecification.getRepo(); } @Override public final Location getLocation() { requireLaunched(); return location; } private void assertPrelaunchState(boolean check) { assert check : this + " was launched twice!"; } private void requireLaunched() { if (!launched.get()) { throw new IllegalStateException(this + " not launched"); } if (failedLaunch.get()) { throw new IllegalStateException(this + " failed launch, should be discarded"); } } private List<Bundle> startAutoBundles(BundleContext bundleContext) { List<Bundle> bundles = Generic.list(); for (BundleSpecification specification : getSystemSpecification().getAutoBundles(bundleResolvers)) { bundles.add(install(bundleContext, specification)); } for (Bundle bundle : bundles) { startBundle(bundleContext, bundle, bundles); } resolve(bundleContext); return bundles; } private static void resolve(BundleContext bundleContext) { ServiceReference ref = bundleContext.getServiceReference(PackageAdmin.class.getName()); try { if (ref != null) { PackageAdmin admin = (PackageAdmin) bundleContext.getService(ref); admin.resolveBundles(null); } } finally { bundleContext.ungetService(ref); } } private static void startBundle(BundleContext bundleContext, Bundle bundle, List<Bundle> bundles) { if (isNonFragment(bundle)) { try { bundle.start(); } catch (BundleException e) { throw new StartupException (bundleContext + " failed to start bundle " + bundle + ", " + bundles.size() + " was started: " + bundles, e); } } } protected abstract BundleContext launchedBundleContext(); protected abstract void stopFramework(); protected abstract String osgiExports(); protected final SystemSpecification getSystemSpecification() { return systemSpecification; } protected Map<String, Object> getStandardPackagesConfiguration() { Map<String, Object> configuration = Generic.map(); configuration.put(Constants.FRAMEWORK_SYSTEMPACKAGES, systemPackages()); configuration.put(Constants.FRAMEWORK_BOOTDELEGATION, bootDelegationPackages()); return configuration; } private String systemPackages() { return new StringBuilder (SystemPackages.JDK).append(",").append (osgiExports()).append(",").append (SystemPackages.UTIL).toString(); } private static String bootDelegationPackages() { String[] bootDelegationPackages = new String[]{SystemPackages.PROFILING, SystemPackages.COVERAGE}; if (VarArgs.present(bootDelegationPackages)) { StringBuilder sb = new StringBuilder(bootDelegationPackages[0]); for (int i = 1; i < bootDelegationPackages.length; i++) { sb.append(",").append(bootDelegationPackages[i]); } return sb.toString(); } return null; } protected final void setLaunchState(URI home, Location location, List<BundleResolver> bundleResolvers, SystemSpecification systemSpecification) { if (launched.getAndSet(true)) { throw new IllegalArgumentException(this + " already launched"); } this.home = setOnceTo(this.home, home, "home"); this.location = setOnceTo(this.location, location, "location"); this.bundleResolvers = setOnceTo(this.bundleResolvers, bundleResolvers, "bundle resolvers"); this.systemSpecification = setOnceTo(this.systemSpecification, systemSpecification, "system specification"); } private <T> T setOnceTo(T current, T value, String desc) { assert current == null : this + " was launched twice, " + desc + " was set to " + current; return Not.nil(value, desc); } private void registerBundles() { registerAll(bundleRegistrations, systemSpecification.getDynaBundles()); } private void registerModules() { registerAll(moduleRegistrations, systemSpecification.moduleSpecifications()); } private void registerAll(List<ServiceRegistration> registrationList, Collection<?> objects) { requireLaunched(); for (Object object : objects) { registrationList.add(registrationOf(object)); } } private void unregisterAll(PrintStream stream) { if (launchResult == null) { return; } print(stream, "["); unregister(moduleRegistrations); defaultWait(new ReferenceVanishWaiter("vanadis.ext.ObjectManager", null, 5, stream, launchResult), "ObjectManagers still present, continuing..."); unregister(bundleRegistrations); defaultWait(new ReferenceVanishWaiter("vanadis.ext.ObjectManagerFactory", null, 5, stream, launchResult), "ObjectManagers still present, continuing..."); print(stream, "|"); uninstallAll(launchResult.getNonCoreBundles(), stream); print(stream, "|"); uninstallAll(launchResult.getAutoBundles(true), stream); print(stream, "]"); } private ServiceRegistration registrationOf(Object object) { return bundleContext.registerService(object.getClass().getName(), object, null); } private void uninstallAll(List<Bundle> bundles, PrintStream stream) { for (Bundle bundle : bundles) { long bundleId = bundle.getBundleId(); if (bundleId > 0 && bundleId != bootstrapId) { try { shutdown(bundle); print(stream, "."); } catch (Throwable e) { if (log.isDebugEnabled()) { log.debug("Bundle " + bundleId + " failed to stop: " + bundle, e); } print(stream, "x"); } } } } private static final Logger log = LoggerFactory.getLogger(AbstractOSGiLauncher.class); private static void shutdown(Bundle bundle) throws BundleException { String bundleString = null; try { bundleString = bundle.toString() + " (" + bundle.getSymbolicName() + ")"; } catch (Exception e) { log.warn("Failed to get bundle data", e); } try { int state = bundle.getState(); if (state == Bundle.ACTIVE || state == Bundle.STARTING || state == Bundle.STOPPING) { bundle.stop(); } } finally { try { bundle.uninstall(); } catch (Throwable e) { log.warn("Bundle " + bundleString + " failed to uninstall", e); } } log.info("Shutdown: " + bundleString); } private static boolean isNonFragment(Bundle bundle) { return bundle.getHeaders().get(Constants.FRAGMENT_HOST) == null; } private static Bundle install(BundleContext bundleContext, BundleSpecification specification) { try { return bundleContext.installBundle(specification.getUrlString()); } catch (BundleException e) { throw new StartupException("Failed to install start bundle at " + specification, e); } } private static void print(PrintStream stream, Object object) { if (stream != null) { stream.print(object); } } private static void defaultWait(Waiter waiter, String warning) { if (!wait(waiter, TimeSpan.MINUTE, TimeSpan.millis(250))) { log.warn(warning); } } private static void unregister(List<ServiceRegistration> regs) { List<ServiceRegistration> reversed = Generic.list(regs); Collections.reverse(reversed); for (ServiceRegistration registration : reversed) { try { registration.unregister(); } catch (Exception e) { log.warn("Failed to unregister " + registration, e); } } } private static Boolean wait(Waiter waiter, TimeSpan timeout, TimeSpan retry) { return timeout.newDeadline().tryEvery(retry, waiter); } }
apache-2.0
Snadde/infotainment
apps/sensors/src/se/chalmers/pd/sensors/Controller.java
1389
package se.chalmers.pd.sensors; import org.json.JSONException; import org.json.JSONObject; /** * This controller class creates messages and asks a mqtt worker to publish * them. The worker is instantiated when the object is created and the thread is * started. There is no guarantee however that the thread will start and connect * immediately. */ public class Controller { private static final String TOPIC = "/sensor/infotainment"; private MqttWorker mqttWorker; /** * Creates a an mqtt client and tells it to connect */ public Controller() { mqttWorker = new MqttWorker(); mqttWorker.start(); } /** * Tells the mqtt client to publish a message on this specific sensor topic with * the action message. */ public void performAction(Action action) { mqttWorker.publish(TOPIC, getJsonMessage(action)); } /** * Helper method to create a json object that can be stringified and sent to * the receiver. * * @param action * the action that the message will contain * @return a stringified json object containing the action that is passed * in. */ private String getJsonMessage(Action action) { JSONObject message = new JSONObject(); try { message.put(Action.action.toString(), action.toString()); } catch (JSONException e) { e.printStackTrace(); } return message.toString(); } }
apache-2.0
philipwhiuk/q-mail
qmail-library/src/main/java/com/fsck/k9/mail/store/imap/ImapResponseParser.java
15316
package com.fsck.k9.mail.store.imap; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.fsck.k9.mail.K9MailLib; import com.fsck.k9.mail.filter.FixedLengthInputStream; import com.fsck.k9.mail.filter.PeekableInputStream; import timber.log.Timber; import static com.fsck.k9.mail.K9MailLib.DEBUG_PROTOCOL_IMAP; class ImapResponseParser { private PeekableInputStream inputStream; private ImapResponse response; private Exception exception; public ImapResponseParser(PeekableInputStream in) { this.inputStream = in; } public ImapResponse readResponse() throws IOException { return readResponse(null); } /** * Reads the next response available on the stream and returns an {@code ImapResponse} object that represents it. */ public ImapResponse readResponse(ImapResponseCallback callback) throws IOException { try { int peek = inputStream.peek(); if (peek == '+') { readContinuationRequest(callback); } else if (peek == '*') { readUntaggedResponse(callback); } else { readTaggedResponse(callback); } if (exception != null) { throw new ImapResponseParserException("readResponse(): Exception in callback method", exception); } return response; } finally { response = null; exception = null; } } private void readContinuationRequest(ImapResponseCallback callback) throws IOException { parseCommandContinuationRequest(); response = ImapResponse.newContinuationRequest(callback); skipIfSpace(); String rest = readStringUntilEndOfLine(); response.add(rest); } private void readUntaggedResponse(ImapResponseCallback callback) throws IOException { parseUntaggedResponse(); response = ImapResponse.newUntaggedResponse(callback); readTokens(response); } private void readTaggedResponse(ImapResponseCallback callback) throws IOException { String tag = parseTaggedResponse(); response = ImapResponse.newTaggedResponse(callback, tag); readTokens(response); } List<ImapResponse> readStatusResponse(String tag, String commandToLog, String logId, UntaggedHandler untaggedHandler) throws IOException, NegativeImapResponseException { List<ImapResponse> responses = new ArrayList<ImapResponse>(); ImapResponse response; do { response = readResponse(); if (K9MailLib.isDebug() && DEBUG_PROTOCOL_IMAP) { Timber.v("%s<<<%s", logId, response); } if (response.getTag() != null && !response.getTag().equalsIgnoreCase(tag)) { Timber.w("After sending tag %s, got tag response from previous command %s for %s", tag, response, logId); Iterator<ImapResponse> responseIterator = responses.iterator(); while (responseIterator.hasNext()) { ImapResponse delResponse = responseIterator.next(); if (delResponse.getTag() != null || delResponse.size() < 2 || ( !equalsIgnoreCase(delResponse.get(1), Responses.EXISTS) && !equalsIgnoreCase(delResponse.get(1), Responses.EXPUNGE))) { responseIterator.remove(); } } response = null; continue; } if (response.getTag() == null && untaggedHandler != null) { untaggedHandler.handleAsyncUntaggedResponse(response); } responses.add(response); } while (response == null || response.getTag() == null); if (response.size() < 1 || !equalsIgnoreCase(response.get(0), Responses.OK)) { String message = "Command: " + commandToLog + "; response: " + response.toString(); throw new NegativeImapResponseException(message, responses); } return responses; } private void readTokens(ImapResponse response) throws IOException { response.clear(); Object firstToken = readToken(response); checkTokenIsString(firstToken); String symbol = (String) firstToken; response.add(symbol); if (isStatusResponse(symbol)) { parseResponseText(response); } else if (equalsIgnoreCase(symbol, Responses.LIST) || equalsIgnoreCase(symbol, Responses.LSUB)) { parseListResponse(response); } else { Object token; while ((token = readToken(response)) != null) { if (!(token instanceof ImapList)) { response.add(token); } } } } /** * Parse {@code resp-text} tokens * <p> * Responses "OK", "PREAUTH", "BYE", "NO", "BAD", and continuation request responses can * contain {@code resp-text} tokens. We parse the {@code resp-text-code} part as tokens and * read the rest as sequence of characters to avoid the parser interpreting things like * "{123}" as start of a literal. * </p> * <p>Example:</p> * <p> * {@code * OK [UIDVALIDITY 3857529045] UIDs valid} * </p> * <p> * See RFC 3501, Section 9 Formal Syntax (resp-text) * </p> * * @param parent * The {@link ImapResponse} instance that holds the parsed tokens of the response. * * @throws IOException * If there's a network error. * * @see #isStatusResponse(String) */ private void parseResponseText(ImapResponse parent) throws IOException { skipIfSpace(); int next = inputStream.peek(); if (next == '[') { parseList(parent, '[', ']'); skipIfSpace(); } String rest = readStringUntilEndOfLine(); if (rest != null && !rest.isEmpty()) { // The rest is free-form text. parent.add(rest); } } private void parseListResponse(ImapResponse response) throws IOException { expect(' '); parseList(response, '(', ')'); expect(' '); String delimiter = parseQuotedOrNil(); response.add(delimiter); expect(' '); String name = parseString(); response.add(name); expect('\r'); expect('\n'); } private void skipIfSpace() throws IOException { if (inputStream.peek() == ' ') { expect(' '); } } /** * Reads the next token of the response. The token can be one of: String - * for NIL, QUOTED, NUMBER, ATOM. Object - for LITERAL. * ImapList - for PARENTHESIZED LIST. Can contain any of the above * elements including List. * * @return The next token in the response or null if there are no more * tokens. */ private Object readToken(ImapResponse response) throws IOException { while (true) { Object token = parseToken(response); if (token == null || !(token.equals(")") || token.equals("]"))) { return token; } } } private Object parseToken(ImapList parent) throws IOException { while (true) { int ch = inputStream.peek(); if (ch == '(') { return parseList(parent, '(', ')'); } else if (ch == '[') { return parseList(parent, '[', ']'); } else if (ch == ')') { expect(')'); return ")"; } else if (ch == ']') { expect(']'); return "]"; } else if (ch == '"') { return parseQuoted(); } else if (ch == '{') { return parseLiteral(); } else if (ch == ' ') { expect(' '); } else if (ch == '\r') { expect('\r'); expect('\n'); return null; } else if (ch == '\n') { expect('\n'); return null; } else if (ch == '\t') { expect('\t'); } else { return parseBareString(true); } } } private String parseString() throws IOException { int ch = inputStream.peek(); if (ch == '"') { return parseQuoted(); } else if (ch == '{') { return (String) parseLiteral(); } else { return parseBareString(false); } } private boolean parseCommandContinuationRequest() throws IOException { expect('+'); return true; } private void parseUntaggedResponse() throws IOException { expect('*'); expect(' '); } private String parseTaggedResponse() throws IOException { return readStringUntil(' '); } private ImapList parseList(ImapList parent, char start, char end) throws IOException { expect(start); ImapList list = new ImapList(); parent.add(list); String endString = String.valueOf(end); Object token; while (true) { token = parseToken(list); if (token == null) { return null; } else if (token.equals(endString)) { break; } else if (!(token instanceof ImapList)) { list.add(token); } } return list; } private String parseBareString(boolean allowBrackets) throws IOException { StringBuilder sb = new StringBuilder(); int ch; while (true) { ch = inputStream.peek(); if (ch == -1) { throw new IOException("parseBareString(): end of stream reached"); } if (ch == '(' || ch == ')' || (allowBrackets && (ch == '[' || ch == ']')) || ch == '{' || ch == ' ' || ch == '"' || (ch >= 0x00 && ch <= 0x1f) || ch == 0x7f) { if (sb.length() == 0) { throw new IOException(String.format("parseBareString(): (%04x %c)", ch, ch)); } return sb.toString(); } else { sb.append((char) inputStream.read()); } } } /** * A "{" has been read. Read the rest of the size string, the space and then notify the callback with an * {@code InputStream}. */ private Object parseLiteral() throws IOException { expect('{'); int size = Integer.parseInt(readStringUntil('}')); expect('\r'); expect('\n'); if (size == 0) { return ""; } if (response.getCallback() != null) { FixedLengthInputStream fixed = new FixedLengthInputStream(inputStream, size); Exception callbackException = null; Object result = null; try { result = response.getCallback().foundLiteral(response, fixed); } catch (IOException e) { throw e; } catch (Exception e) { callbackException = e; } boolean someDataWasRead = fixed.available() != size; if (someDataWasRead) { if (result == null && callbackException == null) { throw new AssertionError("Callback consumed some data but returned no result"); } fixed.skipRemaining(); } if (callbackException != null) { if (exception == null) { exception = callbackException; } return "EXCEPTION"; } if (result != null) { return result; } } byte[] data = new byte[size]; int read = 0; while (read != size) { int count = inputStream.read(data, read, size - read); if (count == -1) { throw new IOException("parseLiteral(): end of stream reached"); } read += count; } return new String(data, "US-ASCII"); } private String parseQuoted() throws IOException { expect('"'); StringBuilder sb = new StringBuilder(); int ch; boolean escape = false; while ((ch = inputStream.read()) != -1) { if (!escape && ch == '\\') { // Found the escape character escape = true; } else if (!escape && ch == '"') { return sb.toString(); } else { sb.append((char) ch); escape = false; } } throw new IOException("parseQuoted(): end of stream reached"); } private String parseQuotedOrNil() throws IOException { int peek = inputStream.peek(); if (peek == '"') { return parseQuoted(); } else { parseNil(); return null; } } private void parseNil() throws IOException { expect('N'); expect('I'); expect('L'); } private String readStringUntil(char end) throws IOException { StringBuilder sb = new StringBuilder(); int ch; while ((ch = inputStream.read()) != -1) { if (ch == end) { return sb.toString(); } else { sb.append((char) ch); } } throw new IOException("readStringUntil(): end of stream reached. " + "Read: \"" + sb.toString() + "\" while waiting for " + formatChar(end)); } private String formatChar(char value) { return value < 32 ? "[" + Integer.toString(value) + "]" : "'" + value + "'"; } private String readStringUntilEndOfLine() throws IOException { String rest = readStringUntil('\r'); expect('\n'); return rest; } private void expect(char expected) throws IOException { int readByte = inputStream.read(); if (readByte != expected) { throw new IOException(String.format("Expected %04x (%c) but got %04x (%c)", (int) expected, expected, readByte, (char) readByte)); } } private boolean isStatusResponse(String symbol) { return symbol.equalsIgnoreCase(Responses.OK) || symbol.equalsIgnoreCase(Responses.NO) || symbol.equalsIgnoreCase(Responses.BAD) || symbol.equalsIgnoreCase(Responses.PREAUTH) || symbol.equalsIgnoreCase(Responses.BYE); } static boolean equalsIgnoreCase(Object token, String symbol) { if (token == null || !(token instanceof String)) { return false; } return symbol.equalsIgnoreCase((String) token); } private void checkTokenIsString(Object token) throws IOException { if (!(token instanceof String)) { throw new IOException("Unexpected non-string token: " + token.getClass().getSimpleName() + " - " + token); } } }
apache-2.0
williamxu/DangoReader
app/src/main/java/moe/dangoreader/activity/MangaItemActivity.java
5092
package moe.dangoreader.activity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import io.paperdb.Paper; import moe.dangoreader.R; import moe.dangoreader.UserLibraryHelper; import moe.dangoreader.adapter.MangaItemPageAdapter; import moe.dangoreader.database.Manga; import moe.dangoreader.model.MangaEdenMangaDetailItem; import moe.dangoreader.parse.MangaEden; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; /** * Activity that displays a single manga, and shows manga info and chapters */ public class MangaItemActivity extends AppCompatActivity { private Manga manga; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_manga_item); Paper.init(this); findViewById(R.id.manga_item_pager).setVisibility(View.GONE); initToolBar(); String mangaId = getIntent().getStringExtra("mangaId"); manga = Paper.book(UserLibraryHelper.USER_LIBRARY_DB).read(mangaId); // if (manga != null && manga.chaptersList != null) { // initViewPager(); // initMarqueeTitle(); // } fetchMangaDetailFromMangaEden(mangaId); } private void initToolBar() { Toolbar toolbar = (Toolbar) findViewById(R.id.manga_item_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } private void initViewPager() { ViewPager viewPager = (ViewPager) findViewById(R.id.manga_item_pager); MangaItemPageAdapter mangaItemPageAdapter = new MangaItemPageAdapter(this, getSupportFragmentManager(), manga.id); viewPager.setAdapter(mangaItemPageAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.manga_item_tabs); tabLayout.setupWithViewPager(viewPager); findViewById(R.id.manga_item_placeholder).setVisibility(View.GONE); findViewById(R.id.manga_item_pager).setVisibility(View.VISIBLE); } private void initMarqueeTitle() { TextView mangaTitleView = (TextView) findViewById(R.id.manga_item_chapter_title); mangaTitleView.setText(manga.title); mangaTitleView.setSelected(true); // for marquee to scroll } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_manga_item, menu); MenuItem bookmarkItem = menu.findItem(R.id.manga_item_bookmark_button); final MangaItemActivity activity = this; final ImageButton bookmarkToggle = new ImageButton(this); bookmarkToggle.setImageResource(R.drawable.bookmark_toggle); bookmarkToggle.setSelected(manga != null && manga.favorite); bookmarkToggle.setBackgroundResource(R.color.transparent); bookmarkToggle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (bookmarkToggle.isSelected()) { UserLibraryHelper.removeFromLibrary(manga, bookmarkToggle, activity, true, null, -1); } else { UserLibraryHelper.addToLibrary(manga, bookmarkToggle, activity, true, null, -1); } } }); bookmarkItem.setActionView(bookmarkToggle); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } private void fetchMangaDetailFromMangaEden(final String mangaId) { Log.d("MangaItemActivity", "Fetching manga details"); MangaEden.getMangaEdenService(this) .getMangaDetails(mangaId) .enqueue(new Callback<MangaEdenMangaDetailItem>() { @Override public void onResponse(Response<MangaEdenMangaDetailItem> response, Retrofit retrofit) { MangaEdenMangaDetailItem mangaDetailItem = response.body(); manga = UserLibraryHelper.updateManga(mangaId, mangaDetailItem); initViewPager(); initMarqueeTitle(); } @Override public void onFailure(Throwable t) { Log.e("MangaItemActivity", "Could not fetch details from MangaEden"); } }); } }
apache-2.0
12315jack/j1st-mqtt
j1st-mqtt-api/src/main/java/com/github/j1stiot/mqtt/api/internal/InternalMessage.java
13361
package com.github.j1stiot.mqtt.api.internal; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.mqtt.*; import org.apache.commons.lang3.StringUtils; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Represent MQTT Message passed in Communicator */ @SuppressWarnings("unused") public class InternalMessage<T> implements Serializable { // fixed header private MqttMessageType messageType; private boolean dup; private MqttQoS qos; private boolean retain; // some info in CONNECT message, but useful for stateless transfer private MqttVersion version; private String clientId; private String userName; // broker id, only meaningful when the message is sent by broker private String brokerId; // variable header and payload private T payload; protected InternalMessage() { } public InternalMessage(MqttMessageType messageType, boolean dup, MqttQoS qos, boolean retain, MqttVersion version, String clientId, String userName, String brokerId) { this(messageType, dup, qos, retain, version, clientId, userName, brokerId, null); } public InternalMessage(MqttMessageType messageType, boolean dup, MqttQoS qos, boolean retain, MqttVersion version, String clientId, String userName, String brokerId, T payload) { this.messageType = messageType; this.dup = dup; this.qos = qos; this.retain = retain; this.version = version; this.clientId = clientId; this.userName = userName; this.brokerId = brokerId; this.payload = payload; } protected static <T> InternalMessage<T> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttFixedHeader fixedHeader) { return new InternalMessage<>(fixedHeader.messageType(), fixedHeader.dup(), fixedHeader.qos(), fixedHeader.retain(), version, clientId, userName, brokerId); } public static InternalMessage<Connect> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttConnectMessage mqtt) { InternalMessage<Connect> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); msg.payload = mqtt.variableHeader().willFlag() ? new Connect(mqtt.variableHeader().cleanSession(), mqtt.variableHeader().willRetain(), mqtt.variableHeader().willQos(), mqtt.payload().willTopic(), mqtt.payload().willMessage().getBytes()) : new Connect(mqtt.variableHeader().cleanSession(), false, MqttQoS.AT_MOST_ONCE, null, null); return msg; } public static InternalMessage<ConnAck> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttConnAckMessage mqtt) { InternalMessage<ConnAck> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); msg.payload = new ConnAck(mqtt.variableHeader().returnCode(), mqtt.variableHeader().sessionPresent()); return msg; } public static InternalMessage<Subscribe> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttSubscribeMessage mqtt, List<MqttGrantedQoS> returnCodes) { InternalMessage<Subscribe> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); // forge topic subscriptions if (mqtt.payload().subscriptions().size() != returnCodes.size()) { throw new IllegalArgumentException("MQTT SUBSCRIBE message's subscriptions count not equal to granted QoS count"); } List<TopicSubscription> topicSubscriptions = new ArrayList<>(); for (int i = 0; i < mqtt.payload().subscriptions().size(); i++) { TopicSubscription subscription = new TopicSubscription(mqtt.payload().subscriptions().get(i).topic(), returnCodes.get(i)); topicSubscriptions.add(subscription); } msg.payload = new Subscribe(mqtt.variableHeader().packetId(), topicSubscriptions); return msg; } public static InternalMessage<SubAck> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttSubAckMessage mqtt) { InternalMessage<SubAck> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); msg.payload = new SubAck(mqtt.variableHeader().packetId(), mqtt.payload().grantedQoSLevels()); return msg; } public static InternalMessage<Unsubscribe> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttUnsubscribeMessage mqtt) { InternalMessage<Unsubscribe> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); msg.payload = new Unsubscribe(mqtt.variableHeader().packetId(), mqtt.payload().topics()); return msg; } public static InternalMessage<Publish> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttPublishMessage mqtt) { InternalMessage<Publish> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); // forge bytes payload ByteBuf buf = mqtt.payload().duplicate(); byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); msg.payload = new Publish(mqtt.variableHeader().topicName(), mqtt.variableHeader().packetId(), bytes); return msg; } public static InternalMessage<Publish> fromMqttMessage(String topic, MqttVersion version, String clientId, String userName, String brokerId, MqttPublishMessage mqtt) { InternalMessage<Publish> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); // forge bytes payload ByteBuf buf = mqtt.payload().duplicate(); byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); msg.payload = new Publish(topic, mqtt.variableHeader().packetId(), bytes); return msg; } public static InternalMessage<Disconnect> fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, boolean cleanSession, boolean cleanExit) { return new InternalMessage<>(MqttMessageType.DISCONNECT, false, MqttQoS.AT_MOST_ONCE, false, version, clientId, userName, brokerId, new Disconnect(cleanSession, cleanExit)); } public static InternalMessage fromMqttMessage(MqttVersion version, String clientId, String userName, String brokerId, MqttMessage mqtt) { if (mqtt.variableHeader() != null && mqtt.variableHeader() instanceof MqttPacketIdVariableHeader) { InternalMessage<PacketId> msg = fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); msg.payload = new PacketId(((MqttPacketIdVariableHeader) mqtt.variableHeader()).packetId()); return msg; } else { return fromMqttMessage(version, clientId, userName, brokerId, mqtt.fixedHeader()); } } public MqttMessageType getMessageType() { return messageType; } public void setMessageType(MqttMessageType messageType) { this.messageType = messageType; } public boolean isDup() { return dup; } public void setDup(boolean dup) { this.dup = dup; } public MqttQoS getQos() { return qos; } public void setQos(MqttQoS qos) { this.qos = qos; } public boolean isRetain() { return retain; } public void setRetain(boolean retain) { this.retain = retain; } public MqttVersion getVersion() { return version; } public void setVersion(MqttVersion version) { this.version = version; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getBrokerId() { return brokerId; } public void setBrokerId(String brokerId) { this.brokerId = brokerId; } public T getPayload() { return payload; } public void setPayload(T payload) { this.payload = payload; } public MqttMessage toMqttMessage() { MqttFixedHeader fixedHeader = new MqttFixedHeader(messageType, dup, qos, retain, 0); switch (messageType) { case CONNECT: Connect connect = (Connect) payload; boolean userNameFlag = StringUtils.isNotBlank(userName); boolean willFlag = connect.getWillMessage() != null && connect.getWillMessage().length > 0; return MqttMessageFactory.newMessage(fixedHeader, new MqttConnectVariableHeader(version.protocolName(), version.protocolLevel(), userNameFlag, false, connect.isWillRetain(), connect.getWillQos(), willFlag, connect.isCleanSession(), 0), new MqttConnectPayload(clientId, connect.getWillTopic(), new String(connect.getWillMessage()), userName, null)); case CONNACK: ConnAck connAck = (ConnAck) payload; return MqttMessageFactory.newMessage(fixedHeader, new MqttConnAckVariableHeader(connAck.getReturnCode(), connAck.isSessionPresent()), null); case SUBSCRIBE: Subscribe subscribe = (Subscribe) payload; List<MqttTopicSubscription> subscriptions = new ArrayList<>(); subscribe.getSubscriptions().forEach(s -> subscriptions.add(new MqttTopicSubscription(s.getTopic(), MqttQoS.valueOf(s.getGrantedQos().value()))) ); return MqttMessageFactory.newMessage(fixedHeader, MqttPacketIdVariableHeader.from(subscribe.getPacketId()), new MqttSubscribePayload(subscriptions)); case SUBACK: SubAck subAck = (SubAck) payload; return MqttMessageFactory.newMessage(fixedHeader, MqttPacketIdVariableHeader.from(subAck.getPacketId()), new MqttSubAckPayload(subAck.getGrantedQoSLevels())); case UNSUBSCRIBE: Unsubscribe unsubscribe = (Unsubscribe) payload; return MqttMessageFactory.newMessage(fixedHeader, MqttPacketIdVariableHeader.from(unsubscribe.getPacketId()), new MqttUnsubscribePayload(unsubscribe.getTopics())); case PUBLISH: Publish publish = (Publish) payload; return MqttMessageFactory.newMessage(fixedHeader, (qos == MqttQoS.AT_MOST_ONCE) ? MqttPublishVariableHeader.from(publish.getTopicName()) : MqttPublishVariableHeader.from(publish.getTopicName(), publish.getPacketId()), (publish.getPayload() != null && publish.getPayload().length > 0) ? Unpooled.wrappedBuffer(publish.getPayload()) : Unpooled.EMPTY_BUFFER); case UNSUBACK: case PUBACK: case PUBREC: case PUBREL: case PUBCOMP: PacketId packetId = (PacketId) payload; return MqttMessageFactory.newMessage(fixedHeader, MqttPacketIdVariableHeader.from(packetId.getPacketId()), null); case PINGREQ: case PINGRESP: case DISCONNECT: return MqttMessageFactory.newMessage(fixedHeader, null, null); default: throw new IllegalStateException("unknown message type " + messageType); } } }
apache-2.0
BladeRunnerJS/brjs-JsTestDriver
JsTestDriver/src/com/google/jstestdriver/output/XmlPrinterImpl.java
3937
/* * Copyright 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.jstestdriver.output; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.inject.Inject; import com.google.inject.name.Named; import com.google.jstestdriver.BrowserInfo; import com.google.jstestdriver.TestResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Set; /** * @author jeremiele@google.com (Jeremie Lenfant-Engelmann) */ public class XmlPrinterImpl implements XmlPrinter { private final Logger logger = LoggerFactory.getLogger(XmlPrinterImpl.class); private final TestResultHolder resultHolder; private final String xmlOutputDir; private final String fileNameFormat = "TEST-%s.xml"; private final FileNameFormatter formatter; @Inject public XmlPrinterImpl(TestResultHolder resultHolder, @Named("testOutput") String xmlOutputDir, FileNameFormatter formatter) { this.resultHolder = resultHolder; this.xmlOutputDir = xmlOutputDir; this.formatter = formatter; } public void writeXmlReportFiles() { Map<BrowserInfo, String> browserNames = createUniqueBrowserNames(resultHolder.getResults().keySet()); for (BrowserInfo browser : resultHolder.getResults().keySet()) { Multimap<String, TestResult> testCaseRollup = newMultiMap(); for (TestResult testResult : resultHolder.getResults().get(browser)) { testCaseRollup.put(testResult.getTestCaseName(), testResult); } for (String testCaseName : testCaseRollup.keySet()) { String suiteName = formatSuiteName(browserNames.get(browser), testCaseName); File xmlOutputFile = new File(xmlOutputDir, formatFileName(suiteName)); try { xmlOutputFile.createNewFile(); TestXmlSerializer serializer = new TestXmlSerializer(new FileWriter(xmlOutputFile)); serializer.writeTestCase(suiteName, testCaseRollup.get(testCaseName)); } catch (IOException e) { logger.error("Could not create file: {}", xmlOutputFile.getAbsolutePath(), e); } } } } public static Map<BrowserInfo, String> createUniqueBrowserNames(Set<BrowserInfo> browserInfos) { Map<BrowserInfo, String> result = Maps.newHashMap(); for (BrowserInfo browserInfo : browserInfos) { if (result.containsValue(browserInfo.toString())) { result.put(browserInfo, browserInfo.toUniqueString()); } else { result.put(browserInfo, browserInfo.toString()); } } return result; } private String formatFileName(String suiteName) { return formatter.format(suiteName, fileNameFormat); } private String formatSuiteName(String browser, String testCaseName) { return String.format("%s.%s", browser.replaceAll("\\s", "_").replaceAll("\\.", ""), testCaseName); } private Multimap<String, TestResult> newMultiMap() { return Multimaps.newMultimap( Maps.<String, Collection<TestResult>>newHashMap(), new Supplier<Collection<TestResult>>() { public Collection<TestResult> get() { return Lists.newLinkedList(); } }); } }
apache-2.0
cristiani/encuestame
enme-business/src/main/java/org/encuestame/business/cron/RemoveUnconfirmedAccountJob.java
3004
/* ************************************************************************************ * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2009 * encuestame Development Team. * Licensed under the Apache Software License version 2.0 * 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.encuestame.business.cron; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.encuestame.core.config.EnMePlaceHolderConfigurer; import org.encuestame.core.service.imp.SecurityOperations; import org.encuestame.persistence.dao.IAccountDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; /** * Remove unconfirmed account Job. * @author Morales, Diana Paola paolaATencuestame.org * @since Jul 19, 2011 */ public class RemoveUnconfirmedAccountJob { /** {@link IAccountDao} **/ @Autowired private IAccountDao accountDao; /** {@link SecurityOperations} **/ @Autowired private SecurityOperations securityService; /** * Log. */ private static final Log log = LogFactory.getLog(RemoveUnconfirmedAccountJob.class); /** * */ public RemoveUnconfirmedAccountJob() { log.debug("Unconfirmed Account Const"); } /** * Remove unconfirmed accounts. */ @Scheduled(cron = "${cron.removeUnconfirmedAccount}") public void removeUnconfirmedAccount(){ log.info("EnMePlaceHolderConfigurer.getSystemInstalled()" + EnMePlaceHolderConfigurer.getSystemInstalled()); if (EnMePlaceHolderConfigurer.getSystemInstalled()) { log.info("Removing non confirmed accounts..."); try { getSecurityService().removeUnconfirmedAccount(Boolean.FALSE); } catch (Exception e) { log.error("Owner account not found to change status"); } } } /** * @return the accountDao */ public IAccountDao getAccountDao() { return accountDao; } /** * @param accountDao the accountDao to set */ public void setAccountDao(IAccountDao accountDao) { this.accountDao = accountDao; } /** * @return the securityService */ public SecurityOperations getSecurityService() { return securityService; } /** * @param securityService the securityService to set */ public void setSecurityService(SecurityOperations securityService) { this.securityService = securityService; } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-proton/src/main/java/com/amazonaws/services/proton/model/transform/ServicePipelineJsonUnmarshaller.java
5087
/* * 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.proton.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.proton.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ServicePipeline JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ServicePipelineJsonUnmarshaller implements Unmarshaller<ServicePipeline, JsonUnmarshallerContext> { public ServicePipeline unmarshall(JsonUnmarshallerContext context) throws Exception { ServicePipeline servicePipeline = new ServicePipeline(); 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("arn", targetDepth)) { context.nextToken(); servicePipeline.setArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("createdAt", targetDepth)) { context.nextToken(); servicePipeline.setCreatedAt(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("deploymentStatus", targetDepth)) { context.nextToken(); servicePipeline.setDeploymentStatus(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("deploymentStatusMessage", targetDepth)) { context.nextToken(); servicePipeline.setDeploymentStatusMessage(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("lastDeploymentAttemptedAt", targetDepth)) { context.nextToken(); servicePipeline.setLastDeploymentAttemptedAt(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("lastDeploymentSucceededAt", targetDepth)) { context.nextToken(); servicePipeline.setLastDeploymentSucceededAt(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } if (context.testExpression("spec", targetDepth)) { context.nextToken(); servicePipeline.setSpec(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("templateMajorVersion", targetDepth)) { context.nextToken(); servicePipeline.setTemplateMajorVersion(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("templateMinorVersion", targetDepth)) { context.nextToken(); servicePipeline.setTemplateMinorVersion(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("templateName", targetDepth)) { context.nextToken(); servicePipeline.setTemplateName(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 servicePipeline; } private static ServicePipelineJsonUnmarshaller instance; public static ServicePipelineJsonUnmarshaller getInstance() { if (instance == null) instance = new ServicePipelineJsonUnmarshaller(); return instance; } }
apache-2.0
jpbirdy/WordsDetection
weibo/src/main/java/weibo4j/http/HttpClient.java
18712
package weibo4j.http; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.*; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.log4j.Logger; import weibo4j.model.*; import weibo4j.org.json.JSONException; import javax.activation.MimetypesFileTypeMap; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; /** * @author sinaWeibo */ public class HttpClient implements java.io.Serializable { private static final long serialVersionUID = -176092625883595547L; private static final int OK = 200;// OK: Success! private static final int NOT_MODIFIED = 304;// Not Modified: There was no new data to return. private static final int BAD_REQUEST = 400;// Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting. private static final int NOT_AUTHORIZED = 401;// Not Authorized: Authentication credentials were missing or incorrect. private static final int FORBIDDEN = 403;// Forbidden: The request is understood, but it has been refused. An accompanying error message will explain why. private static final int NOT_FOUND = 404;// Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists. private static final int NOT_ACCEPTABLE = 406;// Not Acceptable: Returned by the Search API when an invalid format is specified in the request. private static final int INTERNAL_SERVER_ERROR = 500;// Internal Server Error: Something is broken. Please post to the group so the Weibo team can investigate. private static final int BAD_GATEWAY = 502;// Bad Gateway: Weibo is down or being upgraded. private static final int SERVICE_UNAVAILABLE = 503;// Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited. private String proxyHost = Configuration.getProxyHost(); private int proxyPort = Configuration.getProxyPort(); private String proxyAuthUser = Configuration.getProxyUser(); private String proxyAuthPassword = Configuration.getProxyPassword(); public String getProxyHost() { return proxyHost; } /** * Sets proxy host. System property -Dsinat4j.http.proxyHost or * http.proxyHost overrides this attribute. * * @param proxyHost */ public void setProxyHost(String proxyHost) { this.proxyHost = Configuration.getProxyHost(proxyHost); } public int getProxyPort() { return proxyPort; } /** * Sets proxy port. System property -Dsinat4j.http.proxyPort or * -Dhttp.proxyPort overrides this attribute. * * @param proxyPort */ public void setProxyPort(int proxyPort) { this.proxyPort = Configuration.getProxyPort(proxyPort); } public String getProxyAuthUser() { return proxyAuthUser; } /** * Sets proxy authentication user. System property -Dsinat4j.http.proxyUser * overrides this attribute. * * @param proxyAuthUser */ public void setProxyAuthUser(String proxyAuthUser) { this.proxyAuthUser = Configuration.getProxyUser(proxyAuthUser); } public String getProxyAuthPassword() { return proxyAuthPassword; } /** * Sets proxy authentication password. System property * -Dsinat4j.http.proxyPassword overrides this attribute. * * @param proxyAuthPassword */ public void setProxyAuthPassword(String proxyAuthPassword) { this.proxyAuthPassword = Configuration.getProxyPassword(proxyAuthPassword); } private final static boolean DEBUG = Configuration.getDebug(); static Logger log = Logger.getLogger(HttpClient.class.getName()); org.apache.commons.httpclient.HttpClient client = null; private MultiThreadedHttpConnectionManager connectionManager; private int maxSize; public HttpClient() { this(150, 30000, 30000, 1024 * 1024); } public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs, int maxSize) { connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = connectionManager.getParams(); params.setDefaultMaxConnectionsPerHost(maxConPerHost); params.setConnectionTimeout(conTimeOutMs); params.setSoTimeout(soTimeOutMs); HttpClientParams clientParams = new HttpClientParams(); // 忽略cookie 避免 Cookie rejected 警告 clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES); client = new org.apache.commons.httpclient.HttpClient(clientParams, connectionManager); Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443); Protocol.registerProtocol("https", myhttps); this.maxSize = maxSize; // 支持proxy if (proxyHost != null && !proxyHost.equals("")) { client.getHostConfiguration().setProxy(proxyHost, proxyPort); client.getParams().setAuthenticationPreemptive(true); if (proxyAuthUser != null && !proxyAuthUser.equals("")) { client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyAuthUser, proxyAuthPassword)); log("Proxy AuthUser: " + proxyAuthUser); log("Proxy AuthPassword: " + proxyAuthPassword); } } } /** * log调试 */ private static void log(String message) { if (DEBUG) { log.debug(message); } } /** * 处理http getmethod 请求 */ public Response get(String url, String token) throws WeiboException { return get(url, new PostParameter[0], token); } public Response get(String url, PostParameter[] params, String token) throws WeiboException { log("Request:"); log("GET:" + url); if (null != params && params.length > 0) { String encodedParams = HttpClient.encodeParameters(params); if (-1 == url.indexOf("?")) { url += "?" + encodedParams; } else { url += "&" + encodedParams; } } GetMethod getmethod = new GetMethod(url); return httpRequest(getmethod, token); } public Response get(String url, PostParameter[] params, Paging paging, String token) throws WeiboException { if (null != paging) { List<PostParameter> pagingParams = new ArrayList<PostParameter>(4); if (-1 != paging.getMaxId()) { pagingParams.add(new PostParameter("max_id", String.valueOf(paging.getMaxId()))); } if (-1 != paging.getSinceId()) { pagingParams.add(new PostParameter("since_id", String.valueOf(paging.getSinceId()))); } if (-1 != paging.getPage()) { pagingParams.add(new PostParameter("page", String.valueOf(paging.getPage()))); } if (-1 != paging.getCount()) { if (-1 != url.indexOf("search")) { // search api takes "rpp" pagingParams.add(new PostParameter("rpp", String.valueOf(paging.getCount()))); } else { pagingParams.add(new PostParameter("count", String.valueOf(paging.getCount()))); } } PostParameter[] newparams = null; PostParameter[] arrayPagingParams = pagingParams.toArray(new PostParameter[pagingParams.size()]); if (null != params) { newparams = new PostParameter[params.length + pagingParams.size()]; System.arraycopy(params, 0, newparams, 0, params.length); System.arraycopy(arrayPagingParams, 0, newparams, params.length, pagingParams.size()); } else { if (0 != arrayPagingParams.length) { String encodedParams = HttpClient.encodeParameters(arrayPagingParams); if (-1 != url.indexOf("?")) { url += "&" + encodedParams; } else { url += "?" + encodedParams; } } } return get(url, newparams, token); } else { return get(url, params, token); } } /** * 处理http deletemethod请求 */ public Response delete(String url, PostParameter[] params, String token) throws WeiboException { if (0 != params.length) { String encodedParams = HttpClient.encodeParameters(params); if (-1 == url.indexOf("?")) { url += "?" + encodedParams; } else { url += "&" + encodedParams; } } DeleteMethod deleteMethod = new DeleteMethod(url); return httpRequest(deleteMethod, token); } /** * 处理http post请求 */ public Response post(String url, PostParameter[] params, String token) throws WeiboException { return post(url, params, true, token); } public Response post(String url, PostParameter[] params, Boolean WithTokenHeader, String token) throws WeiboException { log("Request:"); log("POST" + url); PostMethod postMethod = new PostMethod(url); for (int i = 0; i < params.length; i++) { postMethod.addParameter(params[i].getName(), params[i].getValue()); } HttpMethodParams param = postMethod.getParams(); param.setContentCharset("UTF-8"); return httpRequest(postMethod, WithTokenHeader, token); } /** * 支持multipart方式上传图片 */ public Response multPartURL(String url, PostParameter[] params, ImageItem item, String token) throws WeiboException { PostMethod postMethod = new PostMethod(url); try { Part[] parts = null; if (params == null) { parts = new Part[1]; } else { parts = new Part[params.length + 1]; } if (params != null) { int i = 0; for (PostParameter entry : params) { parts[i++] = new StringPart(entry.getName(), (String) entry.getValue()); } parts[parts.length - 1] = new ByteArrayPart(item.getContent(), item.getName(), item.getContentType()); } postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); return httpRequest(postMethod, token); } catch (Exception ex) { throw new WeiboException(ex.getMessage(), ex, -1); } } public Response multPartURL(String fileParamName, String url, PostParameter[] params, File file, boolean authenticated, String token) throws WeiboException { PostMethod postMethod = new PostMethod(url); try { Part[] parts = null; if (params == null) { parts = new Part[1]; } else { parts = new Part[params.length + 1]; } if (params != null) { int i = 0; for (PostParameter entry : params) { parts[i++] = new StringPart(entry.getName(), (String) entry.getValue()); } } FilePart filePart = new FilePart(fileParamName, file.getName(), file, new MimetypesFileTypeMap().getContentType(file), "UTF-8"); filePart.setTransferEncoding("binary"); parts[parts.length - 1] = filePart; postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); return httpRequest(postMethod, token); } catch (Exception ex) { throw new WeiboException(ex.getMessage(), ex, -1); } } public Response httpRequest(HttpMethod method, String token) throws WeiboException { return httpRequest(method, true, token); } public Response httpRequest(HttpMethod method, Boolean WithTokenHeader, String token) throws WeiboException { InetAddress ipaddr; int responseCode = -1; try { ipaddr = InetAddress.getLocalHost(); List<Header> headers = new ArrayList<Header>(); if (WithTokenHeader) { if (token == null) { throw new IllegalStateException("Oauth2 token is not set!"); } headers.add(new Header("Authorization", "OAuth2 " + token)); headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress())); client.getHostConfiguration().getParams().setParameter("http.default-headers", headers); for (Header hd : headers) { log(hd.getName() + ": " + hd.getValue()); } } method.getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); client.executeMethod(method); Header[] resHeader = method.getResponseHeaders(); responseCode = method.getStatusCode(); log("Response:"); log("https StatusCode:" + String.valueOf(responseCode)); for (Header header : resHeader) { log(header.getName() + ":" + header.getValue()); } Response response = new Response(); response.setResponseAsString(method.getResponseBodyAsString()); log(response.toString() + "\n"); if (responseCode != OK) { try { throw new WeiboException(getCause(responseCode), response.asJSONObject(), method.getStatusCode()); } catch (JSONException e) { e.printStackTrace(); } } return response; } catch (IOException ioe) { throw new WeiboException(ioe.getMessage(), ioe, responseCode); } finally { method.releaseConnection(); } } /* * 对parameters进行encode处理 */ public static String encodeParameters(PostParameter[] postParams) { StringBuffer buf = new StringBuffer(); for (int j = 0; j < postParams.length; j++) { if (j != 0) { buf.append("&"); } try { buf.append(URLEncoder.encode(postParams[j].getName(), "UTF-8")).append("=") .append(URLEncoder.encode(postParams[j].getValue(), "UTF-8")); } catch (java.io.UnsupportedEncodingException neverHappen) { } } return buf.toString(); } private static class ByteArrayPart extends PartBase { private byte[] mData; private String mName; public ByteArrayPart(byte[] data, String name, String type) throws IOException { super(name, type, "UTF-8", "binary"); mName = name; mData = data; } protected void sendData(OutputStream out) throws IOException { out.write(mData); } protected long lengthOfData() throws IOException { return mData.length; } protected void sendDispositionHeader(OutputStream out) throws IOException { super.sendDispositionHeader(out); StringBuilder buf = new StringBuilder(); buf.append("; filename=\"").append(mName).append("\""); out.write(buf.toString().getBytes()); } } private static String getCause(int statusCode) { String cause = null; switch (statusCode) { case NOT_MODIFIED: break; case BAD_REQUEST: cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting."; break; case NOT_AUTHORIZED: cause = "Authentication credentials were missing or incorrect."; break; case FORBIDDEN: cause = "The request is understood, but it has been refused. An accompanying error message will explain why."; break; case NOT_FOUND: cause = "The URI requested is invalid or the resource requested, such as a user, does not exists."; break; case NOT_ACCEPTABLE: cause = "Returned by the Search API when an invalid format is specified in the request."; break; case INTERNAL_SERVER_ERROR: cause = "Something is broken. Please post to the group so the Weibo team can investigate."; break; case BAD_GATEWAY: cause = "Weibo is down or being upgraded."; break; case SERVICE_UNAVAILABLE: cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited."; break; default: cause = ""; } return statusCode + ":" + cause; } }
apache-2.0
fiscoflex/erp
fiscoflex-api/src/main/java/mx/fiscoflex/contabilidad/util/UUIDCheck.java
229
package mx.fiscoflex.contabilidad.util; public class UUIDCheck { public static boolean isUUID(String uuid) { return uuid.matches("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[34][0-9a-fA-F]{3}-[89ab][0-9a-fA-F]{3}-[0-9a-fA-F]{12}"); } }
apache-2.0
ua-eas/ksd-kc5.2.1-rice2.3.6-ua
rice-middleware/it/ksb/src/test/java/org/kuali/rice/ksb/messaging/remotedservices/BaseballCardCollectionService.java
2496
/** * Copyright 2005-2013 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.ksb.messaging.remotedservices; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; /** * JAX-RS annotated interface for a baseball card collection service which might track the * cards in a collection. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ @Path("/") public interface BaseballCardCollectionService { @GET public List<BaseballCard> getAll(); /** * gets a card by it's (arbitrary) identifier */ @GET @Path("/BaseballCard/id/{id}") public BaseballCard get(@PathParam("id") Integer id); /** * gets all the cards in the collection with the given player name */ @GET @Path("/BaseballCard/playerName/{playerName}") public List<BaseballCard> get(@PathParam("playerName") String playerName); /** * Add a card to the collection. This is a non-idempotent method * (because you can more one of the same card), so we'll use @POST * @return the (arbitrary) numerical identifier assigned to this card by the service */ @POST @Path("/BaseballCard") public Integer add(BaseballCard card); /** * update the card for the given identifier. This will replace the card that was previously * associated with that identifier. */ @PUT @Path("/BaseballCard/id/{id}") @Consumes("application/xml") public void update(@PathParam("id") Integer id, BaseballCard card); /** * delete the card with the given identifier. */ @DELETE @Path("/BaseballCard/id/{id}") public void delete(@PathParam("id") Integer id); /** * This method lacks JAX-RS annotations */ public void unannotatedMethod(); }
apache-2.0
jalotsav/Sarvam-Sugar
app/src/main/java/com/jalotsav/sarvamsugar/navgtndrawer/FrgmntOutstandingRprt.java
25900
/* * Copyright 2016 Jalotsav * * 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.jalotsav.sarvamsugar.navgtndrawer; import android.Manifest; import android.app.DatePickerDialog; import android.content.pm.PackageManager; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.widget.AppCompatAutoCompleteTextView; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; 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.AdapterView; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.jalotsav.sarvamsugar.R; import com.jalotsav.sarvamsugar.adapters.RcyclrOutstandingAdapter; import com.jalotsav.sarvamsugar.common.AppConstants; import com.jalotsav.sarvamsugar.common.GeneralFuncations; import com.jalotsav.sarvamsugar.common.LogManager; import com.jalotsav.sarvamsugar.common.RecyclerViewEmptySupport; import com.jalotsav.sarvamsugar.common.UserSessionManager; import com.jalotsav.sarvamsugar.model.MdlOutstanding; import com.jalotsav.sarvamsugar.model.MdlOutstandingData; import com.jalotsav.sarvamsugar.retrofitapihelper.RetroAPI; import com.mikepenz.community_material_typeface_library.CommunityMaterial; import com.mikepenz.iconics.IconicsDrawable; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by JALOTSAV Dev. on 20/7/16. */ public class FrgmntOutstandingRprt extends Fragment implements AppConstants, View.OnClickListener { UserSessionManager mSession; CoordinatorLayout mCordntrlyotMain; ProgressBar mPrgrsbrMain; LinearLayout mLnrlyotAppearHere; TextView mTvAppearHere; RecyclerViewEmptySupport mRecyclerView; RecyclerView.LayoutManager mLayoutManager; RcyclrOutstandingAdapter mAdapter; FloatingActionButton mFabFilters, mFabApply; LinearLayout mLnrlyotFilters; ImageView mImgvwFltrRemove, mImgvwFltrClose; Spinner mSpnrFltrBy, mSpnrDateType, mSpnrSortby; AppCompatAutoCompleteTextView mAppcmptAutocmplttvSlctdFltrVal; AppCompatButton mAppcmptbtnToDate; MdlOutstanding mObjMdlOutstndng; ArrayList<MdlOutstandingData> mArrylstOutstndngData; ArrayList<String> mArrylstParty, mArrylstDalal, mArrylstArea, mArrylstZone; Calendar mCalndr; int mCrntYear, mCrntMonth, mCrntDay, mToYear, mToMonth, mToDay; String mReqstToDt, mQueryParty, mQueryDalal, mQueryArea, mQueryZone, mReqstType, mReqstSortby; boolean isAPICall = false; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.lo_frgmnt_outstanding_report, container, false); setHasOptionsMenu(true); mCordntrlyotMain = (CoordinatorLayout) rootView.findViewById(R.id.cordntrlyot_outstndng); mPrgrsbrMain = (ProgressBar) rootView.findViewById(R.id.prgrsbr_outstndng_main); mLnrlyotAppearHere = (LinearLayout) rootView.findViewById(R.id.lnrlyot_recyclremptyvw_appearhere); mTvAppearHere = (TextView) rootView.findViewById(R.id.tv_recyclremptyvw_appearhere); mRecyclerView = (RecyclerViewEmptySupport) rootView.findViewById(R.id.rcyclrvw_outstndng); mFabFilters = (FloatingActionButton) rootView.findViewById(R.id.fab_outstndng_filters); mFabApply = (FloatingActionButton) rootView.findViewById(R.id.fab_outstndng_apply); mLnrlyotFilters = (LinearLayout) rootView.findViewById(R.id.lnrlyot_outstndng_filtersvw); mImgvwFltrRemove = (ImageView) rootView.findViewById(R.id.imgvw_outstndng_fltrremove); mImgvwFltrClose = (ImageView) rootView.findViewById(R.id.imgvw_outstndng_fltrclose); mSpnrFltrBy = (Spinner) rootView.findViewById(R.id.spnr_outstndng_filterby); mSpnrDateType = (Spinner) rootView.findViewById(R.id.spnr_outstndng_datetype); mSpnrSortby = (Spinner) rootView.findViewById(R.id.spnr_outstndng_sortby); mAppcmptAutocmplttvSlctdFltrVal = (AppCompatAutoCompleteTextView) rootView.findViewById(R.id.apcmptautocmplttv_outstndng_slctdfilterval); mAppcmptbtnToDate = (AppCompatButton) rootView.findViewById(R.id.appcmptbtn_outstndng_slcttodate); mLayoutManager = new LinearLayoutManager(getActivity()); mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setEmptyView(mLnrlyotAppearHere); mSession = new UserSessionManager(getActivity()); mFabFilters.setImageDrawable(new IconicsDrawable(getActivity()) .icon(CommunityMaterial.Icon.cmd_filter) .color(Color.WHITE)); mFabFilters.setVisibility(View.GONE); mFabApply.setImageDrawable(new IconicsDrawable(getActivity()) .icon(CommunityMaterial.Icon.cmd_check) .color(Color.WHITE)); mFabFilters.setOnClickListener(this); mFabApply.setOnClickListener(this); mImgvwFltrRemove.setOnClickListener(this); mImgvwFltrClose.setOnClickListener(this); mAppcmptbtnToDate.setOnClickListener(this); mTvAppearHere.setText(getString(R.string.outstndng_appear_here)); mArrylstOutstndngData = new ArrayList<>(); mArrylstParty = new ArrayList<>(); mArrylstDalal = new ArrayList<>(); mArrylstArea = new ArrayList<>(); mArrylstZone = new ArrayList<>(); ArrayList<MdlOutstandingData> arrylstOutstndngData = new ArrayList<>(); mAdapter = new RcyclrOutstandingAdapter(getActivity(), arrylstOutstndngData); mRecyclerView.setAdapter(mAdapter); mCalndr = Calendar.getInstance(); mCrntYear = mToYear = mCalndr.get(Calendar.YEAR); mCrntMonth = mToMonth = mCalndr.get(Calendar.MONTH); mCrntDay = mToDay = mCalndr.get(Calendar.DAY_OF_MONTH); mReqstToDt = GeneralFuncations.setDateIn2Digit(mToDay) + "-" + GeneralFuncations.setDateIn2Digit(mToMonth+1) + "-" + mToYear; // Format "15-09-2016" mAppcmptbtnToDate.setText(getResources().getString(R.string.to_date_val, mReqstToDt)); mQueryParty = ""; mQueryDalal = ""; mQueryArea = ""; mQueryZone = ""; mReqstType = ""; mReqstSortby = ""; // Check Storage permission before call AsyncTask for data isAPICall = false; checkStoragePermission(); mSpnrFltrBy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { ((TextView) adapterView.getChildAt(0)).setTextColor(ContextCompat.getColor(getActivity(), R.color.colorPrimaryAmber)); mAppcmptAutocmplttvSlctdFltrVal.setText(""); if (position == 0) { mAppcmptAutocmplttvSlctdFltrVal.setVisibility(View.GONE); // mFabApply.setVisibility(View.GONE); } else { mAppcmptAutocmplttvSlctdFltrVal.setVisibility(View.VISIBLE); // mFabApply.setVisibility(View.VISIBLE); setAutoCompltTvAdapter(position); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); mSpnrDateType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { ((TextView) adapterView.getChildAt(0)).setTextColor(ContextCompat.getColor(getActivity(), R.color.colorPrimaryAmber)); if (position == 2) mReqstType = "1"; else mReqstType = "0"; } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); mSpnrSortby.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) { ((TextView) adapterView.getChildAt(0)).setTextColor(ContextCompat.getColor(getActivity(), R.color.colorPrimaryAmber)); if (position == 2) mReqstSortby = "1"; else mReqstSortby = "0"; } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); return rootView; } private void checkStoragePermission() { try { if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { LogManager.printLog(LOGTYPE_INFO, "Permission Granted"); if (isAPICall) getOutstandingAPI(); // Call API through Retrofit and store response JSON into device storage file else new getOutstandingFromFileAsync().execute(); // AsyncTask through get JSON data of API from device storage file } else { if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) GeneralFuncations.showtoastLngthlong(getActivity(), getString(R.string.you_must_allow_permsn)); requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMSN_STORAGE); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMSN_STORAGE) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) checkStoragePermission(); else showMySnackBar(getString(R.string.permsn_denied)); } } // Call API through Retrofit and store response JSON into device storage file private void getOutstandingAPI() { mPrgrsbrMain.setVisibility(View.VISIBLE); mFabFilters.setVisibility(View.GONE); OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); clientBuilder.connectTimeout(3, TimeUnit.MINUTES); clientBuilder.readTimeout(3, TimeUnit.MINUTES); Retrofit objRetrofit = new Retrofit.Builder() .baseUrl(API_ROOT_URL) .client(clientBuilder.build()) .addConverterFactory(GsonConverterFactory.create()) .build(); RetroAPI apiDalalwsSls = objRetrofit.create(RetroAPI.class); Call<ResponseBody> callGodownStck = apiDalalwsSls.getOutstanding( API_METHOD_GETOUTSTAND, mSession.getUserId(), mSession.getUserType(), mReqstToDt, mReqstType, mQueryParty, mQueryDalal, mQueryArea, mQueryZone, mReqstSortby ); callGodownStck.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (mPrgrsbrMain.isShown()) mPrgrsbrMain.setVisibility(View.GONE); if (response.isSuccessful()) { String[] strArray = new String[1]; try { LogManager.printLog(LOGTYPE_INFO, "Reponse is successful: " + response.isSuccessful()); strArray[0] = response.body().string(); // Create and save API response in device storage in .json file storeJSONDataToStorage(strArray[0]); // AsynTask through get JSON data of API from device storage file new getOutstandingFromFileAsync().execute(); } catch (Exception e) { e.printStackTrace(); } } else showMySnackBar(getString(R.string.there_are_some_server_prblm)); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { t.printStackTrace(); mPrgrsbrMain.setVisibility(View.GONE); if (!mFabFilters.isShown()) mFabFilters.setVisibility(View.VISIBLE); showMySnackBar(getString(R.string.there_are_some_prblm)); } }); } // Create and save API response in device storage in .json file private void storeJSONDataToStorage(String strResponse) { try { File filesDirectory = PATH_SARVAMSUGAR_FILES; if (!filesDirectory.exists()) filesDirectory.mkdirs(); File fileJson = new File(filesDirectory, OUTSTANDING_JSON); if (fileJson.exists()) fileJson.delete(); fileJson.createNewFile(); FileOutputStream fOut = new FileOutputStream(fileJson); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(strResponse); myOutWriter.close(); fOut.close(); } catch (Exception e) { e.printStackTrace(); } } // AsynTask through get JSON data of API from device storage file public class getOutstandingFromFileAsync extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); mPrgrsbrMain.setVisibility(View.VISIBLE); } @Override protected Void doInBackground(Void... voids) { mObjMdlOutstndng = getJSONDataFromStorage(); if (mObjMdlOutstndng != null) { if (TextUtils.isEmpty(mObjMdlOutstndng.getResult()) || mObjMdlOutstndng.getData() == null) { showMySnackBar(getString(R.string.sync_data_msg)); } else if (mObjMdlOutstndng.getResult().equalsIgnoreCase(RESULT_ONE)) { mArrylstOutstndngData = mObjMdlOutstndng.getData(); if (!mArrylstOutstndngData.isEmpty()) { for(MdlOutstandingData objMdlOutstandingData : mArrylstOutstndngData) { if(!mArrylstParty.contains(objMdlOutstandingData.getPname())) mArrylstParty.add(objMdlOutstandingData.getPname()); if(!mArrylstDalal.contains(objMdlOutstandingData.getDalalName())) mArrylstDalal.add(objMdlOutstandingData.getDalalName()); if(!mArrylstArea.contains(objMdlOutstandingData.getArea())) mArrylstArea.add(objMdlOutstandingData.getArea()); if(!mArrylstZone.contains(objMdlOutstandingData.getZone())) mArrylstZone.add(objMdlOutstandingData.getZone()); } if(isAdded()) setAutoCompltTvAdapter(0); } } else showMySnackBar(getString(R.string.there_are_some_prblm)); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if(isAdded()) { mPrgrsbrMain.setVisibility(View.GONE); if (!mArrylstOutstndngData.isEmpty()) { showMySnackBar(getResources().getString(R.string.value_records_sml, mArrylstOutstndngData.size())); mFabFilters.setVisibility(View.VISIBLE); } mAdapter.setFilter(mArrylstOutstndngData); } } } // Create and save API response in device storage in .json file private MdlOutstanding getJSONDataFromStorage() { try { mObjMdlOutstndng = new MdlOutstanding(); File filesDirectory = PATH_SARVAMSUGAR_FILES; if (!filesDirectory.exists()) filesDirectory.mkdirs(); File fileJson = new File(filesDirectory, OUTSTANDING_JSON); if (fileJson.exists()) { FileInputStream fIn = new FileInputStream(fileJson); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); String aDataRow = ""; String aBuffer = ""; while ((aDataRow = myReader.readLine()) != null) { aBuffer += aDataRow + "\n"; } myReader.close(); Gson mGson = new GsonBuilder().create(); mObjMdlOutstndng = mGson.fromJson(aBuffer, MdlOutstanding.class); } } catch (Exception e) { e.printStackTrace(); } return mObjMdlOutstndng; } private void setAutoCompltTvAdapter(int spnrSlctdPosition) { mAppcmptAutocmplttvSlctdFltrVal.setThreshold(1); ArrayAdapter<String> adapterPName = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, mArrylstParty); ArrayAdapter<String> adapterDalal = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, mArrylstDalal); ArrayAdapter<String> adapterArea = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, mArrylstArea); ArrayAdapter<String> adapterZone = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, mArrylstZone); switch (spnrSlctdPosition) { case 1: mAppcmptAutocmplttvSlctdFltrVal.setAdapter(adapterPName); break; case 2: mAppcmptAutocmplttvSlctdFltrVal.setAdapter(adapterDalal); break; case 3: mAppcmptAutocmplttvSlctdFltrVal.setAdapter(adapterArea); break; case 4: mAppcmptAutocmplttvSlctdFltrVal.setAdapter(adapterZone); break; } } @Override public void onClick(View view) { switch (view.getId()) { case R.id.fab_outstndng_filters: showFiltersView(); // Show Filters View break; case R.id.fab_outstndng_apply: String slctdFltrVal = mAppcmptAutocmplttvSlctdFltrVal.getText().toString().trim(); if (!TextUtils.isEmpty(slctdFltrVal)) { switch (mSpnrFltrBy.getSelectedItemPosition()) { case 1: mQueryParty = slctdFltrVal; break; case 2: mQueryDalal = slctdFltrVal; break; case 3: mQueryArea = slctdFltrVal; break; case 4: mQueryZone = slctdFltrVal; break; } } if (!GeneralFuncations.isNetConnected(getActivity())) { mAdapter.setFilter(filters(mArrylstOutstndngData)); } else getOutstandingAPI(); hideFiltersView(); // Hide Filters View break; case R.id.imgvw_outstndng_fltrremove: mToDay = mCrntDay; mToMonth = mCrntMonth; mToYear = mCrntYear; mReqstToDt = GeneralFuncations.setDateIn2Digit(mToDay) + "-" + GeneralFuncations.setDateIn2Digit(mToMonth+1) + "-" + mToYear; // Format "15-09-2016" mAppcmptbtnToDate.setText(getResources().getString(R.string.to_date_val, mReqstToDt)); ArrayList<MdlOutstandingData> arrylstOutstndngData = new ArrayList<>(); mAdapter.setFilter(arrylstOutstndngData); mSpnrFltrBy.setSelection(0); mAppcmptAutocmplttvSlctdFltrVal.setText(""); mQueryParty = ""; mQueryDalal = ""; mQueryArea = ""; mQueryZone = ""; mReqstType = ""; mReqstSortby = ""; // Check Storage permission before call AsyncTask for data isAPICall = false; checkStoragePermission(); hideFiltersView(); // Hide Filters View break; case R.id.imgvw_outstndng_fltrclose: hideFiltersView(); // Hide Filters View break; case R.id.appcmptbtn_outstndng_slcttodate: DatePickerDialog mToDatePckrDlg = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int year, int month, int day) { mToYear = year; mToMonth = month; mToDay = day; month++; mReqstToDt = GeneralFuncations.setDateIn2Digit(day) + "-" + GeneralFuncations.setDateIn2Digit(month) + "-" + year; mAppcmptbtnToDate.setText(getResources().getString(R.string.to_date_val, mReqstToDt)); } }, mToYear, mToMonth, mToDay); mToDatePckrDlg.show(); break; } } // Show Filters View private void showFiltersView() { mFabFilters.setVisibility(View.GONE); mLnrlyotFilters.setVisibility(View.VISIBLE); mFabApply.setVisibility(View.VISIBLE); } // Hide Filters View private void hideFiltersView() { mFabFilters.setVisibility(View.VISIBLE); mLnrlyotFilters.setVisibility(View.GONE); mFabApply.setVisibility(View.GONE); } private ArrayList<MdlOutstandingData> filters(ArrayList<MdlOutstandingData> arrylstMdlOutstandingData) { ArrayList<MdlOutstandingData> fltrdOutstandingData = new ArrayList<>(); for (MdlOutstandingData objMdlOutstandingData : arrylstMdlOutstandingData) { String targetParty = objMdlOutstandingData.getPname().toLowerCase(); String targetDalal = objMdlOutstandingData.getDalalName().toLowerCase(); String targetArea = objMdlOutstandingData.getArea().toLowerCase(); String targetZone = objMdlOutstandingData.getZone().toLowerCase(); if (targetParty.contains(mQueryParty.toLowerCase()) && targetDalal.contains(mQueryDalal.toLowerCase()) && targetArea.contains(mQueryArea.toLowerCase()) && targetZone.contains(mQueryZone.toLowerCase())) { fltrdOutstandingData.add(objMdlOutstandingData); } } return fltrdOutstandingData; } // Show SnackBar with given message private void showMySnackBar(String message) { Snackbar.make(mCordntrlyotMain, message, Snackbar.LENGTH_LONG).show(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_refresh, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_refresh: if (!GeneralFuncations.isNetConnected(getActivity())) { // Show SnackBar with given message showMySnackBar(getResources().getString(R.string.no_intrnt_cnctn)); } else { isAPICall = true; checkStoragePermission(); } break; } return super.onOptionsItemSelected(item); } }
apache-2.0
glimpseio/incubator-calcite
core/src/test/java/org/apache/calcite/util/UtilTest.java
47693
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.util; import org.apache.calcite.avatica.AvaticaUtils; import org.apache.calcite.avatica.util.Spaces; import org.apache.calcite.examples.RelBuilderExample; import org.apache.calcite.linq4j.Ord; import org.apache.calcite.linq4j.function.Function1; import org.apache.calcite.runtime.FlatLists; import org.apache.calcite.runtime.Resources; import org.apache.calcite.sql.SqlDialect; import org.apache.calcite.sql.util.SqlBuilder; import org.apache.calcite.sql.util.SqlString; import org.apache.calcite.test.DiffTestCase; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import org.junit.BeforeClass; import org.junit.Test; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.lang.management.MemoryType; import java.math.BigDecimal; import java.sql.Timestamp; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NavigableSet; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.TimeZone; import java.util.TreeSet; import javax.annotation.Nullable; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.isA; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Unit test for {@link Util} and other classes in this package. */ public class UtilTest { //~ Constructors ----------------------------------------------------------- public UtilTest() { } //~ Methods ---------------------------------------------------------------- @BeforeClass public static void setUSLocale() { // This ensures numbers in exceptions are printed as in asserts. // For example, 1,000 vs 1 000 Locale.setDefault(Locale.US); } @Test public void testPrintEquals() { assertPrintEquals("\"x\"", "x", true); } @Test public void testPrintEquals2() { assertPrintEquals("\"x\"", "x", false); } @Test public void testPrintEquals3() { assertPrintEquals("null", null, true); } @Test public void testPrintEquals4() { assertPrintEquals("", null, false); } @Test public void testPrintEquals5() { assertPrintEquals("\"\\\\\\\"\\r\\n\"", "\\\"\r\n", true); } @Test public void testScientificNotation() { BigDecimal bd; bd = new BigDecimal("0.001234"); TestUtil.assertEqualsVerbose( "1.234E-3", Util.toScientificNotation(bd)); bd = new BigDecimal("0.001"); TestUtil.assertEqualsVerbose( "1E-3", Util.toScientificNotation(bd)); bd = new BigDecimal("-0.001"); TestUtil.assertEqualsVerbose( "-1E-3", Util.toScientificNotation(bd)); bd = new BigDecimal("1"); TestUtil.assertEqualsVerbose( "1E0", Util.toScientificNotation(bd)); bd = new BigDecimal("-1"); TestUtil.assertEqualsVerbose( "-1E0", Util.toScientificNotation(bd)); bd = new BigDecimal("1.0"); TestUtil.assertEqualsVerbose( "1.0E0", Util.toScientificNotation(bd)); bd = new BigDecimal("12345"); TestUtil.assertEqualsVerbose( "1.2345E4", Util.toScientificNotation(bd)); bd = new BigDecimal("12345.00"); TestUtil.assertEqualsVerbose( "1.234500E4", Util.toScientificNotation(bd)); bd = new BigDecimal("12345.001"); TestUtil.assertEqualsVerbose( "1.2345001E4", Util.toScientificNotation(bd)); // test truncate bd = new BigDecimal("1.23456789012345678901"); TestUtil.assertEqualsVerbose( "1.2345678901234567890E0", Util.toScientificNotation(bd)); bd = new BigDecimal("-1.23456789012345678901"); TestUtil.assertEqualsVerbose( "-1.2345678901234567890E0", Util.toScientificNotation(bd)); } @Test public void testToJavaId() throws UnsupportedEncodingException { assertEquals( "ID$0$foo", Util.toJavaId("foo", 0)); assertEquals( "ID$0$foo_20_bar", Util.toJavaId("foo bar", 0)); assertEquals( "ID$0$foo__bar", Util.toJavaId("foo_bar", 0)); assertEquals( "ID$100$_30_bar", Util.toJavaId("0bar", 100)); assertEquals( "ID$0$foo0bar", Util.toJavaId("foo0bar", 0)); assertEquals( "ID$0$it_27_s_20_a_20_bird_2c__20_it_27_s_20_a_20_plane_21_", Util.toJavaId("it's a bird, it's a plane!", 0)); // Try some funny non-ASCII charsets assertEquals( "ID$0$_f6__cb__c4__ca__ae__c1__f9__cb_", Util.toJavaId( "\u00f6\u00cb\u00c4\u00ca\u00ae\u00c1\u00f9\u00cb", 0)); assertEquals( "ID$0$_f6cb__c4ca__aec1__f9cb_", Util.toJavaId("\uf6cb\uc4ca\uaec1\uf9cb", 0)); byte[] bytes1 = {3, 12, 54, 23, 33, 23, 45, 21, 127, -34, -92, -113}; assertEquals( "ID$0$_3__c_6_17__21__17__2d__15__7f__6cd9__fffd_", Util.toJavaId( new String(bytes1, "EUC-JP"), 0)); byte[] bytes2 = { 64, 32, 43, -45, -23, 0, 43, 54, 119, -32, -56, -34 }; assertEquals( "ID$0$_30c__3617__2117__2d15__7fde__a48f_", Util.toJavaId( new String(bytes1, "UTF-16"), 0)); } private void assertPrintEquals( String expect, String in, boolean nullMeansNull) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); Util.printJavaString(pw, in, nullMeansNull); pw.flush(); String out = sw.toString(); assertEquals(expect, out); } /** * Unit-test for {@link BitString}. */ @Test public void testBitString() { // Powers of two, minimal length. final BitString b0 = new BitString("", 0); final BitString b1 = new BitString("1", 1); final BitString b2 = new BitString("10", 2); final BitString b4 = new BitString("100", 3); final BitString b8 = new BitString("1000", 4); final BitString b16 = new BitString("10000", 5); final BitString b32 = new BitString("100000", 6); final BitString b64 = new BitString("1000000", 7); final BitString b128 = new BitString("10000000", 8); final BitString b256 = new BitString("100000000", 9); // other strings final BitString b0x1 = new BitString("", 1); final BitString b0x12 = new BitString("", 12); // conversion to hex strings assertEquals( "", b0.toHexString()); assertEquals( "1", b1.toHexString()); assertEquals( "2", b2.toHexString()); assertEquals( "4", b4.toHexString()); assertEquals( "8", b8.toHexString()); assertEquals( "10", b16.toHexString()); assertEquals( "20", b32.toHexString()); assertEquals( "40", b64.toHexString()); assertEquals( "80", b128.toHexString()); assertEquals( "100", b256.toHexString()); assertEquals( "0", b0x1.toHexString()); assertEquals( "000", b0x12.toHexString()); // to byte array assertByteArray("01", "1", 1); assertByteArray("01", "1", 5); assertByteArray("01", "1", 8); assertByteArray("00, 01", "1", 9); assertByteArray("", "", 0); assertByteArray("00", "0", 1); assertByteArray("00", "0000", 2); // bit count less than string assertByteArray("00", "000", 5); // bit count larger than string assertByteArray("00", "0", 8); // precisely 1 byte assertByteArray("00, 00", "00", 9); // just over 1 byte // from hex string assertReversible(""); assertReversible("1"); assertReversible("10"); assertReversible("100"); assertReversible("1000"); assertReversible("10000"); assertReversible("100000"); assertReversible("1000000"); assertReversible("10000000"); assertReversible("100000000"); assertReversible("01"); assertReversible("001010"); assertReversible("000000000100"); } private static void assertReversible(String s) { assertEquals( s, BitString.createFromBitString(s).toBitString(), s); assertEquals( s, BitString.createFromHexString(s).toHexString()); } private void assertByteArray( String expected, String bits, int bitCount) { byte[] bytes = BitString.toByteArrayFromBitString(bits, bitCount); final String s = toString(bytes); assertEquals(expected, s); } /** * Converts a byte array to a hex string like "AB, CD". */ private String toString(byte[] bytes) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; if (i > 0) { buf.append(", "); } String s = Integer.toString(b, 16); buf.append((b < 16) ? ("0" + s) : s); } return buf.toString(); } /** * Tests {@link org.apache.calcite.util.CastingList} and {@link Util#cast}. */ @Test public void testCastingList() { final List<Number> numberList = new ArrayList<Number>(); numberList.add(new Integer(1)); numberList.add(null); numberList.add(new Integer(2)); List<Integer> integerList = Util.cast(numberList, Integer.class); assertEquals(3, integerList.size()); assertEquals(new Integer(2), integerList.get(2)); // Nulls are OK. assertNull(integerList.get(1)); // Can update the underlying list. integerList.set(1, 345); assertEquals(new Integer(345), integerList.get(1)); integerList.set(1, null); assertNull(integerList.get(1)); // Can add a member of the wrong type to the underlying list. numberList.add(new Double(3.1415)); assertEquals(4, integerList.size()); // Access a member which is of the wrong type. try { integerList.get(3); fail("expected exception"); } catch (ClassCastException e) { // ok } } @Test public void testIterableProperties() { Properties properties = new Properties(); properties.put("foo", "george"); properties.put("bar", "ringo"); StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : Util.toMap(properties).entrySet()) { sb.append(entry.getKey()).append("=").append(entry.getValue()); sb.append(";"); } assertEquals("bar=ringo;foo=george;", sb.toString()); assertEquals(2, Util.toMap(properties).entrySet().size()); properties.put("nonString", 34); try { for (Map.Entry<String, String> e : Util.toMap(properties).entrySet()) { String s = e.getValue(); Util.discard(s); } fail("expected exception"); } catch (ClassCastException e) { // ok } } /** * Tests the difference engine, {@link DiffTestCase#diff}. */ @Test public void testDiffLines() { String[] before = { "Get a dose of her in jackboots and kilt", "She's killer-diller when she's dressed to the hilt", "She's the kind of a girl that makes The News of The World", "Yes you could say she was attractively built.", "Yeah yeah yeah." }; String[] after = { "Get a dose of her in jackboots and kilt", "(they call her \"Polythene Pam\")", "She's killer-diller when she's dressed to the hilt", "She's the kind of a girl that makes The Sunday Times", "seem more interesting.", "Yes you could say she was attractively built." }; String diff = DiffTestCase.diffLines( Arrays.asList(before), Arrays.asList(after)); assertThat(Util.toLinux(diff), equalTo("1a2\n" + "> (they call her \"Polythene Pam\")\n" + "3c4,5\n" + "< She's the kind of a girl that makes The News of The World\n" + "---\n" + "> She's the kind of a girl that makes The Sunday Times\n" + "> seem more interesting.\n" + "5d6\n" + "< Yeah yeah yeah.\n")); } /** * Tests the {@link Util#toPosix(TimeZone, boolean)} method. */ @Test public void testPosixTimeZone() { // NOTE jvs 31-July-2007: First two tests are disabled since // not everyone may have patched their system yet for recent // DST change. // Pacific Standard Time. Effective 2007, the local time changes from // PST to PDT at 02:00 LST to 03:00 LDT on the second Sunday in March // and returns at 02:00 LDT to 01:00 LST on the first Sunday in // November. if (false) { assertEquals( "PST-8PDT,M3.2.0,M11.1.0", Util.toPosix(TimeZone.getTimeZone("PST"), false)); assertEquals( "PST-8PDT1,M3.2.0/2,M11.1.0/2", Util.toPosix(TimeZone.getTimeZone("PST"), true)); } // Tokyo has +ve offset, no DST assertEquals( "JST9", Util.toPosix(TimeZone.getTimeZone("Asia/Tokyo"), true)); // Sydney, Australia lies ten hours east of GMT and makes a one hour // shift forward during daylight savings. Being located in the southern // hemisphere, daylight savings begins on the last Sunday in October at // 2am and ends on the last Sunday in March at 3am. // (Uses STANDARD_TIME time-transition mode.) // Because australia changed their daylight savings rules, some JVMs // have a different (older and incorrect) timezone settings for // Australia. So we test for the older one first then do the // correct assert based upon what the toPosix method returns String posixTime = Util.toPosix(TimeZone.getTimeZone("Australia/Sydney"), true); if (posixTime.equals("EST10EST1,M10.5.0/2,M3.5.0/3")) { // very old JVMs without the fix assertEquals("EST10EST1,M10.5.0/2,M3.5.0/3", posixTime); } else if (posixTime.equals("EST10EST1,M10.1.0/2,M4.1.0/3")) { // old JVMs without the fix assertEquals("EST10EST1,M10.1.0/2,M4.1.0/3", posixTime); } else { // newer JVMs with the fix assertEquals("AEST10AEDT1,M10.1.0/2,M4.1.0/3", posixTime); } // Paris, France. (Uses UTC_TIME time-transition mode.) assertEquals( "CET1CEST1,M3.5.0/2,M10.5.0/3", Util.toPosix(TimeZone.getTimeZone("Europe/Paris"), true)); assertEquals( "UTC0", Util.toPosix(TimeZone.getTimeZone("UTC"), true)); } /** * Tests the methods {@link Util#enumConstants(Class)} and * {@link Util#enumVal(Class, String)}. */ @Test public void testEnumConstants() { final Map<String, MemoryType> memoryTypeMap = Util.enumConstants(MemoryType.class); assertEquals(2, memoryTypeMap.size()); assertEquals(MemoryType.HEAP, memoryTypeMap.get("HEAP")); assertEquals(MemoryType.NON_HEAP, memoryTypeMap.get("NON_HEAP")); try { memoryTypeMap.put("FOO", null); fail("expected exception"); } catch (UnsupportedOperationException e) { // expected: map is immutable } assertEquals("HEAP", Util.enumVal(MemoryType.class, "HEAP").name()); assertNull(Util.enumVal(MemoryType.class, "heap")); assertNull(Util.enumVal(MemoryType.class, "nonexistent")); } /** * Tests SQL builders. */ @Test public void testSqlBuilder() { final SqlBuilder buf = new SqlBuilder(SqlDialect.CALCITE); assertEquals(0, buf.length()); buf.append("select "); assertEquals("select ", buf.getSql()); buf.identifier("x"); assertEquals("select \"x\"", buf.getSql()); buf.append(", "); buf.identifier("y", "a b"); assertEquals("select \"x\", \"y\".\"a b\"", buf.getSql()); final SqlString sqlString = buf.toSqlString(); assertEquals(SqlDialect.CALCITE, sqlString.getDialect()); assertEquals(buf.getSql(), sqlString.getSql()); assertTrue(buf.getSql().length() > 0); assertEquals(buf.getSqlAndClear(), sqlString.getSql()); assertEquals(0, buf.length()); buf.clear(); assertEquals(0, buf.length()); buf.literal("can't get no satisfaction"); assertEquals("'can''t get no satisfaction'", buf.getSqlAndClear()); buf.literal(new Timestamp(0)); assertEquals("TIMESTAMP '1970-01-01 00:00:00'", buf.getSqlAndClear()); buf.clear(); assertEquals(0, buf.length()); buf.append("hello world"); assertEquals(2, buf.indexOf("l")); assertEquals(-1, buf.indexOf("z")); assertEquals(9, buf.indexOf("l", 5)); } /** * Unit test for {@link org.apache.calcite.util.CompositeList}. */ @Test public void testCompositeList() { // Made up of zero lists //noinspection unchecked List<String> list = CompositeList.of(new List[0]); assertEquals(0, list.size()); assertTrue(list.isEmpty()); try { final String s = list.get(0); fail("expected error, got " + s); } catch (IndexOutOfBoundsException e) { // ok } assertFalse(list.listIterator().hasNext()); List<String> listEmpty = Collections.emptyList(); List<String> listAbc = Arrays.asList("a", "b", "c"); List<String> listEmpty2 = new ArrayList<String>(); // Made up of three lists, two of which are empty list = CompositeList.of(listEmpty, listAbc, listEmpty2); assertEquals(3, list.size()); assertFalse(list.isEmpty()); assertEquals("a", list.get(0)); assertEquals("c", list.get(2)); try { final String s = list.get(3); fail("expected error, got " + s); } catch (IndexOutOfBoundsException e) { // ok } try { final String s = list.set(0, "z"); fail("expected error, got " + s); } catch (UnsupportedOperationException e) { // ok } // Iterator final Iterator<String> iterator = list.iterator(); assertTrue(iterator.hasNext()); assertEquals("a", iterator.next()); assertEquals("b", iterator.next()); assertTrue(iterator.hasNext()); try { iterator.remove(); fail("expected error"); } catch (UnsupportedOperationException e) { // ok } assertEquals("c", iterator.next()); assertFalse(iterator.hasNext()); // Extend one of the backing lists, and list grows. listEmpty2.add("zz"); assertEquals(4, list.size()); assertEquals("zz", list.get(3)); // Syntactic sugar 'of' method String ss = ""; for (String s : CompositeList.of(list, list)) { ss += s; } assertEquals("abczzabczz", ss); } /** * Unit test for {@link Template}. */ @Test public void testTemplate() { // Regular java message format. assertEquals( "Hello, world, what a nice day.", MessageFormat.format( "Hello, {0}, what a nice {1}.", "world", "day")); // Our extended message format. First, just strings. final HashMap<Object, Object> map = new HashMap<Object, Object>(); map.put("person", "world"); map.put("time", "day"); assertEquals( "Hello, world, what a nice day.", Template.formatByName( "Hello, {person}, what a nice {time}.", map)); // String and an integer. final Template template = Template.of("Happy {age,number,#.00}th birthday, {person}!"); map.clear(); map.put("person", "Ringo"); map.put("age", 64.5); assertEquals( "Happy 64.50th birthday, Ringo!", template.format(map)); // Missing parameters evaluate to null. map.remove("person"); assertEquals( "Happy 64.50th birthday, null!", template.format(map)); // Specify parameter by Integer ordinal. map.clear(); map.put(1, "Ringo"); map.put("0", 64.5); assertEquals( "Happy 64.50th birthday, Ringo!", template.format(map)); // Too many parameters supplied. map.put("lastName", "Starr"); map.put("homeTown", "Liverpool"); assertEquals( "Happy 64.50th birthday, Ringo!", template.format(map)); // Get parameter names. In order of appearance. assertEquals( Arrays.asList("age", "person"), template.getParameterNames()); // No parameters; doubled single quotes; quoted braces. final Template template2 = Template.of("Don''t expand 'this {brace}'."); assertEquals( Collections.<String>emptyList(), template2.getParameterNames()); assertEquals( "Don't expand this {brace}.", template2.format(Collections.<Object, Object>emptyMap())); // Empty template. assertEquals("", Template.formatByName("", map)); } /** * Unit test for {@link Util#parseLocale(String)} method. */ @Test public void testParseLocale() { Locale[] locales = { Locale.CANADA, Locale.CANADA_FRENCH, Locale.getDefault(), Locale.US, Locale.TRADITIONAL_CHINESE, }; for (Locale locale : locales) { assertEquals(locale, Util.parseLocale(locale.toString())); } // Example locale names in Locale.toString() javadoc. String[] localeNames = { "en", "de_DE", "_GB", "en_US_WIN", "de__POSIX", "fr__MAC" }; for (String localeName : localeNames) { assertEquals(localeName, Util.parseLocale(localeName).toString()); } } @Test public void testSpaces() { assertEquals("", Spaces.of(0)); assertEquals(" ", Spaces.of(1)); assertEquals(" ", Spaces.of(1)); assertEquals(" ", Spaces.of(9)); assertEquals(" ", Spaces.of(5)); assertEquals(1000, Spaces.of(1000).length()); } @Test public void testSpaceString() { assertThat(Spaces.sequence(0).toString(), equalTo("")); assertThat(Spaces.sequence(1).toString(), equalTo(" ")); assertThat(Spaces.sequence(9).toString(), equalTo(" ")); assertThat(Spaces.sequence(5).toString(), equalTo(" ")); String s = new StringBuilder().append("xx").append(Spaces.MAX, 0, 100) .toString(); assertThat(s.length(), equalTo(102)); // this would blow memory if the string were materialized... check that it // is not assertThat(Spaces.sequence(1000000000).length(), equalTo(1000000000)); final StringWriter sw = new StringWriter(); Spaces.append(sw, 4); assertThat(sw.toString(), equalTo(" ")); final StringBuilder buf = new StringBuilder(); Spaces.append(buf, 4); assertThat(buf.toString(), equalTo(" ")); assertThat(Spaces.padLeft("xy", 5), equalTo(" xy")); assertThat(Spaces.padLeft("abcde", 5), equalTo("abcde")); assertThat(Spaces.padLeft("abcdef", 5), equalTo("abcdef")); assertThat(Spaces.padRight("xy", 5), equalTo("xy ")); assertThat(Spaces.padRight("abcde", 5), equalTo("abcde")); assertThat(Spaces.padRight("abcdef", 5), equalTo("abcdef")); } /** * Unit test for {@link Pair#zip(java.util.List, java.util.List)}. */ @Test public void testPairZip() { List<String> strings = Arrays.asList("paul", "george", "john", "ringo"); List<Integer> integers = Arrays.asList(1942, 1943, 1940); List<Pair<String, Integer>> zip = Pair.zip(strings, integers); assertEquals(3, zip.size()); assertEquals("paul:1942", zip.get(0).left + ":" + zip.get(0).right); assertEquals("john", zip.get(2).left); int x = 0; for (Pair<String, Integer> pair : zip) { x += pair.right; } assertEquals(5825, x); } /** * Unit test for {@link Pair#adjacents(Iterable)}. */ @Test public void testPairAdjacents() { List<String> strings = Arrays.asList("a", "b", "c"); List<String> result = new ArrayList<String>(); for (Pair<String, String> pair : Pair.adjacents(strings)) { result.add(pair.toString()); } assertThat(result.toString(), equalTo("[<a, b>, <b, c>]")); // empty source yields empty result assertThat(Pair.adjacents(ImmutableList.of()).iterator().hasNext(), is(false)); // source with 1 element yields empty result assertThat(Pair.adjacents(ImmutableList.of("a")).iterator().hasNext(), is(false)); // source with 100 elements yields result with 99 elements; // null elements are ok assertThat(Iterables.size(Pair.adjacents(Collections.nCopies(100, null))), equalTo(99)); } /** * Unit test for {@link Pair#firstAnd(Iterable)}. */ @Test public void testPairFirstAnd() { List<String> strings = Arrays.asList("a", "b", "c"); List<String> result = new ArrayList<String>(); for (Pair<String, String> pair : Pair.firstAnd(strings)) { result.add(pair.toString()); } assertThat(result.toString(), equalTo("[<a, b>, <a, c>]")); // empty source yields empty result assertThat(Pair.firstAnd(ImmutableList.of()).iterator().hasNext(), is(false)); // source with 1 element yields empty result assertThat(Pair.firstAnd(ImmutableList.of("a")).iterator().hasNext(), is(false)); // source with 100 elements yields result with 99 elements; // null elements are ok assertThat(Iterables.size(Pair.firstAnd(Collections.nCopies(100, null))), equalTo(99)); } /** * Unit test for {@link Util#quotientList(java.util.List, int, int)}. */ @Test public void testQuotientList() { List<String> beatles = Arrays.asList("john", "paul", "george", "ringo"); final List list0 = Util.quotientList(beatles, 3, 0); assertEquals(2, list0.size()); assertEquals("john", list0.get(0)); assertEquals("ringo", list0.get(1)); final List list1 = Util.quotientList(beatles, 3, 1); assertEquals(1, list1.size()); assertEquals("paul", list1.get(0)); final List list2 = Util.quotientList(beatles, 3, 2); assertEquals(1, list2.size()); assertEquals("george", list2.get(0)); try { final List listBad = Util.quotientList(beatles, 3, 4); fail("Expected error, got " + listBad); } catch (IllegalArgumentException e) { // ok } try { final List listBad = Util.quotientList(beatles, 3, 3); fail("Expected error, got " + listBad); } catch (IllegalArgumentException e) { // ok } try { final List listBad = Util.quotientList(beatles, 0, 0); fail("Expected error, got " + listBad); } catch (IllegalArgumentException e) { // ok } // empty final List<String> empty = Collections.emptyList(); final List<String> list3 = Util.quotientList(empty, 7, 2); assertEquals(0, list3.size()); // shorter than n final List list4 = Util.quotientList(beatles, 10, 0); assertEquals(1, list4.size()); assertEquals("john", list4.get(0)); final List list5 = Util.quotientList(beatles, 10, 5); assertEquals(0, list5.size()); } @Test public void testImmutableIntList() { final ImmutableIntList list = ImmutableIntList.of(); assertEquals(0, list.size()); assertEquals(list, Collections.<Integer>emptyList()); assertThat(list.toString(), equalTo("[]")); assertThat(BitSets.of(list), equalTo(new BitSet())); final ImmutableIntList list2 = ImmutableIntList.of(1, 3, 5); assertEquals(3, list2.size()); assertEquals("[1, 3, 5]", list2.toString()); assertEquals(list2.hashCode(), Arrays.asList(1, 3, 5).hashCode()); Integer[] integers = list2.toArray(new Integer[3]); assertEquals(1, (int) integers[0]); assertEquals(3, (int) integers[1]); assertEquals(5, (int) integers[2]); //noinspection EqualsWithItself assertThat(list.equals(list), is(true)); assertThat(list.equals(list2), is(false)); assertThat(list2.equals(list), is(false)); //noinspection EqualsWithItself assertThat(list2.equals(list2), is(true)); } /** * Unit test for {@link IntegerIntervalSet}. */ @Test public void testIntegerIntervalSet() { checkIntegerIntervalSet("1,5", 1, 5); // empty checkIntegerIntervalSet(""); // empty due to exclusions checkIntegerIntervalSet("2,4,-1-5"); // open range checkIntegerIntervalSet("1-6,-3-5,4,9", 1, 2, 4, 6, 9); // repeats checkIntegerIntervalSet("1,3,1,2-4,-2,-4", 1, 3); } private List<Integer> checkIntegerIntervalSet(String s, int... ints) { List<Integer> list = new ArrayList<Integer>(); final Set<Integer> set = IntegerIntervalSet.of(s); assertEquals(set.size(), ints.length); for (Integer integer : set) { list.add(integer); } assertEquals(new HashSet<Integer>(IntList.asList(ints)), set); return list; } /** * Tests that flat lists behave like regular lists in terms of equals * and hashCode. */ @Test public void testFlatList() { final List<String> emp = FlatLists.of(); final List<String> emp0 = Collections.emptyList(); assertEquals(emp, emp0); assertEquals(emp.hashCode(), emp0.hashCode()); final List<String> ab = FlatLists.of("A", "B"); final List<String> ab0 = Arrays.asList("A", "B"); assertEquals(ab, ab0); assertEquals(ab.hashCode(), ab0.hashCode()); final List<String> an = FlatLists.of("A", null); final List<String> an0 = Arrays.asList("A", null); assertEquals(an, an0); assertEquals(an.hashCode(), an0.hashCode()); final List<String> anb = FlatLists.of("A", null, "B"); final List<String> anb0 = Arrays.asList("A", null, "B"); assertEquals(anb, anb0); assertEquals(anb.hashCode(), anb0.hashCode()); } /** * Unit test for {@link AvaticaUtils#toCamelCase(String)}. */ @Test public void testToCamelCase() { assertEquals("myJdbcDriver", AvaticaUtils.toCamelCase("MY_JDBC_DRIVER")); assertEquals("myJdbcDriver", AvaticaUtils.toCamelCase("MY_JDBC__DRIVER")); assertEquals("myJdbcDriver", AvaticaUtils.toCamelCase("my_jdbc_driver")); assertEquals("abCdefGHij", AvaticaUtils.toCamelCase("ab_cdEf_g_Hij")); assertEquals("JdbcDriver", AvaticaUtils.toCamelCase("_JDBC_DRIVER")); assertEquals("", AvaticaUtils.toCamelCase("_")); assertEquals("", AvaticaUtils.toCamelCase("")); } /** Unit test for {@link AvaticaUtils#camelToUpper(String)}. */ @Test public void testCamelToUpper() { assertEquals("MY_JDBC_DRIVER", AvaticaUtils.camelToUpper("myJdbcDriver")); assertEquals("MY_J_D_B_C_DRIVER", AvaticaUtils.camelToUpper("myJDBCDriver")); assertEquals("AB_CDEF_G_HIJ", AvaticaUtils.camelToUpper("abCdefGHij")); assertEquals("_JDBC_DRIVER", AvaticaUtils.camelToUpper("JdbcDriver")); assertEquals("", AvaticaUtils.camelToUpper("")); } /** * Unit test for {@link Util#isDistinct(java.util.List)}. */ @Test public void testDistinct() { assertTrue(Util.isDistinct(Collections.emptyList())); assertTrue(Util.isDistinct(Arrays.asList("a"))); assertTrue(Util.isDistinct(Arrays.asList("a", "b", "c"))); assertFalse(Util.isDistinct(Arrays.asList("a", "b", "a"))); assertTrue(Util.isDistinct(Arrays.asList("a", "b", null))); assertFalse(Util.isDistinct(Arrays.asList("a", null, "b", null))); } /** * Unit test for {@link org.apache.calcite.util.JsonBuilder}. */ @Test public void testJsonBuilder() { JsonBuilder builder = new JsonBuilder(); Map<String, Object> map = builder.map(); map.put("foo", 1); map.put("baz", true); map.put("bar", "can't"); List<Object> list = builder.list(); map.put("list", list); list.add(2); list.add(3); list.add(builder.list()); list.add(builder.map()); list.add(null); map.put("nullValue", null); assertEquals( "{\n" + " foo: 1,\n" + " baz: true,\n" + " bar: \"can't\",\n" + " list: [\n" + " 2,\n" + " 3,\n" + " [],\n" + " {},\n" + " null\n" + " ],\n" + " nullValue: null\n" + "}", builder.toJsonString(map)); } @Test public void testCompositeMap() { String[] beatles = {"john", "paul", "george", "ringo"}; Map<String, Integer> beatleMap = new LinkedHashMap<String, Integer>(); for (String beatle : beatles) { beatleMap.put(beatle, beatle.length()); } CompositeMap<String, Integer> map = CompositeMap.of(beatleMap); checkCompositeMap(beatles, map); map = CompositeMap.of( beatleMap, Collections.<String, Integer>emptyMap()); checkCompositeMap(beatles, map); map = CompositeMap.of( Collections.<String, Integer>emptyMap(), beatleMap); checkCompositeMap(beatles, map); map = CompositeMap.of(beatleMap, beatleMap); checkCompositeMap(beatles, map); final Map<String, Integer> founderMap = new LinkedHashMap<String, Integer>(); founderMap.put("ben", 1706); founderMap.put("george", 1732); founderMap.put("thomas", 1743); map = CompositeMap.of(beatleMap, founderMap); assertThat(map.isEmpty(), equalTo(false)); assertThat(map.size(), equalTo(6)); assertThat(map.keySet().size(), equalTo(6)); assertThat(map.entrySet().size(), equalTo(6)); assertThat(map.values().size(), equalTo(6)); assertThat(map.containsKey("john"), equalTo(true)); assertThat(map.containsKey("george"), equalTo(true)); assertThat(map.containsKey("ben"), equalTo(true)); assertThat(map.containsKey("andrew"), equalTo(false)); assertThat(map.get("ben"), equalTo(1706)); assertThat(map.get("george"), equalTo(6)); // use value from first map assertThat(map.values().contains(1743), equalTo(true)); assertThat(map.values().contains(1732), equalTo(false)); // masked assertThat(map.values().contains(1999), equalTo(false)); } private void checkCompositeMap(String[] beatles, Map<String, Integer> map) { assertThat(4, equalTo(map.size())); assertThat(false, equalTo(map.isEmpty())); assertThat( map.keySet(), equalTo((Set<String>) new HashSet<String>(Arrays.asList(beatles)))); assertThat( ImmutableMultiset.copyOf(map.values()), equalTo(ImmutableMultiset.copyOf(Arrays.asList(4, 4, 6, 5)))); } /** Tests {@link Util#commaList(java.util.List)}. */ @Test public void testCommaList() { try { String s = Util.commaList(null); fail("expected NPE, got " + s); } catch (NullPointerException e) { // ok } assertThat(Util.commaList(ImmutableList.<Object>of()), equalTo("")); assertThat(Util.commaList(ImmutableList.of(1)), equalTo("1")); assertThat(Util.commaList(ImmutableList.of(2, 3)), equalTo("2, 3")); assertThat(Util.commaList(Arrays.asList(2, null, 3)), equalTo("2, null, 3")); } /** Unit test for {@link Util#firstDuplicate(java.util.List)}. */ @Test public void testFirstDuplicate() { assertThat(Util.firstDuplicate(ImmutableList.of()), equalTo(-1)); assertThat(Util.firstDuplicate(ImmutableList.of(5)), equalTo(-1)); assertThat(Util.firstDuplicate(ImmutableList.of(5, 6)), equalTo(-1)); assertThat(Util.firstDuplicate(ImmutableList.of(5, 6, 5)), equalTo(2)); assertThat(Util.firstDuplicate(ImmutableList.of(5, 5, 6)), equalTo(1)); assertThat(Util.firstDuplicate(ImmutableList.of(5, 5, 6, 5)), equalTo(1)); // list longer than 15, the threshold where we move to set-based algorithm assertThat( Util.firstDuplicate( ImmutableList.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 3, 19, 3, 21)), equalTo(18)); } /** Benchmark for {@link Util#isDistinct}. Has determined that map-based * implementation is better than nested loops implementation if list is larger * than about 15. */ @Test public void testIsDistinctBenchmark() { // Run a much quicker form of the test during regular testing. final int limit = Benchmark.enabled() ? 1000000 : 10; final int zMax = 100; for (int i = 0; i < 30; i++) { final int size = i; new Benchmark("isDistinct " + i + " (set)", new Function1<Benchmark.Statistician, Void>() { public Void apply(Benchmark.Statistician statistician) { final Random random = new Random(0); final List<List<Integer>> lists = new ArrayList<List<Integer>>(); for (int z = 0; z < zMax; z++) { final List<Integer> list = new ArrayList<Integer>(); for (int k = 0; k < size; k++) { list.add(random.nextInt(size * size)); } lists.add(list); } long nanos = System.nanoTime(); int n = 0; for (int j = 0; j < limit; j++) { n += Util.firstDuplicate(lists.get(j % zMax)); } statistician.record(nanos); Util.discard(n); return null; } }, 5).run(); } } /** Unit test for {@link Util#hashCode(double)}. */ @Test public void testHash() { checkHash(0d); checkHash(1d); checkHash(-2.5d); checkHash(10d / 3d); checkHash(Double.NEGATIVE_INFINITY); checkHash(Double.POSITIVE_INFINITY); checkHash(Double.MAX_VALUE); checkHash(Double.MIN_VALUE); } public void checkHash(double v) { assertThat(new Double(v).hashCode(), equalTo(Util.hashCode(v))); } /** Unit test for {@link Util#startsWith}. */ @Test public void testStartsWithList() { assertThat(Util.startsWith(list("x"), list()), is(true)); assertThat(Util.startsWith(list("x"), list("x")), is(true)); assertThat(Util.startsWith(list("x"), list("y")), is(false)); assertThat(Util.startsWith(list("x"), list("x", "y")), is(false)); assertThat(Util.startsWith(list("x", "y"), list("x")), is(true)); assertThat(Util.startsWith(list(), list()), is(true)); assertThat(Util.startsWith(list(), list("x")), is(false)); } public List<String> list(String... xs) { return Arrays.asList(xs); } @Test public void testResources() { Resources.validate(Static.RESOURCE); } /** Tests that sorted sets behave the way we expect. */ @Test public void testSortedSet() { final TreeSet<String> treeSet = new TreeSet<String>(); Collections.addAll(treeSet, "foo", "bar", "fOo", "FOO", "pug"); assertThat(treeSet.size(), equalTo(5)); final TreeSet<String> treeSet2 = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER); treeSet2.addAll(treeSet); assertThat(treeSet2.size(), equalTo(3)); final Comparator<String> comparator = new Comparator<String>() { public int compare(String o1, String o2) { String u1 = o1.toUpperCase(); String u2 = o2.toUpperCase(); int c = u1.compareTo(u2); if (c == 0) { c = o1.compareTo(o2); } return c; } }; final TreeSet<String> treeSet3 = new TreeSet<String>(comparator); treeSet3.addAll(treeSet); assertThat(treeSet3.size(), equalTo(5)); assertThat(checkNav(treeSet3, "foo").size(), equalTo(3)); assertThat(checkNav(treeSet3, "FOO").size(), equalTo(3)); assertThat(checkNav(treeSet3, "FoO").size(), equalTo(3)); assertThat(checkNav(treeSet3, "BAR").size(), equalTo(1)); final ImmutableSortedSet<String> treeSet4 = ImmutableSortedSet.copyOf(comparator, treeSet); final NavigableSet<String> navigableSet4 = Compatible.INSTANCE.navigableSet(treeSet4); assertThat(treeSet4.size(), equalTo(5)); assertThat(navigableSet4.size(), equalTo(5)); assertThat(navigableSet4, equalTo((SortedSet<String>) treeSet4)); assertThat(checkNav(navigableSet4, "foo").size(), equalTo(3)); assertThat(checkNav(navigableSet4, "FOO").size(), equalTo(3)); assertThat(checkNav(navigableSet4, "FoO").size(), equalTo(3)); assertThat(checkNav(navigableSet4, "BAR").size(), equalTo(1)); } private NavigableSet<String> checkNav(NavigableSet<String> set, String s) { return set.subSet(s.toUpperCase(), true, s.toLowerCase(), true); } /** Test for {@link org.apache.calcite.util.ImmutableNullableList}. */ @Test public void testImmutableNullableList() { final List<String> arrayList = Arrays.asList("a", null, "c"); final List<String> list = ImmutableNullableList.copyOf(arrayList); assertThat(list.size(), equalTo(arrayList.size())); assertThat(list, equalTo(arrayList)); assertThat(list.hashCode(), equalTo(arrayList.hashCode())); assertThat(list.toString(), equalTo(arrayList.toString())); String z = ""; for (String s : list) { z += s; } assertThat(z, equalTo("anullc")); // changes to array list do not affect copy arrayList.set(0, "z"); assertThat(arrayList.get(0), equalTo("z")); assertThat(list.get(0), equalTo("a")); try { boolean b = list.add("z"); fail("expected error, got " + b); } catch (UnsupportedOperationException e) { // ok } try { String b = list.set(1, "z"); fail("expected error, got " + b); } catch (UnsupportedOperationException e) { // ok } // empty list uses ImmutableList assertThat(ImmutableNullableList.copyOf(Collections.emptyList()), isA((Class) ImmutableList.class)); // list with no nulls uses ImmutableList assertThat(ImmutableNullableList.copyOf(Arrays.asList("a", "b", "c")), isA((Class) ImmutableList.class)); } /** Test for {@link org.apache.calcite.util.UnmodifiableArrayList}. */ @Test public void testUnmodifiableArrayList() { final String[] strings = {"a", null, "c"}; final List<String> arrayList = Arrays.asList(strings); final List<String> list = UnmodifiableArrayList.of(strings); assertThat(list.size(), equalTo(arrayList.size())); assertThat(list, equalTo(arrayList)); assertThat(list.hashCode(), equalTo(arrayList.hashCode())); assertThat(list.toString(), equalTo(arrayList.toString())); String z = ""; for (String s : list) { z += s; } assertThat(z, equalTo("anullc")); // changes to array list do affect copy arrayList.set(0, "z"); assertThat(arrayList.get(0), equalTo("z")); assertThat(list.get(0), equalTo("z")); try { boolean b = list.add("z"); fail("expected error, got " + b); } catch (UnsupportedOperationException e) { // ok } try { String b = list.set(1, "z"); fail("expected error, got " + b); } catch (UnsupportedOperationException e) { // ok } } /** Test for {@link org.apache.calcite.util.ImmutableNullableList.Builder}. */ @Test public void testImmutableNullableListBuilder() { final ImmutableNullableList.Builder<String> builder = ImmutableNullableList.builder(); builder.add("a") .add((String) null) .add("c"); final List<String> arrayList = Arrays.asList("a", null, "c"); final List<String> list = builder.build(); assertThat(arrayList.equals(list), is(true)); } @Test public void testHuman() { assertThat(Util.human(0D), equalTo("0")); assertThat(Util.human(1D), equalTo("1")); assertThat(Util.human(19D), equalTo("19")); assertThat(Util.human(198D), equalTo("198")); assertThat(Util.human(1000D), equalTo("1.00K")); assertThat(Util.human(1002D), equalTo("1.00K")); assertThat(Util.human(1009D), equalTo("1.01K")); assertThat(Util.human(1234D), equalTo("1.23K")); assertThat(Util.human(1987D), equalTo("1.99K")); assertThat(Util.human(1999D), equalTo("2.00K")); assertThat(Util.human(86837.2D), equalTo("86.8K")); assertThat(Util.human(868372.8D), equalTo("868K")); assertThat(Util.human(1009000D), equalTo("1.01M")); assertThat(Util.human(1999999D), equalTo("2.00M")); assertThat(Util.human(1009000000D), equalTo("1.01G")); assertThat(Util.human(1999999000D), equalTo("2.00G")); assertThat(Util.human(-1D), equalTo("-1")); assertThat(Util.human(-19D), equalTo("-19")); assertThat(Util.human(-198D), equalTo("-198")); assertThat(Util.human(-1999999000D), equalTo("-2.00G")); // not ideal - should use m (milli) and u (micro) assertThat(Util.human(0.18D), equalTo("0.18")); assertThat(Util.human(0.018D), equalTo("0.018")); assertThat(Util.human(0.0018D), equalTo("0.0018")); assertThat(Util.human(0.00018D), equalTo("1.8E-4")); assertThat(Util.human(0.000018D), equalTo("1.8E-5")); assertThat(Util.human(0.0000018D), equalTo("1.8E-6")); // bad - should round to 3 digits assertThat(Util.human(0.181111D), equalTo("0.181111")); assertThat(Util.human(0.0181111D), equalTo("0.0181111")); assertThat(Util.human(0.00181111D), equalTo("0.00181111")); assertThat(Util.human(0.000181111D), equalTo("1.81111E-4")); assertThat(Util.human(0.0000181111D), equalTo("1.81111E-5")); assertThat(Util.human(0.00000181111D), equalTo("1.81111E-6")); } @Test public void testAsIndexView() { final List<String> values = Lists.newArrayList("abCde", "X", "y"); final Map<String, String> map = Util.asIndexMap(values, new Function<String, String>() { public String apply(@Nullable String input) { return input.toUpperCase(); } }); assertThat(map.size(), equalTo(values.size())); assertThat(map.get("X"), equalTo("X")); assertThat(map.get("Y"), equalTo("y")); assertThat(map.get("y"), is((String) null)); assertThat(map.get("ABCDE"), equalTo("abCde")); // If you change the values collection, the map changes. values.remove(1); assertThat(map.size(), equalTo(values.size())); assertThat(map.get("X"), is((String) null)); assertThat(map.get("Y"), equalTo("y")); } @Test public void testRelBuilderExample() { new RelBuilderExample(false).runAllExamples(); } @Test public void testOrdReverse() { checkOrdReverse(Ord.reverse(Arrays.asList("a", "b", "c"))); checkOrdReverse(Ord.reverse("a", "b", "c")); assertThat(Ord.reverse(ImmutableList.<String>of()).iterator().hasNext(), is(false)); assertThat(Ord.reverse().iterator().hasNext(), is(false)); } private void checkOrdReverse(Iterable<Ord<String>> reverse1) { final Iterator<Ord<String>> reverse = reverse1.iterator(); assertThat(reverse.hasNext(), is(true)); assertThat(reverse.next().i, is(2)); assertThat(reverse.hasNext(), is(true)); assertThat(reverse.next().e, is("b")); assertThat(reverse.hasNext(), is(true)); assertThat(reverse.next().e, is("a")); assertThat(reverse.hasNext(), is(false)); } } // End UtilTest.java
apache-2.0
3p14/weather
src/com/weather/app/db/WeatherDB.java
3630
package com.weather.app.db; import java.util.ArrayList; import java.util.List; import com.weather.app.model.City; import com.weather.app.model.County; import com.weather.app.model.Province; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class WeatherDB { public static final String DB_NAME = "weather"; public static final int VERSION = 1; private static WeatherDB weatherDB; private SQLiteDatabase db; private WeatherDB(Context context){ WeatherOpenHelper dbHelper = new WeatherOpenHelper(context, DB_NAME, null, VERSION); db = dbHelper.getWritableDatabase(); } public synchronized static WeatherDB getInstance(Context context){ if(weatherDB == null){ weatherDB = new WeatherDB(context); } return weatherDB; } public void saveProvince(Province province){ if(province != null){ ContentValues values = new ContentValues(); values.put("province_name", province.getProvinceName()); values.put("province_code", province.getProvinceCode()); db.insert("Province", null, values); } } public List<Province> loadProvinces(){ List<Province> list = new ArrayList<Province>(); Cursor cursor = db.query("Province", null, null, null, null, null, null); if(cursor.moveToFirst()){ do{ Province province = new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name"))); province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code"))); list.add(province); }while(cursor.moveToNext()); } return list; } public void saveCity(City city){ if(city != null){ ContentValues values = new ContentValues(); values.put("city_name", city.getCityName()); values.put("city_code", city.getCityCode()); values.put("province_id", city.getProvinceId()); db.insert("City", null, values); } } public List<City> loadCities(int provinceId){ List<City> list = new ArrayList<City>(); Cursor cursor = db.query("City", null, "province_id = ?", new String[]{String.valueOf(provinceId)}, null, null, null); if(cursor.moveToFirst()){ do{ City city = new City(); city.setId(cursor.getInt(cursor.getColumnIndex("id"))); city.setCityName(cursor.getString(cursor.getColumnIndex("city_name"))); city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code"))); city.setProvinceId(provinceId); list.add(city); }while(cursor.moveToNext()); } return list; } public void saveCounty(County county){ if(county != null){ ContentValues values = new ContentValues(); values.put("county_name", county.getCountyName()); values.put("county_code", county.getCountyCode()); values.put("city_id", county.getCityId()); db.insert("County", null, values); } } public List<County> loadCounties(int cityId){ List<County> list = new ArrayList<County>(); Cursor cursor = db.query("County", null, "city_id = ?", new String[]{String.valueOf(cityId)}, null, null, null); if(cursor.moveToFirst()){ do{ County county = new County(); county.setId(cursor.getInt(cursor.getColumnIndex("id"))); county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name"))); county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code"))); county.setCityId(cityId); list.add(county); }while(cursor.moveToNext()); } return list; } }
apache-2.0
RizalLovins/LovinsSmartKasir
app/src/main/java/com/rizal/lovins/smartkasir/activity/MapsActivity.java
3259
package com.rizal.lovins.smartkasir.activity; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.rizal.lovins.smartkasir.R; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } Location location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { sydney = new LatLng(location.getLatitude(), location.getLongitude()); } mMap.addMarker(new MarkerOptions().position(sydney).title("Current Position")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } }
apache-2.0
topie/topie-oa
src/main/java/com/topie/humantask/rule/SuperiorAssigneeRule.java
922
package com.topie.humantask.rule; import java.util.Collections; import java.util.List; import com.topie.api.org.OrgConnector; import com.topie.core.spring.ApplicationContextHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 获得指定用户的上级领导. * */ public class SuperiorAssigneeRule implements AssigneeRule { private static Logger logger = LoggerFactory .getLogger(SuperiorAssigneeRule.class); private OrgConnector orgConnector; public List<String> process(String value, String initiator) { return Collections.singletonList(this.process(initiator)); } /** * 获得员工的直接上级. */ public String process(String initiator) { if (orgConnector == null) { orgConnector = ApplicationContextHelper.getBean(OrgConnector.class); } return orgConnector.getSuperiorId(initiator); } }
apache-2.0
pnerg/java-scala-util
src/main/java/javascalautils/concurrent/ExecutorImpl.java
4857
/** * Copyright 2015 Peter Nerg * * <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 javascalautils.concurrent; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import static javascalautils.concurrent.PromiseCompanion.Promise; /** * Implements the executor interface. <br> * Internally uses a Java concurrent executor to provide the thread execution mechanism. * * @author Peter Nerg * @since 1.2 */ final class ExecutorImpl implements Executor { /** The internal Java concurrent executor to perform the actual work. */ private final java.util.concurrent.Executor executor; /** * Creates an instance using the provided SDK {@link java.util.concurrent.Executor} for thread * management. * * @param executor The underlying executor to use * @since 1.2 */ ExecutorImpl(java.util.concurrent.Executor executor) { this.executor = executor; } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#execute(javascalautils.concurrent.Executable) */ @Override public <T> Future<T> execute(final Executable<T> executable) { final Promise<T> promise = Promise(); return execute( promise, () -> { try { executable.execute(promise); // if the implementation didn't respond to the Promise we mark it as a failure. if (!promise.isCompleted()) { promise.failure(new IllegalStateException("No response was provided by the Promise")); } } catch (Exception ex) { promise.failure(ex); } }); } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#execute(java.util.concurrent.Callable) */ @Override public <T> Future<T> execute(final Callable<T> callable) { final Promise<T> promise = Promise(); return execute( promise, () -> { try { promise.success(callable.call()); } catch (Exception ex) { promise.failure(ex); } }); } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#executeAll(javascalautils.concurrent.Executable<T>[]) */ @Override public <T> List<Future<T>> executeAll( @SuppressWarnings("unchecked") Executable<T>... executables) { List<Future<T>> responses = new ArrayList<>(); for (Executable<T> executable : executables) { responses.add(execute(executable)); } return responses; } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#executeAll(java.util.concurrent.Callable<T>[]) */ @Override public <T> List<Future<T>> executeAll(@SuppressWarnings("unchecked") Callable<T>... callables) { List<Future<T>> responses = new ArrayList<>(); for (Callable<T> callable : callables) { responses.add(execute(callable)); } return responses; } /** * Executes the provided {@link Runnable} on the internal executor. <br> * Any issues related to the internal executor are reported to the provided {@link Promise} * * @param promise The promise to fulfill once the work is finished * @param runnable The runnable to execute in the executor * @return The Future holding the response-to-be */ private <T> Future<T> execute(Promise<T> promise, Runnable runnable) { try { executor.execute(runnable); } catch (RejectedExecutionException ex) { // could be rejected due to resource starvation, report a failure promise.failure(ex); } return promise.future(); } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#shutdown() */ @Override public void shutdown() { if (executor instanceof ExecutorService) { ((ExecutorService) executor).shutdown(); } } /* * (non-Javadoc) * * @see javascalautils.concurrent.Executor#awaitTermination(long, java.util.concurrent.TimeUnit) */ @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { if (executor instanceof ExecutorService) { return ((ExecutorService) executor).awaitTermination(timeout, unit); } return true; } }
apache-2.0
ontopia/ontopia
ontopia-engine/src/main/java/net/ontopia/topicmaps/cmdlineutils/rdbms/TranslateSourceLocators.java
4242
/* * #! * 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.topicmaps.cmdlineutils.rdbms; import java.util.Iterator; import java.io.File; import net.ontopia.infoset.core.LocatorIF; import net.ontopia.topicmaps.core.TopicIF; import net.ontopia.topicmaps.core.TopicMapIF; import net.ontopia.topicmaps.core.UniquenessViolationException; import net.ontopia.topicmaps.impl.rdbms.RDBMSTopicMapStore; import net.ontopia.topicmaps.utils.MergeUtils; import net.ontopia.utils.CmdlineOptions; import net.ontopia.utils.CmdlineUtils; import net.ontopia.utils.URIUtils; /** * INTERNAL: Command line utility for translating the source locators * in an imported topic map from their original base to the new base. * * @since 2.0 */ public class TranslateSourceLocators { public static void main(String[] argv) throws Exception { // Initialize logging CmdlineUtils.initializeLogging(); // Register logging options CmdlineOptions options = new CmdlineOptions("TranslateSourceLocators", argv); CmdlineUtils.registerLoggingOptions(options); // Parse command line options try { options.parse(); } catch (CmdlineOptions.OptionsException e) { System.err.println("Error: " + e.getMessage()); System.exit(1); } // Get command line arguments String[] args = options.getArguments(); if (args.length < 3 || args.length > 3) { usage(); System.exit(3); } translate(args[0], args[1], args[2]); } private static void translate(String propfile, String tmid, String tmfile) throws Exception { RDBMSTopicMapStore store = new RDBMSTopicMapStore(propfile, Integer.parseInt(tmid)); TopicMapIF tm = store.getTopicMap(); LocatorIF newbase = store.getBaseAddress(); String oldbase = newbase.resolveAbsolute(URIUtils.toURL(new File(tmfile)).toString()).getAddress(); int oldlen = oldbase.length(); Iterator it = tm.getTopics().iterator(); while (it.hasNext()) { TopicIF topic = (TopicIF) it.next(); Object[] srclocs = topic.getItemIdentifiers().toArray(); for (int ix = 0; ix < srclocs.length; ix++) { LocatorIF srcloc = (LocatorIF) srclocs[ix]; String url = srcloc.getAddress(); if (url.startsWith(oldbase)) { LocatorIF newloc = newbase.resolveAbsolute(url.substring(oldlen)); topic.removeItemIdentifier(srcloc); try { topic.addItemIdentifier(newloc); } catch (UniquenessViolationException e) { // ooops! this topic already exists, so we must merge TopicIF other = (TopicIF) tm.getObjectByItemIdentifier(newloc); if (other == null) other = tm.getTopicBySubjectIdentifier(newloc); MergeUtils.mergeInto(other, topic); // this kills our topic, not the other } } } } store.commit(); store.close(); } private static void usage() { System.out.println("java net.ontopia.topicmaps.cmdlineutils.rdbms.TranslateSourceLocators [options] <dbprops> <tmid> <tmfile>"); System.out.println(""); System.out.println(" Translates the base addresses of source locators to that of the topic map."); System.out.println(""); System.out.println(" Options:"); CmdlineUtils.printLoggingOptionsUsage(System.out); System.out.println(""); System.out.println(" <dbprops>: the database configuration file"); System.out.println(" <tmid> : the id of the topic map to modify"); System.out.println(" <tmfile> : the original file name"); System.out.println(""); } }
apache-2.0
cominvent/solr-explorer
src/main/java/org/apache/solr/explorer/client/core/manager/ui/DefaultProgressIndicator.java
2187
/* * Copyright 2011 SearchWorkings.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.explorer.client.core.manager.ui; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.PopupPanel; import com.google.gwt.user.client.Window; /** * A simple implementation of a {@link ProgressIndicator} that shows a message on the middle-top part of the screen. * * @author Uri Boness */ public class DefaultProgressIndicator extends PopupPanel implements ProgressIndicator { private Label messageLabel; /** * Constructs a new MessageProgressIndicator with a default message. */ public DefaultProgressIndicator() { this("Loading..."); } /** * Constructs a new MessageProgressIndicator with a given initial message to be displayed. * * @param message The initial message to be displayed. */ public DefaultProgressIndicator(String message) { super(false, true); messageLabel = new Label(message); messageLabel.setStyleName("Label"); setPopupPositionAndShow(new PopupPanel.PositionCallback() { public void setPosition(int offsetWidth, int offsetHeight) { int x = Window.getClientWidth()/2 - offsetWidth/2; setPopupPosition(x, 0); } }); setWidget(messageLabel); setStyleName("DefaultProgressIndicator"); } /** * Sets the message this indicator should display. Can be set while the indicator is already displayed. * * @param message The message this indicator should display. */ public void setMessage(String message) { messageLabel.setText(message); } }
apache-2.0
infakt/material-menu
library/src/main/java/com/balysv/materialmenu/MaterialMenuDrawable.java
26723
/* * Copyright (C) 2014 Balys Valentukevicius * * 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.balysv.materialmenu; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.util.TypedValue; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.util.Property; import static android.graphics.Paint.Style; public class MaterialMenuDrawable extends Drawable implements Animatable { public enum IconState { BURGER, ARROW, X, CHECK } public enum Stroke { /** * 3 dip */ REGULAR(3), /** * 2 dip */ THIN(2), /** * 1 dip */ EXTRA_THIN(1); private final int strokeWidth; Stroke(int strokeWidth) { this.strokeWidth = strokeWidth; } protected static Stroke valueOf(int strokeWidth) { switch (strokeWidth) { case 3: return REGULAR; case 2: return THIN; case 1: return EXTRA_THIN; default: return REGULAR; } } } public static final int DEFAULT_COLOR = Color.WHITE; public static final int DEFAULT_SCALE = 1; public static final int DEFAULT_TRANSFORM_DURATION = 800; public static final int DEFAULT_PRESSED_DURATION = 400; private enum AnimationState { BURGER_ARROW, BURGER_X, ARROW_X, ARROW_CHECK, BURGER_CHECK, X_CHECK } private static final int BASE_DRAWABLE_WIDTH = 40; private static final int BASE_DRAWABLE_HEIGHT = 40; private static final int BASE_ICON_WIDTH = 20; private static final int BASE_CIRCLE_RADIUS = 18; private static final int BASE_GRID_OFFSET = 6; private static final float ARROW_MID_LINE_ANGLE = 180; private static final float ARROW_TOP_LINE_ANGLE = 135; private static final float ARROW_BOT_LINE_ANGLE = 225; private static final float X_TOP_LINE_ANGLE = 44; private static final float X_BOT_LINE_ANGLE = -44; private static final float X_ROTATION_ANGLE = 90; private static final float CHECK_MIDDLE_ANGLE = 135; private static final float CHECK_BOTTOM_ANGLE = -90; private static final float TRANSFORMATION_START = 0; private static final float TRANSFORMATION_MID = 1.0f; private static final float TRANSFORMATION_END = 2.0f; private static final int DEFAULT_CIRCLE_ALPHA = 200; private final float diph; private final float dip1; private final float dip2; private final float dip3; private final float dip4; private final float dip6; private final float dip8; private final int width; private final int height; private final float strokeWidth; private final float iconWidth; private final float topPadding; private final float sidePadding; private final float circleRadius; private final float gridOffset; private final Stroke stroke; private final Paint gridPaint; private final Paint iconPaint; private final Paint circlePaint; private float transformationValue = 0f; private float pressedProgressValue = 0f; private boolean transformationRunning = false; private boolean drawGrid = false; private IconState currentIconState = IconState.BURGER; private AnimationState animationState = AnimationState.BURGER_ARROW; private IconState animatingIconState; private boolean drawTouchCircle; private boolean neverDrawTouch; private ObjectAnimator transformation; private ObjectAnimator pressedCircle; public MaterialMenuDrawable(Context context, int color, Stroke stroke) { this(context, color, stroke, DEFAULT_SCALE, DEFAULT_TRANSFORM_DURATION, DEFAULT_PRESSED_DURATION); } public MaterialMenuDrawable(Context context, int color, Stroke stroke, int transformDuration, int pressedDuration) { this(context, color, stroke, DEFAULT_SCALE, transformDuration, pressedDuration); } public MaterialMenuDrawable(Context context, int color, Stroke stroke, int scale, int transformDuration, int pressedDuration) { Resources resources = context.getResources(); // convert each separately due to various densities this.dip1 = dpToPx(resources, 1) * scale; this.dip2 = dpToPx(resources, 2) * scale; this.dip3 = dpToPx(resources, 3) * scale; this.dip4 = dpToPx(resources, 4) * scale; this.dip6 = dpToPx(resources, 6) * scale; this.dip8 = dpToPx(resources, 8) * scale; this.diph = dip1 / 2; this.stroke = stroke; this.width = (int) (dpToPx(resources, BASE_DRAWABLE_WIDTH) * scale); this.height = (int) (dpToPx(resources, BASE_DRAWABLE_HEIGHT) * scale); this.iconWidth = dpToPx(resources, BASE_ICON_WIDTH) * scale; this.circleRadius = dpToPx(resources, BASE_CIRCLE_RADIUS) * scale; this.strokeWidth = dpToPx(resources, stroke.strokeWidth) * scale; this.sidePadding = (width - iconWidth) / 2; this.topPadding = (height - 5 * dip3) / 2; this.gridOffset = dpToPx(resources, BASE_GRID_OFFSET) * scale; gridPaint = new Paint(); gridPaint.setAntiAlias(false); gridPaint.setColor(Color.GREEN); gridPaint.setStrokeWidth(1); iconPaint = new Paint(); iconPaint.setAntiAlias(true); iconPaint.setStyle(Style.STROKE); iconPaint.setStrokeWidth(strokeWidth); iconPaint.setColor(color); circlePaint = new Paint(); circlePaint.setAntiAlias(true); circlePaint.setStyle(Style.FILL); circlePaint.setColor(color); circlePaint.setAlpha(DEFAULT_CIRCLE_ALPHA); setBounds(0, 0, width, height); initAnimations(transformDuration, pressedDuration); } /* * Drawing */ @Override public void draw(Canvas canvas) { if (drawGrid) drawGrid(canvas); final float ratio = transformationValue <= 1 ? transformationValue : 2 - transformationValue; drawTopLine(canvas, ratio); drawMiddleLine(canvas, ratio); drawBottomLine(canvas, ratio); if (drawTouchCircle) drawTouchCircle(canvas); } private void drawTouchCircle(Canvas canvas) { canvas.restore(); canvas.drawCircle(width / 2, height / 2, pressedProgressValue, circlePaint); } private void drawMiddleLine(Canvas canvas, float ratio) { canvas.restore(); canvas.save(); float rotation = 0; float pivotX = width / 2; float pivotY = width / 2; float startX = sidePadding; float startY = topPadding + dip3 / 2 * 5; float stopX = width - sidePadding; float stopY = topPadding + dip3 / 2 * 5; int alpha = 255; switch (animationState) { case BURGER_ARROW: // rotate by 180 if (isMorphingForward()) { rotation = ratio * ARROW_MID_LINE_ANGLE; } else { rotation = ARROW_MID_LINE_ANGLE + (1 - ratio) * ARROW_MID_LINE_ANGLE; } // shorten one end stopX -= ratio * resolveStrokeModifier(ratio) / 2; break; case BURGER_X: // fade out alpha = (int) ((1 - ratio) * 255); break; case ARROW_X: // fade out and shorten one end alpha = (int) ((1 - ratio) * 255); startX += (1 - ratio) * dip2; break; case ARROW_CHECK: if (isMorphingForward()) { // rotate until required angle rotation = ratio * CHECK_MIDDLE_ANGLE; // lengthen both ends startX += dip3 / 2 + ratio * dip4; stopX += ratio * (dip8 + diph); } else { // rotate back to starting angle rotation = CHECK_MIDDLE_ANGLE - CHECK_MIDDLE_ANGLE * (1 - ratio); // shorten one end and lengthen the other startX += dip3 / 2 + dip4 - (1 - ratio) * (dip2 + diph); stopX += dip8 - (1 - ratio) * (dip2 + dip6); } pivotX = width / 2 + dip3 * 2; break; case BURGER_CHECK: // rotate until required angle rotation = ratio * CHECK_MIDDLE_ANGLE; // lengthen both ends startX += ratio * (dip4 + dip3 / 2); stopX += ratio * (dip8 + diph); pivotX = width / 2 + dip3 * 2; break; case X_CHECK: // fade in alpha = (int) (ratio * 255); // rotation to check angle rotation = ratio * CHECK_MIDDLE_ANGLE; // lengthen both ends startX += ratio * (dip4 + dip3 / 2); stopX += ratio * (dip8 + diph); pivotX = width / 2 + dip3 * 2; break; } iconPaint.setAlpha(alpha); canvas.rotate(rotation, pivotX, pivotY); canvas.drawLine(startX, startY, stopX, stopY, iconPaint); iconPaint.setAlpha(255); } private void drawTopLine(Canvas canvas, float ratio) { canvas.save(); float rotation = 0, pivotX = 0, pivotY = 0; float rotation2 = 0; // pivot at center of line float pivotX2 = width / 2 + dip3 / 2; float pivotY2 = topPadding + dip2; float startX = sidePadding; float startY = topPadding + dip2; float stopX = width - sidePadding; float stopY = topPadding + dip2; int alpha = 255; switch (animationState) { case BURGER_ARROW: if (isMorphingForward()) { // rotate until required angle rotation = ratio * ARROW_BOT_LINE_ANGLE; } else { // rotate back to start doing a 360 rotation = ARROW_BOT_LINE_ANGLE + (1 - ratio) * ARROW_TOP_LINE_ANGLE; } // rotate by middle pivotX = width / 2; pivotY = height / 2; // shorten both ends stopX -= resolveStrokeModifier(ratio); startX += dip3 * ratio; break; case BURGER_X: // rotate until required angles rotation = X_TOP_LINE_ANGLE * ratio; rotation2 = X_ROTATION_ANGLE * ratio; // pivot at left corner of line pivotX = sidePadding + dip4; pivotY = topPadding + dip3; // lengthen one end stopX += dip3 * ratio; break; case ARROW_X: // rotate from ARROW angle to X angle rotation = ARROW_BOT_LINE_ANGLE + (X_TOP_LINE_ANGLE - ARROW_BOT_LINE_ANGLE) * ratio; rotation2 = X_ROTATION_ANGLE * ratio; // move pivot from ARROW pivot to X pivot pivotX = width / 2 + (sidePadding + dip4 - width / 2) * ratio; pivotY = height / 2 + (topPadding + dip3 - height / 2) * ratio; // lengthen both ends stopX -= resolveStrokeModifier(ratio); startX += dip3 * (1 - ratio); break; case ARROW_CHECK: // fade out alpha = (int) ((1 - ratio) * 255); // retain starting arrow configuration rotation = ARROW_BOT_LINE_ANGLE; pivotX = width / 2; pivotY = height / 2; // shorted both ends stopX -= resolveStrokeModifier(1); startX += dip3; break; case BURGER_CHECK: // fade out alpha = (int) ((1 - ratio) * 255); break; case X_CHECK: // retain X configuration rotation = X_TOP_LINE_ANGLE; rotation2 = X_ROTATION_ANGLE; pivotX = sidePadding + dip4; pivotY = topPadding + dip3; stopX += dip3; // fade out alpha = (int) ((1 - ratio) * 255); break; } iconPaint.setAlpha(alpha); canvas.rotate(rotation, pivotX, pivotY); canvas.rotate(rotation2, pivotX2, pivotY2); canvas.drawLine(startX, startY, stopX, stopY, iconPaint); iconPaint.setAlpha(255); } private void drawBottomLine(Canvas canvas, float ratio) { canvas.restore(); canvas.save(); float rotation = 0, pivotX = 0, pivotY = 0; float rotation2 = 0; // pivot at center of line float pivotX2 = width / 2 + dip3 / 2; float pivotY2 = height - topPadding - dip2; float startX = sidePadding; float startY = height - topPadding - dip2; float stopX = width - sidePadding; float stopY = height - topPadding - dip2; switch (animationState) { case BURGER_ARROW: if (isMorphingForward()) { // rotate to required angle rotation = ARROW_TOP_LINE_ANGLE * ratio; } else { // rotate back to start doing a 360 rotation = ARROW_TOP_LINE_ANGLE + (1 - ratio) * ARROW_BOT_LINE_ANGLE; } // pivot center of canvas pivotX = width / 2; pivotY = height / 2; // shorten both ends stopX = width - sidePadding - resolveStrokeModifier(ratio); startX = sidePadding + dip3 * ratio; break; case BURGER_X: if (isMorphingForward()) { // rotate around rotation2 = -X_ROTATION_ANGLE * ratio; } else { // rotate directly rotation2 = X_ROTATION_ANGLE * ratio; } // rotate to required angle rotation = X_BOT_LINE_ANGLE * ratio; // pivot left corner of line pivotX = sidePadding + dip4; pivotY = height - topPadding - dip3; // lengthen one end stopX += dip3 * ratio; break; case ARROW_X: // rotate from ARROW angle to X angle rotation = ARROW_TOP_LINE_ANGLE + (360 + X_BOT_LINE_ANGLE - ARROW_TOP_LINE_ANGLE) * ratio; rotation2 = -X_ROTATION_ANGLE * ratio; // move pivot from ARROW pivot to X pivot pivotX = width / 2 + (sidePadding + dip4 - width / 2) * ratio; pivotY = height / 2 + (height / 2 - topPadding - dip3) * ratio; // lengthen both ends stopX -= resolveStrokeModifier(ratio); startX += dip3 * (1 - ratio); break; case ARROW_CHECK: // rotate from ARROW angle to CHECK angle rotation = ARROW_TOP_LINE_ANGLE + ratio * CHECK_BOTTOM_ANGLE; // move pivot from ARROW pivot to CHECK pivot pivotX = width / 2 - dip3 * ratio; pivotY = height / 2 - dip3 * ratio; // length stays same as ARROW stopX -= resolveStrokeModifier(1); startX += dip3; break; case BURGER_CHECK: // rotate from ARROW angle to CHECK angle rotation = ratio * (CHECK_BOTTOM_ANGLE + ARROW_TOP_LINE_ANGLE); // move pivot from ARROW pivot to CHECK pivot pivotX = width / 2 - dip3 * ratio; pivotY = height / 2 - dip3 * ratio; // length stays same as BURGER startX += dip3 * ratio; stopX -= resolveStrokeModifier(ratio); break; case X_CHECK: // rotate from X to CHECK angles rotation2 = -X_ROTATION_ANGLE * (1 - ratio); rotation = X_BOT_LINE_ANGLE + (CHECK_BOTTOM_ANGLE + ARROW_TOP_LINE_ANGLE - X_BOT_LINE_ANGLE) * ratio; // move pivot from X to CHECK pivotX = sidePadding + dip4 + (width / 2 - sidePadding - dip3 - dip4) * ratio; pivotY = height - topPadding - dip3 + (topPadding + height / 2 - height) * ratio; // shorten both ends startX += dip3 - dip3 * (1 - ratio); stopX -= resolveStrokeModifier(1 - ratio); break; } canvas.rotate(rotation, pivotX, pivotY); canvas.rotate(rotation2, pivotX2, pivotY2); canvas.drawLine(startX, startY, stopX, stopY, iconPaint); } private void drawGrid(Canvas canvas) { for (int i = 0; i < width + 1; i += dip1) { if (i % sidePadding == 0) gridPaint.setColor(Color.BLUE); canvas.drawLine(i, 0, i, height, gridPaint); if (i % sidePadding == 0) gridPaint.setColor(Color.GREEN); } for (int i = 0; i < height + 1; i += dip1) { if (i % gridOffset == 0) gridPaint.setColor(Color.BLUE); canvas.drawLine(0, i, width, i, gridPaint); if (i % gridOffset == 0) gridPaint.setColor(Color.GREEN); } } private boolean isMorphingForward() { return transformationValue <= TRANSFORMATION_MID; } private float resolveStrokeModifier(float ratio) { switch (stroke) { case REGULAR: if (animationState == AnimationState.ARROW_X || animationState == AnimationState.X_CHECK) { return dip3 - (dip6 * ratio); } return ratio * dip3; case THIN: if (animationState == AnimationState.ARROW_X || animationState == AnimationState.X_CHECK) { return dip3 + diph - (dip6 + diph) * ratio; } return ratio * (dip3 + diph); case EXTRA_THIN: if (animationState == AnimationState.ARROW_X || animationState == AnimationState.X_CHECK) { return dip4 - ((dip6 + dip1) * ratio); } return ratio * dip4; } return 0; } @Override public void setAlpha(int alpha) { iconPaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter cf) { iconPaint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSPARENT; } /* * Accessor methods */ public void setColor(int color) { iconPaint.setColor(color); circlePaint.setColor(color); invalidateSelf(); } protected void setDrawGrid(boolean drawGrid) { this.drawGrid = drawGrid; } public void setTransformationDuration(int duration) { transformation.setDuration(duration); } public void setPressedDuration(int duration) { pressedCircle.setDuration(duration); } public void setInterpolator(Interpolator interpolator) { transformation.setInterpolator(interpolator); } public void setNeverDrawTouch(boolean neverDrawTouch) { this.neverDrawTouch = neverDrawTouch; } public synchronized void setIconState(IconState iconState) { if (transformationRunning) { transformation.cancel(); transformationRunning = false; } if (currentIconState == iconState) return; switch (iconState) { case BURGER: animationState = AnimationState.BURGER_ARROW; transformationValue = TRANSFORMATION_START; break; case ARROW: animationState = AnimationState.BURGER_ARROW; transformationValue = TRANSFORMATION_MID; break; case X: animationState = AnimationState.BURGER_X; transformationValue = TRANSFORMATION_MID; break; case CHECK: animationState = AnimationState.BURGER_CHECK; transformationValue = TRANSFORMATION_MID; } currentIconState = iconState; invalidateSelf(); } public synchronized void animateIconState(IconState state, boolean drawTouch) { if (transformationRunning) { transformation.end(); pressedCircle.end(); } drawTouchCircle = drawTouch; animatingIconState = state; start(); } /* * Animations */ private Property<MaterialMenuDrawable, Float> transformationProperty = new Property<MaterialMenuDrawable, Float>(Float.class, "transformation") { @Override public Float get(MaterialMenuDrawable object) { return object.getTransformationValue(); } @Override public void set(MaterialMenuDrawable object, Float value) { object.setTransformationValue(value); } }; private Property<MaterialMenuDrawable, Float> pressedProgressProperty = new Property<MaterialMenuDrawable, Float>(Float.class, "pressedProgress") { @Override public Float get(MaterialMenuDrawable object) { return object.getPressedProgress(); } @Override public void set(MaterialMenuDrawable object, Float value) { object.setPressedProgress(value); } }; public Float getTransformationValue() { return transformationValue; } public void setTransformationValue(Float value) { this.transformationValue = value; invalidateSelf(); } public Float getPressedProgress() { return pressedProgressValue; } public void setPressedProgress(Float value) { this.pressedProgressValue = value; circlePaint.setAlpha((int) (DEFAULT_CIRCLE_ALPHA * (1 - value / (circleRadius * 1.22f)))); invalidateSelf(); } private void initAnimations(int transformDuration, int pressedDuration) { transformation = ObjectAnimator.ofFloat(this, transformationProperty, 0); transformation.setInterpolator(new DecelerateInterpolator(3)); transformation.setDuration(transformDuration); transformation.addListener(new SimpleAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { transformationRunning = false; setIconState(animatingIconState); } }); pressedCircle = ObjectAnimator.ofFloat(this, pressedProgressProperty, 0, 0); pressedCircle.setDuration(pressedDuration); pressedCircle.setInterpolator(new DecelerateInterpolator()); pressedCircle.addListener(new SimpleAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { pressedProgressValue = 0; } @Override public void onAnimationCancel(Animator animation) { pressedProgressValue = 0; } }); } private boolean resolveTransformation() { boolean isCurrentBurger = currentIconState == IconState.BURGER; boolean isCurrentArrow = currentIconState == IconState.ARROW; boolean isCurrentX = currentIconState == IconState.X; boolean isCurrentCheck = currentIconState == IconState.CHECK; boolean isAnimatingBurger = animatingIconState == IconState.BURGER; boolean isAnimatingArrow = animatingIconState == IconState.ARROW; boolean isAnimatingX = animatingIconState == IconState.X; boolean isAnimatingCheck = animatingIconState == IconState.CHECK; if ((isCurrentBurger && isAnimatingArrow) || (isCurrentArrow && isAnimatingBurger)) { animationState = AnimationState.BURGER_ARROW; return isCurrentBurger; } if ((isCurrentArrow && isAnimatingX) || (isCurrentX && isAnimatingArrow)) { animationState = AnimationState.ARROW_X; return isCurrentArrow; } if ((isCurrentBurger && isAnimatingX) || (isCurrentX && isAnimatingBurger)) { animationState = AnimationState.BURGER_X; return isCurrentBurger; } if ((isCurrentArrow && isAnimatingCheck) || (isCurrentCheck && isAnimatingArrow)) { animationState = AnimationState.ARROW_CHECK; return isCurrentArrow; } if ((isCurrentBurger && isAnimatingCheck) || (isCurrentCheck && isAnimatingBurger)) { animationState = AnimationState.BURGER_CHECK; return isCurrentBurger; } if ((isCurrentX && isAnimatingCheck) || (isCurrentCheck && isAnimatingX)) { animationState = AnimationState.X_CHECK; return isCurrentX; } throw new IllegalStateException( String.format("Animating from %s to %s is not supported", currentIconState, animatingIconState) ); } @Override public void start() { if (transformationRunning || animatingIconState == null || animatingIconState == currentIconState) return; transformationRunning = true; final boolean direction = resolveTransformation(); transformation.setFloatValues( direction ? TRANSFORMATION_START : TRANSFORMATION_MID, direction ? TRANSFORMATION_MID : TRANSFORMATION_END ); transformation.start(); if (pressedCircle.isRunning()) { pressedCircle.cancel(); } if (drawTouchCircle && !neverDrawTouch) { pressedCircle.setFloatValues(0, circleRadius * 1.22f); pressedCircle.start(); } invalidateSelf(); } @Override public void stop() { if (!isRunning()) return; if (transformation.isRunning()) { transformation.end(); } else { transformationRunning = false; invalidateSelf(); } } @Override public boolean isRunning() { return transformationRunning; } @Override public int getIntrinsicWidth() { return width; } @Override public int getIntrinsicHeight() { return height; } private class SimpleAnimatorListener implements Animator.AnimatorListener { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } } static float dpToPx(Resources resources, float dp) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.getDisplayMetrics()); } }
apache-2.0
eug48/hapi-fhir
hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/Practitioner.java
65552
package org.hl7.fhir.dstu3.model; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Generated on Mon, Apr 17, 2017 17:38-0400 for FHIR v3.0.1 import java.util.*; import org.hl7.fhir.utilities.Utilities; import org.hl7.fhir.dstu3.model.Enumerations.*; import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.model.api.annotation.SearchParamDefinition; import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.ChildOrder; import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.api.annotation.Block; import org.hl7.fhir.instance.model.api.*; import org.hl7.fhir.exceptions.FHIRException; /** * A person who is directly or indirectly involved in the provisioning of healthcare. */ @ResourceDef(name="Practitioner", profile="http://hl7.org/fhir/Profile/Practitioner") public class Practitioner extends DomainResource { @Block() public static class PractitionerQualificationComponent extends BackboneElement implements IBaseBackboneElement { /** * An identifier that applies to this person's qualification in this role. */ @Child(name = "identifier", type = {Identifier.class}, order=1, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="An identifier for this qualification for the practitioner", formalDefinition="An identifier that applies to this person's qualification in this role." ) protected List<Identifier> identifier; /** * Coded representation of the qualification. */ @Child(name = "code", type = {CodeableConcept.class}, order=2, min=1, max=1, modifier=false, summary=false) @Description(shortDefinition="Coded representation of the qualification", formalDefinition="Coded representation of the qualification." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/v2-2.7-0360") protected CodeableConcept code; /** * Period during which the qualification is valid. */ @Child(name = "period", type = {Period.class}, order=3, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Period during which the qualification is valid", formalDefinition="Period during which the qualification is valid." ) protected Period period; /** * Organization that regulates and issues the qualification. */ @Child(name = "issuer", type = {Organization.class}, order=4, min=0, max=1, modifier=false, summary=false) @Description(shortDefinition="Organization that regulates and issues the qualification", formalDefinition="Organization that regulates and issues the qualification." ) protected Reference issuer; /** * The actual object that is the target of the reference (Organization that regulates and issues the qualification.) */ protected Organization issuerTarget; private static final long serialVersionUID = 1095219071L; /** * Constructor */ public PractitionerQualificationComponent() { super(); } /** * Constructor */ public PractitionerQualificationComponent(CodeableConcept code) { super(); this.code = code; } /** * @return {@link #identifier} (An identifier that applies to this person's qualification in this role.) */ public List<Identifier> getIdentifier() { if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); return this.identifier; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public PractitionerQualificationComponent setIdentifier(List<Identifier> theIdentifier) { this.identifier = theIdentifier; return this; } public boolean hasIdentifier() { if (this.identifier == null) return false; for (Identifier item : this.identifier) if (!item.isEmpty()) return true; return false; } public Identifier addIdentifier() { //3 Identifier t = new Identifier(); if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return t; } public PractitionerQualificationComponent addIdentifier(Identifier t) { //3 if (t == null) return this; if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return this; } /** * @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist */ public Identifier getIdentifierFirstRep() { if (getIdentifier().isEmpty()) { addIdentifier(); } return getIdentifier().get(0); } /** * @return {@link #code} (Coded representation of the qualification.) */ public CodeableConcept getCode() { if (this.code == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PractitionerQualificationComponent.code"); else if (Configuration.doAutoCreate()) this.code = new CodeableConcept(); // cc return this.code; } public boolean hasCode() { return this.code != null && !this.code.isEmpty(); } /** * @param value {@link #code} (Coded representation of the qualification.) */ public PractitionerQualificationComponent setCode(CodeableConcept value) { this.code = value; return this; } /** * @return {@link #period} (Period during which the qualification is valid.) */ public Period getPeriod() { if (this.period == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PractitionerQualificationComponent.period"); else if (Configuration.doAutoCreate()) this.period = new Period(); // cc return this.period; } public boolean hasPeriod() { return this.period != null && !this.period.isEmpty(); } /** * @param value {@link #period} (Period during which the qualification is valid.) */ public PractitionerQualificationComponent setPeriod(Period value) { this.period = value; return this; } /** * @return {@link #issuer} (Organization that regulates and issues the qualification.) */ public Reference getIssuer() { if (this.issuer == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PractitionerQualificationComponent.issuer"); else if (Configuration.doAutoCreate()) this.issuer = new Reference(); // cc return this.issuer; } public boolean hasIssuer() { return this.issuer != null && !this.issuer.isEmpty(); } /** * @param value {@link #issuer} (Organization that regulates and issues the qualification.) */ public PractitionerQualificationComponent setIssuer(Reference value) { this.issuer = value; return this; } /** * @return {@link #issuer} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Organization that regulates and issues the qualification.) */ public Organization getIssuerTarget() { if (this.issuerTarget == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create PractitionerQualificationComponent.issuer"); else if (Configuration.doAutoCreate()) this.issuerTarget = new Organization(); // aa return this.issuerTarget; } /** * @param value {@link #issuer} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Organization that regulates and issues the qualification.) */ public PractitionerQualificationComponent setIssuerTarget(Organization value) { this.issuerTarget = value; return this; } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("identifier", "Identifier", "An identifier that applies to this person's qualification in this role.", 0, java.lang.Integer.MAX_VALUE, identifier)); childrenList.add(new Property("code", "CodeableConcept", "Coded representation of the qualification.", 0, java.lang.Integer.MAX_VALUE, code)); childrenList.add(new Property("period", "Period", "Period during which the qualification is valid.", 0, java.lang.Integer.MAX_VALUE, period)); childrenList.add(new Property("issuer", "Reference(Organization)", "Organization that regulates and issues the qualification.", 0, java.lang.Integer.MAX_VALUE, issuer)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier case 3059181: /*code*/ return this.code == null ? new Base[0] : new Base[] {this.code}; // CodeableConcept case -991726143: /*period*/ return this.period == null ? new Base[0] : new Base[] {this.period}; // Period case -1179159879: /*issuer*/ return this.issuer == null ? new Base[0] : new Base[] {this.issuer}; // Reference default: return super.getProperty(hash, name, checkValid); } } @Override public Base setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -1618432855: // identifier this.getIdentifier().add(castToIdentifier(value)); // Identifier return value; case 3059181: // code this.code = castToCodeableConcept(value); // CodeableConcept return value; case -991726143: // period this.period = castToPeriod(value); // Period return value; case -1179159879: // issuer this.issuer = castToReference(value); // Reference return value; default: return super.setProperty(hash, name, value); } } @Override public Base setProperty(String name, Base value) throws FHIRException { if (name.equals("identifier")) { this.getIdentifier().add(castToIdentifier(value)); } else if (name.equals("code")) { this.code = castToCodeableConcept(value); // CodeableConcept } else if (name.equals("period")) { this.period = castToPeriod(value); // Period } else if (name.equals("issuer")) { this.issuer = castToReference(value); // Reference } else return super.setProperty(name, value); return value; } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: return addIdentifier(); case 3059181: return getCode(); case -991726143: return getPeriod(); case -1179159879: return getIssuer(); default: return super.makeProperty(hash, name); } } @Override public String[] getTypesForProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return new String[] {"Identifier"}; case 3059181: /*code*/ return new String[] {"CodeableConcept"}; case -991726143: /*period*/ return new String[] {"Period"}; case -1179159879: /*issuer*/ return new String[] {"Reference"}; default: return super.getTypesForProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("identifier")) { return addIdentifier(); } else if (name.equals("code")) { this.code = new CodeableConcept(); return this.code; } else if (name.equals("period")) { this.period = new Period(); return this.period; } else if (name.equals("issuer")) { this.issuer = new Reference(); return this.issuer; } else return super.addChild(name); } public PractitionerQualificationComponent copy() { PractitionerQualificationComponent dst = new PractitionerQualificationComponent(); copyValues(dst); if (identifier != null) { dst.identifier = new ArrayList<Identifier>(); for (Identifier i : identifier) dst.identifier.add(i.copy()); }; dst.code = code == null ? null : code.copy(); dst.period = period == null ? null : period.copy(); dst.issuer = issuer == null ? null : issuer.copy(); return dst; } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof PractitionerQualificationComponent)) return false; PractitionerQualificationComponent o = (PractitionerQualificationComponent) other; return compareDeep(identifier, o.identifier, true) && compareDeep(code, o.code, true) && compareDeep(period, o.period, true) && compareDeep(issuer, o.issuer, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof PractitionerQualificationComponent)) return false; PractitionerQualificationComponent o = (PractitionerQualificationComponent) other; return true; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, code, period , issuer); } public String fhirType() { return "Practitioner.qualification"; } } /** * An identifier that applies to this person in this role. */ @Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="A identifier for the person as this agent", formalDefinition="An identifier that applies to this person in this role." ) protected List<Identifier> identifier; /** * Whether this practitioner's record is in active use. */ @Child(name = "active", type = {BooleanType.class}, order=1, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="Whether this practitioner's record is in active use", formalDefinition="Whether this practitioner's record is in active use." ) protected BooleanType active; /** * The name(s) associated with the practitioner. */ @Child(name = "name", type = {HumanName.class}, order=2, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="The name(s) associated with the practitioner", formalDefinition="The name(s) associated with the practitioner." ) protected List<HumanName> name; /** * A contact detail for the practitioner, e.g. a telephone number or an email address. */ @Child(name = "telecom", type = {ContactPoint.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="A contact detail for the practitioner (that apply to all roles)", formalDefinition="A contact detail for the practitioner, e.g. a telephone number or an email address." ) protected List<ContactPoint> telecom; /** * Address(es) of the practitioner that are not role specific (typically home address). Work addresses are not typically entered in this property as they are usually role dependent. */ @Child(name = "address", type = {Address.class}, order=4, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true) @Description(shortDefinition="Address(es) of the practitioner that are not role specific (typically home address)", formalDefinition="Address(es) of the practitioner that are not role specific (typically home address). \rWork addresses are not typically entered in this property as they are usually role dependent." ) protected List<Address> address; /** * Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. */ @Child(name = "gender", type = {CodeType.class}, order=5, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="male | female | other | unknown", formalDefinition="Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/administrative-gender") protected Enumeration<AdministrativeGender> gender; /** * The date of birth for the practitioner. */ @Child(name = "birthDate", type = {DateType.class}, order=6, min=0, max=1, modifier=false, summary=true) @Description(shortDefinition="The date on which the practitioner was born", formalDefinition="The date of birth for the practitioner." ) protected DateType birthDate; /** * Image of the person. */ @Child(name = "photo", type = {Attachment.class}, order=7, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Image of the person", formalDefinition="Image of the person." ) protected List<Attachment> photo; /** * Qualifications obtained by training and certification. */ @Child(name = "qualification", type = {}, order=8, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="Qualifications obtained by training and certification", formalDefinition="Qualifications obtained by training and certification." ) protected List<PractitionerQualificationComponent> qualification; /** * A language the practitioner is able to use in patient communication. */ @Child(name = "communication", type = {CodeableConcept.class}, order=9, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false) @Description(shortDefinition="A language the practitioner is able to use in patient communication", formalDefinition="A language the practitioner is able to use in patient communication." ) @ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/languages") protected List<CodeableConcept> communication; private static final long serialVersionUID = 2128349259L; /** * Constructor */ public Practitioner() { super(); } /** * @return {@link #identifier} (An identifier that applies to this person in this role.) */ public List<Identifier> getIdentifier() { if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); return this.identifier; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setIdentifier(List<Identifier> theIdentifier) { this.identifier = theIdentifier; return this; } public boolean hasIdentifier() { if (this.identifier == null) return false; for (Identifier item : this.identifier) if (!item.isEmpty()) return true; return false; } public Identifier addIdentifier() { //3 Identifier t = new Identifier(); if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return t; } public Practitioner addIdentifier(Identifier t) { //3 if (t == null) return this; if (this.identifier == null) this.identifier = new ArrayList<Identifier>(); this.identifier.add(t); return this; } /** * @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist */ public Identifier getIdentifierFirstRep() { if (getIdentifier().isEmpty()) { addIdentifier(); } return getIdentifier().get(0); } /** * @return {@link #active} (Whether this practitioner's record is in active use.). This is the underlying object with id, value and extensions. The accessor "getActive" gives direct access to the value */ public BooleanType getActiveElement() { if (this.active == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Practitioner.active"); else if (Configuration.doAutoCreate()) this.active = new BooleanType(); // bb return this.active; } public boolean hasActiveElement() { return this.active != null && !this.active.isEmpty(); } public boolean hasActive() { return this.active != null && !this.active.isEmpty(); } /** * @param value {@link #active} (Whether this practitioner's record is in active use.). This is the underlying object with id, value and extensions. The accessor "getActive" gives direct access to the value */ public Practitioner setActiveElement(BooleanType value) { this.active = value; return this; } /** * @return Whether this practitioner's record is in active use. */ public boolean getActive() { return this.active == null || this.active.isEmpty() ? false : this.active.getValue(); } /** * @param value Whether this practitioner's record is in active use. */ public Practitioner setActive(boolean value) { if (this.active == null) this.active = new BooleanType(); this.active.setValue(value); return this; } /** * @return {@link #name} (The name(s) associated with the practitioner.) */ public List<HumanName> getName() { if (this.name == null) this.name = new ArrayList<HumanName>(); return this.name; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setName(List<HumanName> theName) { this.name = theName; return this; } public boolean hasName() { if (this.name == null) return false; for (HumanName item : this.name) if (!item.isEmpty()) return true; return false; } public HumanName addName() { //3 HumanName t = new HumanName(); if (this.name == null) this.name = new ArrayList<HumanName>(); this.name.add(t); return t; } public Practitioner addName(HumanName t) { //3 if (t == null) return this; if (this.name == null) this.name = new ArrayList<HumanName>(); this.name.add(t); return this; } /** * @return The first repetition of repeating field {@link #name}, creating it if it does not already exist */ public HumanName getNameFirstRep() { if (getName().isEmpty()) { addName(); } return getName().get(0); } /** * @return {@link #telecom} (A contact detail for the practitioner, e.g. a telephone number or an email address.) */ public List<ContactPoint> getTelecom() { if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); return this.telecom; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setTelecom(List<ContactPoint> theTelecom) { this.telecom = theTelecom; return this; } public boolean hasTelecom() { if (this.telecom == null) return false; for (ContactPoint item : this.telecom) if (!item.isEmpty()) return true; return false; } public ContactPoint addTelecom() { //3 ContactPoint t = new ContactPoint(); if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); this.telecom.add(t); return t; } public Practitioner addTelecom(ContactPoint t) { //3 if (t == null) return this; if (this.telecom == null) this.telecom = new ArrayList<ContactPoint>(); this.telecom.add(t); return this; } /** * @return The first repetition of repeating field {@link #telecom}, creating it if it does not already exist */ public ContactPoint getTelecomFirstRep() { if (getTelecom().isEmpty()) { addTelecom(); } return getTelecom().get(0); } /** * @return {@link #address} (Address(es) of the practitioner that are not role specific (typically home address). Work addresses are not typically entered in this property as they are usually role dependent.) */ public List<Address> getAddress() { if (this.address == null) this.address = new ArrayList<Address>(); return this.address; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setAddress(List<Address> theAddress) { this.address = theAddress; return this; } public boolean hasAddress() { if (this.address == null) return false; for (Address item : this.address) if (!item.isEmpty()) return true; return false; } public Address addAddress() { //3 Address t = new Address(); if (this.address == null) this.address = new ArrayList<Address>(); this.address.add(t); return t; } public Practitioner addAddress(Address t) { //3 if (t == null) return this; if (this.address == null) this.address = new ArrayList<Address>(); this.address.add(t); return this; } /** * @return The first repetition of repeating field {@link #address}, creating it if it does not already exist */ public Address getAddressFirstRep() { if (getAddress().isEmpty()) { addAddress(); } return getAddress().get(0); } /** * @return {@link #gender} (Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value */ public Enumeration<AdministrativeGender> getGenderElement() { if (this.gender == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Practitioner.gender"); else if (Configuration.doAutoCreate()) this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory()); // bb return this.gender; } public boolean hasGenderElement() { return this.gender != null && !this.gender.isEmpty(); } public boolean hasGender() { return this.gender != null && !this.gender.isEmpty(); } /** * @param value {@link #gender} (Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value */ public Practitioner setGenderElement(Enumeration<AdministrativeGender> value) { this.gender = value; return this; } /** * @return Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. */ public AdministrativeGender getGender() { return this.gender == null ? null : this.gender.getValue(); } /** * @param value Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes. */ public Practitioner setGender(AdministrativeGender value) { if (value == null) this.gender = null; else { if (this.gender == null) this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory()); this.gender.setValue(value); } return this; } /** * @return {@link #birthDate} (The date of birth for the practitioner.). This is the underlying object with id, value and extensions. The accessor "getBirthDate" gives direct access to the value */ public DateType getBirthDateElement() { if (this.birthDate == null) if (Configuration.errorOnAutoCreate()) throw new Error("Attempt to auto-create Practitioner.birthDate"); else if (Configuration.doAutoCreate()) this.birthDate = new DateType(); // bb return this.birthDate; } public boolean hasBirthDateElement() { return this.birthDate != null && !this.birthDate.isEmpty(); } public boolean hasBirthDate() { return this.birthDate != null && !this.birthDate.isEmpty(); } /** * @param value {@link #birthDate} (The date of birth for the practitioner.). This is the underlying object with id, value and extensions. The accessor "getBirthDate" gives direct access to the value */ public Practitioner setBirthDateElement(DateType value) { this.birthDate = value; return this; } /** * @return The date of birth for the practitioner. */ public Date getBirthDate() { return this.birthDate == null ? null : this.birthDate.getValue(); } /** * @param value The date of birth for the practitioner. */ public Practitioner setBirthDate(Date value) { if (value == null) this.birthDate = null; else { if (this.birthDate == null) this.birthDate = new DateType(); this.birthDate.setValue(value); } return this; } /** * @return {@link #photo} (Image of the person.) */ public List<Attachment> getPhoto() { if (this.photo == null) this.photo = new ArrayList<Attachment>(); return this.photo; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setPhoto(List<Attachment> thePhoto) { this.photo = thePhoto; return this; } public boolean hasPhoto() { if (this.photo == null) return false; for (Attachment item : this.photo) if (!item.isEmpty()) return true; return false; } public Attachment addPhoto() { //3 Attachment t = new Attachment(); if (this.photo == null) this.photo = new ArrayList<Attachment>(); this.photo.add(t); return t; } public Practitioner addPhoto(Attachment t) { //3 if (t == null) return this; if (this.photo == null) this.photo = new ArrayList<Attachment>(); this.photo.add(t); return this; } /** * @return The first repetition of repeating field {@link #photo}, creating it if it does not already exist */ public Attachment getPhotoFirstRep() { if (getPhoto().isEmpty()) { addPhoto(); } return getPhoto().get(0); } /** * @return {@link #qualification} (Qualifications obtained by training and certification.) */ public List<PractitionerQualificationComponent> getQualification() { if (this.qualification == null) this.qualification = new ArrayList<PractitionerQualificationComponent>(); return this.qualification; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setQualification(List<PractitionerQualificationComponent> theQualification) { this.qualification = theQualification; return this; } public boolean hasQualification() { if (this.qualification == null) return false; for (PractitionerQualificationComponent item : this.qualification) if (!item.isEmpty()) return true; return false; } public PractitionerQualificationComponent addQualification() { //3 PractitionerQualificationComponent t = new PractitionerQualificationComponent(); if (this.qualification == null) this.qualification = new ArrayList<PractitionerQualificationComponent>(); this.qualification.add(t); return t; } public Practitioner addQualification(PractitionerQualificationComponent t) { //3 if (t == null) return this; if (this.qualification == null) this.qualification = new ArrayList<PractitionerQualificationComponent>(); this.qualification.add(t); return this; } /** * @return The first repetition of repeating field {@link #qualification}, creating it if it does not already exist */ public PractitionerQualificationComponent getQualificationFirstRep() { if (getQualification().isEmpty()) { addQualification(); } return getQualification().get(0); } /** * @return {@link #communication} (A language the practitioner is able to use in patient communication.) */ public List<CodeableConcept> getCommunication() { if (this.communication == null) this.communication = new ArrayList<CodeableConcept>(); return this.communication; } /** * @return Returns a reference to <code>this</code> for easy method chaining */ public Practitioner setCommunication(List<CodeableConcept> theCommunication) { this.communication = theCommunication; return this; } public boolean hasCommunication() { if (this.communication == null) return false; for (CodeableConcept item : this.communication) if (!item.isEmpty()) return true; return false; } public CodeableConcept addCommunication() { //3 CodeableConcept t = new CodeableConcept(); if (this.communication == null) this.communication = new ArrayList<CodeableConcept>(); this.communication.add(t); return t; } public Practitioner addCommunication(CodeableConcept t) { //3 if (t == null) return this; if (this.communication == null) this.communication = new ArrayList<CodeableConcept>(); this.communication.add(t); return this; } /** * @return The first repetition of repeating field {@link #communication}, creating it if it does not already exist */ public CodeableConcept getCommunicationFirstRep() { if (getCommunication().isEmpty()) { addCommunication(); } return getCommunication().get(0); } protected void listChildren(List<Property> childrenList) { super.listChildren(childrenList); childrenList.add(new Property("identifier", "Identifier", "An identifier that applies to this person in this role.", 0, java.lang.Integer.MAX_VALUE, identifier)); childrenList.add(new Property("active", "boolean", "Whether this practitioner's record is in active use.", 0, java.lang.Integer.MAX_VALUE, active)); childrenList.add(new Property("name", "HumanName", "The name(s) associated with the practitioner.", 0, java.lang.Integer.MAX_VALUE, name)); childrenList.add(new Property("telecom", "ContactPoint", "A contact detail for the practitioner, e.g. a telephone number or an email address.", 0, java.lang.Integer.MAX_VALUE, telecom)); childrenList.add(new Property("address", "Address", "Address(es) of the practitioner that are not role specific (typically home address). \rWork addresses are not typically entered in this property as they are usually role dependent.", 0, java.lang.Integer.MAX_VALUE, address)); childrenList.add(new Property("gender", "code", "Administrative Gender - the gender that the person is considered to have for administration and record keeping purposes.", 0, java.lang.Integer.MAX_VALUE, gender)); childrenList.add(new Property("birthDate", "date", "The date of birth for the practitioner.", 0, java.lang.Integer.MAX_VALUE, birthDate)); childrenList.add(new Property("photo", "Attachment", "Image of the person.", 0, java.lang.Integer.MAX_VALUE, photo)); childrenList.add(new Property("qualification", "", "Qualifications obtained by training and certification.", 0, java.lang.Integer.MAX_VALUE, qualification)); childrenList.add(new Property("communication", "CodeableConcept", "A language the practitioner is able to use in patient communication.", 0, java.lang.Integer.MAX_VALUE, communication)); } @Override public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier case -1422950650: /*active*/ return this.active == null ? new Base[0] : new Base[] {this.active}; // BooleanType case 3373707: /*name*/ return this.name == null ? new Base[0] : this.name.toArray(new Base[this.name.size()]); // HumanName case -1429363305: /*telecom*/ return this.telecom == null ? new Base[0] : this.telecom.toArray(new Base[this.telecom.size()]); // ContactPoint case -1147692044: /*address*/ return this.address == null ? new Base[0] : this.address.toArray(new Base[this.address.size()]); // Address case -1249512767: /*gender*/ return this.gender == null ? new Base[0] : new Base[] {this.gender}; // Enumeration<AdministrativeGender> case -1210031859: /*birthDate*/ return this.birthDate == null ? new Base[0] : new Base[] {this.birthDate}; // DateType case 106642994: /*photo*/ return this.photo == null ? new Base[0] : this.photo.toArray(new Base[this.photo.size()]); // Attachment case -631333393: /*qualification*/ return this.qualification == null ? new Base[0] : this.qualification.toArray(new Base[this.qualification.size()]); // PractitionerQualificationComponent case -1035284522: /*communication*/ return this.communication == null ? new Base[0] : this.communication.toArray(new Base[this.communication.size()]); // CodeableConcept default: return super.getProperty(hash, name, checkValid); } } @Override public Base setProperty(int hash, String name, Base value) throws FHIRException { switch (hash) { case -1618432855: // identifier this.getIdentifier().add(castToIdentifier(value)); // Identifier return value; case -1422950650: // active this.active = castToBoolean(value); // BooleanType return value; case 3373707: // name this.getName().add(castToHumanName(value)); // HumanName return value; case -1429363305: // telecom this.getTelecom().add(castToContactPoint(value)); // ContactPoint return value; case -1147692044: // address this.getAddress().add(castToAddress(value)); // Address return value; case -1249512767: // gender value = new AdministrativeGenderEnumFactory().fromType(castToCode(value)); this.gender = (Enumeration) value; // Enumeration<AdministrativeGender> return value; case -1210031859: // birthDate this.birthDate = castToDate(value); // DateType return value; case 106642994: // photo this.getPhoto().add(castToAttachment(value)); // Attachment return value; case -631333393: // qualification this.getQualification().add((PractitionerQualificationComponent) value); // PractitionerQualificationComponent return value; case -1035284522: // communication this.getCommunication().add(castToCodeableConcept(value)); // CodeableConcept return value; default: return super.setProperty(hash, name, value); } } @Override public Base setProperty(String name, Base value) throws FHIRException { if (name.equals("identifier")) { this.getIdentifier().add(castToIdentifier(value)); } else if (name.equals("active")) { this.active = castToBoolean(value); // BooleanType } else if (name.equals("name")) { this.getName().add(castToHumanName(value)); } else if (name.equals("telecom")) { this.getTelecom().add(castToContactPoint(value)); } else if (name.equals("address")) { this.getAddress().add(castToAddress(value)); } else if (name.equals("gender")) { value = new AdministrativeGenderEnumFactory().fromType(castToCode(value)); this.gender = (Enumeration) value; // Enumeration<AdministrativeGender> } else if (name.equals("birthDate")) { this.birthDate = castToDate(value); // DateType } else if (name.equals("photo")) { this.getPhoto().add(castToAttachment(value)); } else if (name.equals("qualification")) { this.getQualification().add((PractitionerQualificationComponent) value); } else if (name.equals("communication")) { this.getCommunication().add(castToCodeableConcept(value)); } else return super.setProperty(name, value); return value; } @Override public Base makeProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: return addIdentifier(); case -1422950650: return getActiveElement(); case 3373707: return addName(); case -1429363305: return addTelecom(); case -1147692044: return addAddress(); case -1249512767: return getGenderElement(); case -1210031859: return getBirthDateElement(); case 106642994: return addPhoto(); case -631333393: return addQualification(); case -1035284522: return addCommunication(); default: return super.makeProperty(hash, name); } } @Override public String[] getTypesForProperty(int hash, String name) throws FHIRException { switch (hash) { case -1618432855: /*identifier*/ return new String[] {"Identifier"}; case -1422950650: /*active*/ return new String[] {"boolean"}; case 3373707: /*name*/ return new String[] {"HumanName"}; case -1429363305: /*telecom*/ return new String[] {"ContactPoint"}; case -1147692044: /*address*/ return new String[] {"Address"}; case -1249512767: /*gender*/ return new String[] {"code"}; case -1210031859: /*birthDate*/ return new String[] {"date"}; case 106642994: /*photo*/ return new String[] {"Attachment"}; case -631333393: /*qualification*/ return new String[] {}; case -1035284522: /*communication*/ return new String[] {"CodeableConcept"}; default: return super.getTypesForProperty(hash, name); } } @Override public Base addChild(String name) throws FHIRException { if (name.equals("identifier")) { return addIdentifier(); } else if (name.equals("active")) { throw new FHIRException("Cannot call addChild on a primitive type Practitioner.active"); } else if (name.equals("name")) { return addName(); } else if (name.equals("telecom")) { return addTelecom(); } else if (name.equals("address")) { return addAddress(); } else if (name.equals("gender")) { throw new FHIRException("Cannot call addChild on a primitive type Practitioner.gender"); } else if (name.equals("birthDate")) { throw new FHIRException("Cannot call addChild on a primitive type Practitioner.birthDate"); } else if (name.equals("photo")) { return addPhoto(); } else if (name.equals("qualification")) { return addQualification(); } else if (name.equals("communication")) { return addCommunication(); } else return super.addChild(name); } public String fhirType() { return "Practitioner"; } public Practitioner copy() { Practitioner dst = new Practitioner(); copyValues(dst); if (identifier != null) { dst.identifier = new ArrayList<Identifier>(); for (Identifier i : identifier) dst.identifier.add(i.copy()); }; dst.active = active == null ? null : active.copy(); if (name != null) { dst.name = new ArrayList<HumanName>(); for (HumanName i : name) dst.name.add(i.copy()); }; if (telecom != null) { dst.telecom = new ArrayList<ContactPoint>(); for (ContactPoint i : telecom) dst.telecom.add(i.copy()); }; if (address != null) { dst.address = new ArrayList<Address>(); for (Address i : address) dst.address.add(i.copy()); }; dst.gender = gender == null ? null : gender.copy(); dst.birthDate = birthDate == null ? null : birthDate.copy(); if (photo != null) { dst.photo = new ArrayList<Attachment>(); for (Attachment i : photo) dst.photo.add(i.copy()); }; if (qualification != null) { dst.qualification = new ArrayList<PractitionerQualificationComponent>(); for (PractitionerQualificationComponent i : qualification) dst.qualification.add(i.copy()); }; if (communication != null) { dst.communication = new ArrayList<CodeableConcept>(); for (CodeableConcept i : communication) dst.communication.add(i.copy()); }; return dst; } protected Practitioner typedCopy() { return copy(); } @Override public boolean equalsDeep(Base other) { if (!super.equalsDeep(other)) return false; if (!(other instanceof Practitioner)) return false; Practitioner o = (Practitioner) other; return compareDeep(identifier, o.identifier, true) && compareDeep(active, o.active, true) && compareDeep(name, o.name, true) && compareDeep(telecom, o.telecom, true) && compareDeep(address, o.address, true) && compareDeep(gender, o.gender, true) && compareDeep(birthDate, o.birthDate, true) && compareDeep(photo, o.photo, true) && compareDeep(qualification, o.qualification, true) && compareDeep(communication, o.communication, true); } @Override public boolean equalsShallow(Base other) { if (!super.equalsShallow(other)) return false; if (!(other instanceof Practitioner)) return false; Practitioner o = (Practitioner) other; return compareValues(active, o.active, true) && compareValues(gender, o.gender, true) && compareValues(birthDate, o.birthDate, true) ; } public boolean isEmpty() { return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, active, name , telecom, address, gender, birthDate, photo, qualification, communication); } @Override public ResourceType getResourceType() { return ResourceType.Practitioner; } /** * Search parameter: <b>identifier</b> * <p> * Description: <b>A practitioner's Identifier</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.identifier</b><br> * </p> */ @SearchParamDefinition(name="identifier", path="Practitioner.identifier", description="A practitioner's Identifier", type="token" ) public static final String SP_IDENTIFIER = "identifier"; /** * <b>Fluent Client</b> search parameter constant for <b>identifier</b> * <p> * Description: <b>A practitioner's Identifier</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.identifier</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER); /** * Search parameter: <b>given</b> * <p> * Description: <b>A portion of the given name</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name.given</b><br> * </p> */ @SearchParamDefinition(name="given", path="Practitioner.name.given", description="A portion of the given name", type="string" ) public static final String SP_GIVEN = "given"; /** * <b>Fluent Client</b> search parameter constant for <b>given</b> * <p> * Description: <b>A portion of the given name</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name.given</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam GIVEN = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_GIVEN); /** * Search parameter: <b>address</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address</b><br> * </p> */ @SearchParamDefinition(name="address", path="Practitioner.address", description="A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text", type="string" ) public static final String SP_ADDRESS = "address"; /** * <b>Fluent Client</b> search parameter constant for <b>address</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS); /** * Search parameter: <b>address-state</b> * <p> * Description: <b>A state specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.state</b><br> * </p> */ @SearchParamDefinition(name="address-state", path="Practitioner.address.state", description="A state specified in an address", type="string" ) public static final String SP_ADDRESS_STATE = "address-state"; /** * <b>Fluent Client</b> search parameter constant for <b>address-state</b> * <p> * Description: <b>A state specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.state</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_STATE = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_STATE); /** * Search parameter: <b>gender</b> * <p> * Description: <b>Gender of the practitioner</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.gender</b><br> * </p> */ @SearchParamDefinition(name="gender", path="Practitioner.gender", description="Gender of the practitioner", type="token" ) public static final String SP_GENDER = "gender"; /** * <b>Fluent Client</b> search parameter constant for <b>gender</b> * <p> * Description: <b>Gender of the practitioner</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.gender</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam GENDER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_GENDER); /** * Search parameter: <b>active</b> * <p> * Description: <b>Whether the practitioner record is active</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.active</b><br> * </p> */ @SearchParamDefinition(name="active", path="Practitioner.active", description="Whether the practitioner record is active", type="token" ) public static final String SP_ACTIVE = "active"; /** * <b>Fluent Client</b> search parameter constant for <b>active</b> * <p> * Description: <b>Whether the practitioner record is active</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.active</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam ACTIVE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ACTIVE); /** * Search parameter: <b>address-postalcode</b> * <p> * Description: <b>A postalCode specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.postalCode</b><br> * </p> */ @SearchParamDefinition(name="address-postalcode", path="Practitioner.address.postalCode", description="A postalCode specified in an address", type="string" ) public static final String SP_ADDRESS_POSTALCODE = "address-postalcode"; /** * <b>Fluent Client</b> search parameter constant for <b>address-postalcode</b> * <p> * Description: <b>A postalCode specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.postalCode</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_POSTALCODE = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_POSTALCODE); /** * Search parameter: <b>address-country</b> * <p> * Description: <b>A country specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.country</b><br> * </p> */ @SearchParamDefinition(name="address-country", path="Practitioner.address.country", description="A country specified in an address", type="string" ) public static final String SP_ADDRESS_COUNTRY = "address-country"; /** * <b>Fluent Client</b> search parameter constant for <b>address-country</b> * <p> * Description: <b>A country specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.country</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_COUNTRY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_COUNTRY); /** * Search parameter: <b>phonetic</b> * <p> * Description: <b>A portion of either family or given name using some kind of phonetic matching algorithm</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name</b><br> * </p> */ @SearchParamDefinition(name="phonetic", path="Practitioner.name", description="A portion of either family or given name using some kind of phonetic matching algorithm", type="string" ) public static final String SP_PHONETIC = "phonetic"; /** * <b>Fluent Client</b> search parameter constant for <b>phonetic</b> * <p> * Description: <b>A portion of either family or given name using some kind of phonetic matching algorithm</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam PHONETIC = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_PHONETIC); /** * Search parameter: <b>phone</b> * <p> * Description: <b>A value in a phone contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom(system=phone)</b><br> * </p> */ @SearchParamDefinition(name="phone", path="Practitioner.telecom.where(system='phone')", description="A value in a phone contact", type="token" ) public static final String SP_PHONE = "phone"; /** * <b>Fluent Client</b> search parameter constant for <b>phone</b> * <p> * Description: <b>A value in a phone contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom(system=phone)</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam PHONE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_PHONE); /** * Search parameter: <b>name</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name</b><br> * </p> */ @SearchParamDefinition(name="name", path="Practitioner.name", description="A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text", type="string" ) public static final String SP_NAME = "name"; /** * <b>Fluent Client</b> search parameter constant for <b>name</b> * <p> * Description: <b>A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam NAME = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_NAME); /** * Search parameter: <b>address-use</b> * <p> * Description: <b>A use code specified in an address</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.address.use</b><br> * </p> */ @SearchParamDefinition(name="address-use", path="Practitioner.address.use", description="A use code specified in an address", type="token" ) public static final String SP_ADDRESS_USE = "address-use"; /** * <b>Fluent Client</b> search parameter constant for <b>address-use</b> * <p> * Description: <b>A use code specified in an address</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.address.use</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam ADDRESS_USE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ADDRESS_USE); /** * Search parameter: <b>telecom</b> * <p> * Description: <b>The value in any kind of contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom</b><br> * </p> */ @SearchParamDefinition(name="telecom", path="Practitioner.telecom", description="The value in any kind of contact", type="token" ) public static final String SP_TELECOM = "telecom"; /** * <b>Fluent Client</b> search parameter constant for <b>telecom</b> * <p> * Description: <b>The value in any kind of contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam TELECOM = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_TELECOM); /** * Search parameter: <b>family</b> * <p> * Description: <b>A portion of the family name</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name.family</b><br> * </p> */ @SearchParamDefinition(name="family", path="Practitioner.name.family", description="A portion of the family name", type="string" ) public static final String SP_FAMILY = "family"; /** * <b>Fluent Client</b> search parameter constant for <b>family</b> * <p> * Description: <b>A portion of the family name</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.name.family</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam FAMILY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_FAMILY); /** * Search parameter: <b>address-city</b> * <p> * Description: <b>A city specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.city</b><br> * </p> */ @SearchParamDefinition(name="address-city", path="Practitioner.address.city", description="A city specified in an address", type="string" ) public static final String SP_ADDRESS_CITY = "address-city"; /** * <b>Fluent Client</b> search parameter constant for <b>address-city</b> * <p> * Description: <b>A city specified in an address</b><br> * Type: <b>string</b><br> * Path: <b>Practitioner.address.city</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_CITY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_CITY); /** * Search parameter: <b>communication</b> * <p> * Description: <b>One of the languages that the practitioner can communicate with</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.communication</b><br> * </p> */ @SearchParamDefinition(name="communication", path="Practitioner.communication", description="One of the languages that the practitioner can communicate with", type="token" ) public static final String SP_COMMUNICATION = "communication"; /** * <b>Fluent Client</b> search parameter constant for <b>communication</b> * <p> * Description: <b>One of the languages that the practitioner can communicate with</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.communication</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam COMMUNICATION = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_COMMUNICATION); /** * Search parameter: <b>email</b> * <p> * Description: <b>A value in an email contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom(system=email)</b><br> * </p> */ @SearchParamDefinition(name="email", path="Practitioner.telecom.where(system='email')", description="A value in an email contact", type="token" ) public static final String SP_EMAIL = "email"; /** * <b>Fluent Client</b> search parameter constant for <b>email</b> * <p> * Description: <b>A value in an email contact</b><br> * Type: <b>token</b><br> * Path: <b>Practitioner.telecom(system=email)</b><br> * </p> */ public static final ca.uhn.fhir.rest.gclient.TokenClientParam EMAIL = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_EMAIL); }
apache-2.0
raphaelning/resteasy-client-android
jaxrs/resteasy-client/src/main/java/org/jboss/resteasy/client/jaxrs/ProxyConfig.java
646
package org.jboss.resteasy.client.jaxrs; import javax.ws.rs.core.MediaType; public class ProxyConfig { private final ClassLoader loader; private final MediaType defaultConsumes; private final MediaType defaultProduces; public ProxyConfig(ClassLoader loader, MediaType defaultConsumes, MediaType defaultProduces) { super(); this.loader = loader; this.defaultConsumes = defaultConsumes; this.defaultProduces = defaultProduces; } public ClassLoader getLoader() { return loader; } public MediaType getDefaultConsumes() { return defaultConsumes; } public MediaType getDefaultProduces() { return defaultProduces; } }
apache-2.0
CyberEagle/AndroidLibrary
library/src/main/java/br/com/cybereagle/androidlibrary/util/Utils.java
1060
/* * Copyright 2013 Cyber Eagle * * 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 br.com.cybereagle.androidlibrary.util; import android.app.Activity; import android.view.inputmethod.InputMethodManager; public class Utils { public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); } }
apache-2.0
saulbein/web3j
core/src/main/java/org/web3j/abi/datatypes/generated/Fixed112x72.java
587
package org.web3j.abi.datatypes.generated; import java.math.BigInteger; import org.web3j.abi.datatypes.Fixed; /** * <p>Auto generated code.<br> * <strong>Do not modifiy!</strong><br> * Please use {@link org.web3j.codegen.AbiTypesGenerator} to update.</p> */ public class Fixed112x72 extends Fixed { public static final Fixed112x72 DEFAULT = new Fixed112x72(BigInteger.ZERO); public Fixed112x72(BigInteger value) { super(112, 72, value); } public Fixed112x72(int mBitSize, int nBitSize, BigInteger m, BigInteger n) { super(112, 72, m, n); } }
apache-2.0
krux/java-stdlib
krux-stdlib-monitoring/src/main/java/com/krux/stdlib/status/StatusBean.java
2094
package com.krux.stdlib.status; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; public class StatusBean { private final AppState state; private final String message; private final List<String> warnings = new ArrayList<>(); private final List<String> errors = new ArrayList<>(); public StatusBean(AppState appStatus, String message) { this.state = appStatus; this.message = message; } @Override public int hashCode() { // only the status and message contribute to this objects "identity" return Objects.hash(state, message); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || !getClass().equals(obj.getClass())) { return false; } StatusBean that = (StatusBean) obj; return Objects.equals(this.state, that.state) && Objects.equals(this.message, that.message); } protected ToStringBuilder toStringBuilder() { return new ToStringBuilder(this, ToStringStyle.DEFAULT_STYLE) .append("state", state) .append("message", message) .append("warnings", warnings) .append("errors", errors); } @Override public String toString() { return toStringBuilder().build(); } public AppState getAppStatus() { return state; } public String getMessage() { return message; } public List<String> getWarnings() { return Collections.unmodifiableList(warnings); } public List<String> getErrors() { return Collections.unmodifiableList(errors); } public StatusBean addWarning(String warning) { warnings.add(warning); return this; } public StatusBean addError(String error) { errors.add(error); return this; } }
apache-2.0
mmm2a/GridApp
src/com/morgan/grid/server/auth/AuthConstantsModule.java
869
package com.morgan.grid.server.auth; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.google.inject.Provides; import com.morgan.grid.server.common.constants.AbstractConstantsModule; import com.morgan.grid.server.common.constants.BindConstant; import com.morgan.grid.shared.common.constants.DictionaryConstant; /** * GUICE module for configuring constants related to the auth application. * * @author mark@mark-morgan.net (Mark Morgan) */ final class AuthConstantsModule extends AbstractConstantsModule { @BindConstant(DictionaryConstant.AUTH_TEST_CONSTANT) @Provides protected String provideAuthTestConstant(HttpServletRequest request, HttpServletResponse response, HttpSession session) { return "Auth application for " + request.getRemoteAddr(); } }
apache-2.0
hortonworks/cloudbreak
integration-test/src/main/java/com/sequenceiq/it/cloudbreak/log/Log.java
5386
package com.sequenceiq.it.cloudbreak.log; import static java.lang.String.format; import java.io.IOException; import java.io.StringWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.ITestResult; import org.testng.Reporter; import com.fasterxml.jackson.databind.ObjectMapper; import com.sequenceiq.it.cloudbreak.dto.CloudbreakTestDto; public class Log<T extends CloudbreakTestDto> { public static final String TEST_CONTEXT_REPORTER = "testContextReporter"; public static final String ALTERNATE_LOG = "alternateLog"; private static final Logger LOGGER = LoggerFactory.getLogger(Log.class); private Log() { } public static void whenJson(Logger logger, String message, Object jsonObject) throws IOException { ObjectMapper mapper = new ObjectMapper(); StringWriter writer = new StringWriter(); mapper.writeValue(writer, jsonObject); log(logger, "When", message, writer.toString()); } public static void whenJson(String message, Object jsonObject) throws IOException { whenJson(null, message, jsonObject); } public static void log(String message, Object... args) { log(null, message, args); } public static void log(Logger logger, String message, Object... args) { String format = String.format(message, args); log(format); if (logger != null) { logger.info(format); } } public static void error(Logger logger, String message, Object... args) { String format = String.format(message, args); log(format); if (logger != null) { logger.error(format); } } private static void log(Logger logger, String step, String message) { log(logger, step, message, null); } private static void log(Logger logger, String step, String message, String json) { TestContextReporter testContextReporter = getReporter(); if (testContextReporter == null) { log(logger, step + " " + message); } else { getReporter().addStep(step, message, json); } publishReport(getReporter()); } public static void given(Logger logger, String message) { log(logger, "Given", message); } public static void as(Logger logger, String message) { log(logger, "As", message); } public static void when(Logger logger, String message) { log(logger, "When", message); } public static void whenException(Logger logger, String message) { log(logger, "WhenException", message); } public static void then(Logger logger, String message) { log(logger, "Then", message); } public static void expect(Logger logger, String message) { log(logger, "Expect", message); } public static void await(Logger logger, String message) { log(logger, "Await", message); } public static void validateError(Logger logger, String message) { log(logger, "Validate", message); } public static void log(String message) { Reporter.log(message); } public static void log(ITestResult testResult) { if (testResult != null) { Throwable testResultException = testResult.getThrowable(); String methodName = testResult.getName(); int status = testResult.getStatus(); if (testResultException != null) { try { String message = testResultException.getCause() != null ? testResultException.getCause().getMessage() : testResultException.getMessage(); String testFailureType = testResultException.getCause() != null ? testResultException.getCause().getClass().getName() : testResultException.getClass().getName(); if (message == null || message.isEmpty()) { log(format(" Test Case: %s have been failed with empty test result! ", methodName)); } else { LOGGER.info("Failed test results are: Test Case: {} | Status: {} | Failure Type: {} | Message: {}", methodName, status, testFailureType, message); log(message); } } catch (Exception e) { log(format(" Test Case: %s got Unexpected Exception: %s ", methodName, e.getMessage())); } } } else { LOGGER.error("Test result is NULL!"); } } private static TestContextReporter getReporter() { ITestResult res = Reporter.getCurrentTestResult(); if (res == null) { return null; } TestContextReporter reporter = (TestContextReporter) res.getAttribute(TEST_CONTEXT_REPORTER); if (reporter == null) { reporter = new TestContextReporter(); res.setAttribute(TEST_CONTEXT_REPORTER, reporter); } return reporter; } private static void publishReport(TestContextReporter testContextReporter) { ITestResult res = Reporter.getCurrentTestResult(); if (res != null) { res.setAttribute(ALTERNATE_LOG, testContextReporter.print()); } } }
apache-2.0
hstoenescu/PracticalTest02
PracticalTest2/app/src/androidTest/java/practicaltest02/eim/systems/cs/pub/ro/practicaltest2/ExampleInstrumentedTest.java
808
package practicaltest02.eim.systems.cs.pub.ro.practicaltest2; 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.*; /** * Instrumentation 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() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("practicaltest02.eim.systems.cs.pub.ro.practicaltest2", appContext.getPackageName()); } }
apache-2.0
nkasvosve/beyondj
beyondj-admin/beyondj-web-console/src/main/java/com/lenox/beyondj/action/site/FAQActionBean.java
854
package com.lenox.beyondj.action.site; import com.lenox.beyondj.action.BaseActionBean; import com.lenox.beyondj.action.SkipAuthentication; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.action.UrlBinding; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SkipAuthentication @UrlBinding("/web/faqs") public class FAQActionBean extends BaseActionBean { @DefaultHandler public Resolution view() { return new ForwardResolution(JSP); } private static final String JSP = "/WEB-INF/jsp/site/faqs.jsp"; @Override protected Logger getLogger(){ return LOG; } private Logger LOG = LoggerFactory.getLogger(FAQActionBean.class); }
apache-2.0
mgrand/bigchaindb-java-driver
bigchaindbdriver/src/test/java/com/hcl/bigchaindbDriver/BigchainDBTest.java
2946
package com.hcl.bigchaindbDriver; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.Test; import java.awt.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Unit tests for {@link BigchainDB}. * * Created by mark.grand on 1/12/2017. */ public class BigchainDBTest { private final static String HOST_ADDRESS = "example.com"; private final static int PORT_NUMBER = 34567; private final static ObjectMapper objectMapper = new ObjectMapper(); @Test public void createInstance() throws Exception { final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER); assertEquals(HOST_ADDRESS, bigchainDB.getHostAddress()); assertEquals(PORT_NUMBER, bigchainDB.getPort()); assertNotNull(bigchainDB.getObjectMapper()); } @Test public void createInstance1() throws Exception { final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER, objectMapper); assertEquals(HOST_ADDRESS, bigchainDB.getHostAddress()); assertEquals(PORT_NUMBER, bigchainDB.getPort()); assertEquals(objectMapper, bigchainDB.getObjectMapper()); } @Test public void createAssetTransaction() throws Throwable { final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER); final UnsignedCreateTransaction transaction = bigchainDB.createAssetTransaction(new Point(1, 0)); assertNotNull(transaction); final JsonNode json = getAssetData(transaction); assertEquals(1, json.get("x").asInt()); assertEquals(0, json.get("y").asInt()); } private JsonNode getAssetData(UnsignedCreateTransaction transaction) { //noinspection RedundantTypeArguments return transaction.getAssetData().<RuntimeException>orElseThrow(() -> {throw new RuntimeException();}); } @Test public void createAssetTransaction1() throws Exception { final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER); final ObjectNode json = objectMapper.createObjectNode(); json.set("foo", JsonNodeFactory.instance.textNode("bar")); final UnsignedCreateTransaction transaction = bigchainDB.createAssetTransaction(json); assertNotNull(transaction); assertEquals(json, getAssetData(transaction)); } @Test public void transferAssetTransaction() throws Exception { final BigchainDB bigchainDB = BigchainDB.createInstance(HOST_ADDRESS, PORT_NUMBER); final UnsignedTransferTransaction transaction = bigchainDB.transferAssetTransaction(); assertNotNull(transaction); //assertEquals(ASSET_ID, transaction.getAssetId()); } }
apache-2.0