repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
PkayJava/pluggable | framework/src/main/java/com/angkorteam/pluggable/framework/panel/menu/ItemHeadPanel.java | 678 | package com.angkorteam.pluggable.framework.panel.menu;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import com.angkorteam.pluggable.framework.core.Menu;
/**
* @author Socheat KHAUV
*/
public class ItemHeadPanel extends Panel {
private Menu menu;
public ItemHeadPanel(String id, Menu menu) {
super(id);
this.menu = menu;
}
@Override
protected void onInitialize() {
super.onInitialize();
Label label = new Label("label", menu.getLabel());
add(label);
}
/**
*
*/
private static final long serialVersionUID = -7680231749431069387L;
}
| apache-2.0 |
jmad/aloha | src/java/cern/accsoft/steering/aloha/gui/panels/fit/FitFrame.java | 5234 | /**
*
*/
package cern.accsoft.steering.aloha.gui.panels.fit;
import cern.accsoft.gui.beans.MultiSplitLayout;
import cern.accsoft.gui.beans.MultiSplitPane;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
/**
* This is the panel to configure and start fits
*
* @author kfuchsbe
*
*/
public class FitFrame extends JFrame {
/** the panel, which displays the variation-parameters */
private JPanel variationParameterPanel;
/** the panel, which displays the fixed parameters */
private JPanel fixedParameterPanel;
/** the panel to configure the calculator */
private JPanel calculatorConfigPanel;
/** the info-panel of the calculator */
private JPanel calculatorInfoPanel;
/** the panel to configure the contributors to the sensitivity matrix */
private JPanel sensitivityMatrixContributorConfigsPanel;
/** the panel which contains the buttons to start the fits */
private JPanel calcButtonsPanel;
/** the panel to operate model details */
private JPanel modelOperationPanel;
private JPanel fitDataViewerPanel;
public void init() {
initComponents();
}
private void initComponents() {
setLayout(new BorderLayout());
setSize(1024, 768);
setTitle("Aloha Fitting");
/*
* The multisplit layout and the multisplit-pane, which contains all
* others.
*/
String layoutDef = "(COLUMN (ROW weight=0.5 "
+ "(LEAF name=top.left weight=0.2) (LEAF name=top.center weight=0.4) (LEAF name=top.right weight=0.4)) "
+ "(LEAF name=bottom weight=0.5))";
MultiSplitLayout.Node layoutModel = MultiSplitLayout
.parseModel(layoutDef);
MultiSplitPane multiSplitPane = new MultiSplitPane();
multiSplitPane.getMultiSplitLayout().setModel(layoutModel);
multiSplitPane.getMultiSplitLayout().setDividerSize(5);
add(multiSplitPane, BorderLayout.CENTER);
JPanel calcButtonsPanel = getCalcButtonsPanel();
calcButtonsPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
multiSplitPane.add(calcButtonsPanel, "top.left");
/* Calculator Panels */
JTabbedPane tabbedPaneCalculator = new JTabbedPane();
tabbedPaneCalculator.setBorder(new BevelBorder(BevelBorder.LOWERED));
multiSplitPane.add(tabbedPaneCalculator, "top.center");
tabbedPaneCalculator.addTab("Configure", getCalculatorConfigPanel());
tabbedPaneCalculator.addTab("Contributors",
getSensitivityMatrixContributorConfigsPanel());
tabbedPaneCalculator.addTab("varied parameters",
getVariationParameterPanel());
tabbedPaneCalculator.addTab("fixed parameters",
getFixedParameterPanel());
JPanel modelOperationsPanel = getModelOperationPanel();
modelOperationsPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
multiSplitPane.add(modelOperationsPanel, "top.right");
if (getFitDataViewerPanel() != null) {
getFitDataViewerPanel().setBorder(
new BevelBorder(BevelBorder.LOWERED));
multiSplitPane.add(getFitDataViewerPanel(), "bottom");
}
setDefaultCloseOperation(HIDE_ON_CLOSE);
}
public JPanel getVariationParameterPanel() {
return variationParameterPanel;
}
public void setVariationParameterPanel(JPanel variationParameterPanel) {
this.variationParameterPanel = variationParameterPanel;
}
public JPanel getCalculatorConfigPanel() {
return calculatorConfigPanel;
}
public void setCalculatorConfigPanel(JPanel calculatorConfigPanel) {
this.calculatorConfigPanel = calculatorConfigPanel;
}
public JPanel getCalculatorInfoPanel() {
return calculatorInfoPanel;
}
public void setCalculatorInfoPanel(JPanel calculatorInfoPanel) {
this.calculatorInfoPanel = calculatorInfoPanel;
}
public JPanel getSensitivityMatrixContributorConfigsPanel() {
return sensitivityMatrixContributorConfigsPanel;
}
public void setSensitivityMatrixContributorConfigsPanel(
JPanel sensitivityMatrixContributorConfigsPanel) {
this.sensitivityMatrixContributorConfigsPanel = sensitivityMatrixContributorConfigsPanel;
}
public void setCalcButtonsPanel(JPanel calcButtonsPanel) {
this.calcButtonsPanel = calcButtonsPanel;
}
public JPanel getCalcButtonsPanel() {
return calcButtonsPanel;
}
public void setModelOperationPanel(JPanel modelOperationPanel) {
this.modelOperationPanel = modelOperationPanel;
}
public JPanel getModelOperationPanel() {
return modelOperationPanel;
}
public void setFixedParameterPanel(JPanel fixedParameterPanel) {
this.fixedParameterPanel = fixedParameterPanel;
}
public JPanel getFixedParameterPanel() {
return fixedParameterPanel;
}
public void setFitDataViewerPanel(JPanel fitDataViewerPanel) {
this.fitDataViewerPanel = fitDataViewerPanel;
}
private JPanel getFitDataViewerPanel() {
return fitDataViewerPanel;
}
}
| apache-2.0 |
GamersCave/ACRA-Android-PHP-backend | app/src/androidTest/java/com/gamerscave/acrabackend/ExampleInstrumentedTest.java | 756 | package com.gamerscave.acrabackend;
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("com.gamerscave.acrabackend", appContext.getPackageName());
}
}
| apache-2.0 |
fastnsilver/vaadin4spring | samples/mvp-sample/src/main/java/org/vaadin/spring/samples/mvp/ui/component/listener/ParticipantSelectedListener.java | 1489 | /*
* Copyright 2015 The original 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.vaadin.spring.samples.mvp.ui.component.listener;
import javax.inject.Inject;
import org.vaadin.spring.annotation.VaadinComponent;
import org.vaadin.spring.annotation.VaadinUIScope;
import org.vaadin.spring.events.EventBus;
import org.vaadin.spring.events.EventScope;
import org.vaadin.spring.events.annotation.EventBusScope;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
@VaadinUIScope
@VaadinComponent
public class ParticipantSelectedListener implements ValueChangeListener {
private static final long serialVersionUID = 331391425040065709L;
@Inject
@EventBusScope(EventScope.APPLICATION)
private EventBus eventBus;
@Override
public void valueChange(ValueChangeEvent event) {
// publish AssetOwnerDailyId
eventBus.publish(this, event.getProperty().getValue());
}
}
| apache-2.0 |
Idilia/idilia-java-sdk | src/main/java/com/idilia/services/kb/SenseCardResponse.java | 473 | package com.idilia.services.kb;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.idilia.services.base.ResponseBase;
/**
* Response for a SenseCardRequest.
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SenseCardResponse extends ResponseBase {
public String card;
/**
* Returns the HTML string computed by the KB server for a sense card.
* @return HTML for the card
*/
public String getCard() {
return card;
}
}
| apache-2.0 |
trevor-e/TerminatorExample | src/com/trevore/Main.java | 611 | package com.trevore;
import com.trevore.skynet.Skynet;
import com.trevore.terminators.*;
/**
* Created by trevor on 2/19/15.
*/
public class Main {
public static void main(String[] args) {
Terminator terminator1 = TerminatorFactory.getEvilTerminator();
Terminator terminator2 = TerminatorFactory.getEvilTerminator();
Terminator terminator3 = TerminatorFactory.getEvilTerminator();
Skynet skynet = new Skynet();
skynet.addObserver(terminator1);
skynet.addObserver(terminator2);
skynet.addObserver(terminator3);
skynet.turnEvil();
}
}
| apache-2.0 |
vanilladb/vanillacore | src/main/java/org/vanilladb/core/query/algebra/multibuffer/MultiBufferProductScan.java | 3819 | /*******************************************************************************
* Copyright 2016, 2017 vanilladb.org contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package org.vanilladb.core.query.algebra.multibuffer;
import org.vanilladb.core.query.algebra.ProductScan;
import org.vanilladb.core.query.algebra.Scan;
import org.vanilladb.core.sql.Constant;
import org.vanilladb.core.storage.metadata.TableInfo;
import org.vanilladb.core.storage.tx.Transaction;
/**
* The Scan class for the muti-buffer version of the <em>product</em> operator.
*/
public class MultiBufferProductScan implements Scan {
private Scan lhsScan, rhsScan = null, prodScan;
private TableInfo rhsTi;
private Transaction tx;
private int rhsChunkSize;
private long nextBlkNum, rhsFileSize;
/**
* Creates the scan class for the product of the LHS scan and a table.
*
* @param lhsScan
* the LHS scan
* @param rhsTi
* the metadata for the RHS table
* @param tx
* the current transaction
*/
public MultiBufferProductScan(Scan lhsScan, TableInfo rhsTi, Transaction tx) {
this.lhsScan = lhsScan;
this.rhsTi = rhsTi;
this.tx = tx;
rhsFileSize = rhsTi.open(tx, true).fileSize();
rhsChunkSize = BufferNeeds.bestFactor(rhsFileSize, tx);
}
/**
* Positions the scan before the first record. That is, the LHS scan is
* positioned at its first record, and the RHS scan is positioned before the
* first record of the first chunk.
*
* @see Scan#beforeFirst()
*/
@Override
public void beforeFirst() {
nextBlkNum = 0;
useNextChunk();
}
/**
* Moves to the next record in the current scan. If there are no more
* records in the current chunk, then move to the next LHS record and the
* beginning of that chunk. If there are no more LHS records, then move to
* the next chunk and begin again.
*
* @see Scan#next()
*/
@Override
public boolean next() {
if (prodScan == null)
return false;
while (!prodScan.next())
if (!useNextChunk())
return false;
return true;
}
/**
* Closes the current scans.
*
* @see Scan#close()
*/
@Override
public void close() {
if (prodScan != null)
prodScan.close();
}
/**
* Returns the value of the specified field. The value is obtained from
* whichever scan contains the field.
*
* @see Scan#getVal(java.lang.String)
*/
@Override
public Constant getVal(String fldname) {
return prodScan.getVal(fldname);
}
/**
* Returns true if the specified field is in either of the underlying scans.
*
* @see Scan#hasField(java.lang.String)
*/
@Override
public boolean hasField(String fldName) {
return prodScan.hasField(fldName);
}
private boolean useNextChunk() {
if (rhsScan != null)
rhsScan.close();
if (nextBlkNum >= rhsFileSize)
return false;
long end = nextBlkNum + rhsChunkSize - 1;
if (end >= rhsFileSize)
end = rhsFileSize - 1;
rhsScan = new ChunkScan(rhsTi, nextBlkNum, end, tx);
prodScan = new ProductScan(lhsScan, rhsScan);
prodScan.beforeFirst();
nextBlkNum = end + 1;
return true;
}
}
| apache-2.0 |
wso2/carbon-analytics-common | components/data-bridge/org.wso2.carbon.databridge.receiver.thrift/src/main/java/org/wso2/carbon/databridge/receiver/thrift/internal/ThriftDataReceiverDS.java | 4313 | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.databridge.receiver.thrift.internal;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.wso2.carbon.databridge.commons.ServerEventListener;
import org.wso2.carbon.databridge.core.DataBridgeReceiverService;
import org.wso2.carbon.kernel.CarbonRuntime;
/**
* ThriftDataReceiver Service component.
*
* @since 1.0.0
*/
@Component(
name = "org.wso2.carbon.databridge.receiver.thrift.internal.ThriftDataReceiverDS",
immediate = true
)
public class ThriftDataReceiverDS {
private static final Logger log = LogManager.getLogger(ThriftDataReceiverDS.class);
private ThriftServerStartupImpl thriftDataReceiver;
/**
* This is the activation method of ThriftDataReceiverDS. This will be called when its references are
* satisfied.
*
* @param bundleContext the bundle context instance of this bundle.
* @throws Exception this will be thrown if an issue occurs while executing the activate method
*/
@Activate
protected void start(BundleContext bundleContext) throws Exception {
log.info("Service Component is activated");
thriftDataReceiver = new ThriftServerStartupImpl();
bundleContext.registerService(ServerEventListener.class.getName(),
thriftDataReceiver, null);
}
/**
* This is the deactivation method of ThriftDataReceiverDS. This will be called when this component
* is being stopped or references are satisfied during runtime.
*
* @throws Exception this will be thrown if an issue occurs while executing the de-activate method
*/
@Deactivate
protected void stop() throws Exception {
thriftDataReceiver.stop();
}
/**
*
* @param dataBridgeReceiverService The DataBridgeReceiverService instance registered as an OSGi service
*/
@Reference(
name = "dataBridge.receiver.service",
service = DataBridgeReceiverService.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetDatabridgeReceiverService"
)
protected void setDataBridgeReceiverService(
DataBridgeReceiverService dataBridgeReceiverService) {
ServiceHolder.setDataBridgeReceiverService(dataBridgeReceiverService);
}
protected void unsetDatabridgeReceiverService(
DataBridgeReceiverService dataBridgeReceiverService) {
ServiceHolder.setDataBridgeReceiverService(dataBridgeReceiverService);
}
/**
* This bind method will be called when CarbonRuntime OSGi service is registered.
*
* @param carbonRuntime The CarbonRuntime instance registered by Carbon Kernel as an OSGi service
*/
@Reference(
name = "carbon.runtime.service",
service = CarbonRuntime.class,
cardinality = ReferenceCardinality.MANDATORY,
policy = ReferencePolicy.DYNAMIC,
unbind = "unsetCarbonRuntime"
)
protected void setCarbonRuntime(CarbonRuntime carbonRuntime) {
ServiceHolder.setCarbonRuntime(carbonRuntime);
}
protected void unsetCarbonRuntime(CarbonRuntime carbonRuntime) {
ServiceHolder.setCarbonRuntime(null);
}
}
| apache-2.0 |
wukonggg/mz-g | src/main/java/band/wukong/mz/g/AppConf.java | 510 | package band.wukong.mz.g;
import org.nutz.ioc.impl.PropertiesProxy;
/**
* 通过js文件被ioc容器识别
*
* @author wukong(wukonggg@139.com)
*/
public class AppConf extends PropertiesProxy {
public static final String BARCODE_IMAGE_PATH = "barcode.image.path";
public static final String BARCODE_IMAGE_WIDTH = "barcode.image.width";
public static final String BARCODE_IMAGE_HEIGHT = "barcode.image.height";
public static final String BARCODE_IMAGE_FORMAT = "barcode.image.format";
}
| apache-2.0 |
OpenSourceConsulting/athena-dolly | common/src/main/java/com/athena/dolly/common/cache/SessionKey.java | 1505 | /*
* Athena Peacock Dolly - DataGrid based Clustering
*
* Copyright (C) 2013 Open Source Consulting, Inc. All rights reserved by Open Source Consulting, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Revision History
* Author Date Description
* --------------- ---------------- ------------
* Sang-cheon Park 2014. 4. 1. First Draft.
*/
package com.athena.dolly.common.cache;
import java.io.Serializable;
/**
* <pre>
*
* </pre>
* @author Sang-cheon Park
* @version 1.0
*/
public class SessionKey implements Serializable {
private static final long serialVersionUID = 1L;
private String key;
/**
* @return the key
*/
public String getKey() {
return key;
}
/**
* @param key the key to set
*/
public void setKey(String key) {
this.key = key;
}
}
//end of SessionKey.java | apache-2.0 |
farruxxamidov/java_pft | mantis-tests/src/test/java/ru/stqa/pft/mantis/appmanager/FtpHelper.java | 1113 | package ru.stqa.pft.mantis.appmanager;
import org.apache.commons.net.ftp.FTPClient;
import ru.stqa.pft.mantis.tests.TestBase;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* Created on 08.04.2016.
*/
public class FtpHelper extends TestBase {
private final ApplicationManager app;
private FTPClient ftp;
public FtpHelper(ApplicationManager app) {
this.app = app;
ftp = new FTPClient();
}
public void upload(File file, String target, String backup) throws IOException {
ftp.connect(app.getProperty("ftp.host"));
ftp.login(app.getProperty("ftp.login"),app.getProperty("ftp.password"));
ftp.deleteFile(backup);
ftp.rename(target,backup);
ftp.enterLocalPassiveMode();
ftp.storeFile(target,new FileInputStream(file));
ftp.disconnect();
}
public void restore(String target, String backup) throws IOException {
ftp.connect(app.getProperty("ftp.host"));
ftp.login(app.getProperty("ftp.login"),app.getProperty("ftp.password"));
ftp.deleteFile(target);
ftp.rename(backup,target);
ftp.disconnect();
}
}
| apache-2.0 |
kenmeidearu/MaterialDateTimePicker | library/src/main/java/com/kenmeidearu/materialdatetimepicker/date/MonthAdapter.java | 8122 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kenmeidearu.materialdatetimepicker.date;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.BaseAdapter;
import com.kenmeidearu.materialdatetimepicker.date.MonthView.OnDayClickListener;
import java.util.Calendar;
import java.util.HashMap;
/**
* An adapter for a list of {@link MonthView} items.
*/
public abstract class MonthAdapter extends BaseAdapter implements OnDayClickListener {
private static final String TAG = "SimpleMonthAdapter";
private final Context mContext;
protected final DatePickerController mController;
private CalendarDay mSelectedDay;
protected static int WEEK_7_OVERHANG_HEIGHT = 7;
protected static final int MONTHS_IN_YEAR = 12;
/**
* A convenience class to represent a specific date.
*/
public static class CalendarDay {
private Calendar calendar;
private Timepoint mInitialTime;
int year;
int month;
int day;
int hour;
public CalendarDay() {
setTime(System.currentTimeMillis());
}
public CalendarDay(long timeInMillis) {
setTime(timeInMillis);
}
public CalendarDay(Calendar calendar,Timepoint minitialTime) {
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
mInitialTime=minitialTime;
}
public CalendarDay(Calendar calendar) {
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
}
public CalendarDay(int year, int month, int day) {
setDay(year, month, day);
}
/* public CalendarDay(int year, int month, int day,int hour) {
setDay(year, month, day,hour);
}*/
public void set(CalendarDay date) {
year = date.year;
month = date.month;
day = date.day;
}
/*public void setDay(int year, int month, int day,int hour) {
this.year = year;
this.month = month;
this.day = day;
this.hour=hour;
}*/
public void setDay(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
private void setTime(long timeInMillis) {
if (calendar == null) {
calendar = Calendar.getInstance();
}
calendar.setTimeInMillis(timeInMillis);
month = calendar.get(Calendar.MONTH);
year = calendar.get(Calendar.YEAR);
day = calendar.get(Calendar.DAY_OF_MONTH);
// hour=calendar.get(Calendar.HOUR);
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public int getDay() {
return day;
}
public int getHour(){return mInitialTime.getHour();}
public int getMinute(){return mInitialTime.getMinute();}
public int getSecond(){return mInitialTime.getSecond();}
public boolean isAm(){return mInitialTime.isAM();}
public boolean isPM(){return mInitialTime.isPM();}
}
public MonthAdapter(Context context,
DatePickerController controller) {
mContext = context;
mController = controller;
init();
setSelectedDay(mController.getSelectedDay());
}
/**
* Updates the selected day and related parameters.
*
* @param day The day to highlight
*/
public void setSelectedDay(CalendarDay day) {
mSelectedDay = day;
notifyDataSetChanged();
}
@SuppressWarnings("unused")
public CalendarDay getSelectedDay() {
return mSelectedDay;
}
/**
* Set up the gesture detector and selected time
*/
protected void init() {
mSelectedDay = new CalendarDay(System.currentTimeMillis());
}
@Override
public int getCount() {
Calendar endDate = mController.getEndDate();
Calendar startDate = mController.getStartDate();
int endMonth = endDate.get(Calendar.YEAR) * MONTHS_IN_YEAR + endDate.get(Calendar.MONTH);
int startMonth = startDate.get(Calendar.YEAR) * MONTHS_IN_YEAR + startDate.get(Calendar.MONTH);
return endMonth - startMonth + 1;
//return ((mController.getMaxYear() - mController.getMinYear()) + 1) * MONTHS_IN_YEAR;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
@SuppressLint("NewApi")
@SuppressWarnings("unchecked")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MonthView v;
HashMap<String, Integer> drawingParams = null;
if (convertView != null) {
v = (MonthView) convertView;
// We store the drawing parameters in the view so it can be recycled
drawingParams = (HashMap<String, Integer>) v.getTag();
} else {
v = createMonthView(mContext);
// Set up the new view
LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
v.setLayoutParams(params);
v.setClickable(true);
v.setOnDayClickListener(this);
}
if (drawingParams == null) {
drawingParams = new HashMap<>();
}
drawingParams.clear();
final int month = (position + mController.getStartDate().get(Calendar.MONTH)) % MONTHS_IN_YEAR;
final int year = (position + mController.getStartDate().get(Calendar.MONTH)) / MONTHS_IN_YEAR + mController.getMinYear();
int selectedDay = -1;
if (isSelectedDayInMonth(year, month)) {
selectedDay = mSelectedDay.day;
}
// Invokes requestLayout() to ensure that the recycled view is set with the appropriate
// height/number of weeks before being displayed.
v.reuse();
drawingParams.put(MonthView.VIEW_PARAMS_SELECTED_DAY, selectedDay);
drawingParams.put(MonthView.VIEW_PARAMS_YEAR, year);
drawingParams.put(MonthView.VIEW_PARAMS_MONTH, month);
drawingParams.put(MonthView.VIEW_PARAMS_WEEK_START, mController.getFirstDayOfWeek());
v.setMonthParams(drawingParams);
v.invalidate();
return v;
}
public abstract MonthView createMonthView(Context context);
private boolean isSelectedDayInMonth(int year, int month) {
return mSelectedDay.year == year && mSelectedDay.month == month;
}
@Override
public void onDayClick(MonthView view, CalendarDay day) {
if (day != null) {
onDayTapped(day);
}
}
/**
* Maintains the same hour/min/sec but moves the day to the tapped day.
*
* @param day The day that was tapped
*/
protected void onDayTapped(CalendarDay day) {
mController.tryVibrate();
mController.onDayOfMonthSelected(day.year, day.month, day.day);
setSelectedDay(day);
}
}
| apache-2.0 |
Songhuitang/impala-connect-couchbase | src/com/softtek/couchbase/CouchbaseUtil.java | 2995 | package com.softtek.couchbase;
import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.PersistTo;
import com.couchbase.client.java.document.Document;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonArray;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.query.N1qlQuery;
import com.couchbase.client.java.query.N1qlQueryResult;
import com.oracle.javafx.jmx.json.JSONDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by simon.song on 2017/6/27.
*/
public class CouchbaseUtil {
private static Logger logger = LoggerFactory.getLogger(CouchbaseUtil.class);
public static N1qlQueryResult getQueryResult( String bucket, String query){
N1qlQueryResult result = null;
// Connect to the bucket and open it
Bucket couchBucket = CouchbaseFactory.getCouchbaseCluster().openBucket(bucket);
// Create a N1QL Primary Index (but ignore if it exists)
couchBucket.bucketManager().createN1qlPrimaryIndex(true,false);
// Perform a N1QL Query
result = couchBucket.query(
N1qlQuery.simple(query)
);
closeBucket(couchBucket);
return result;
}
public static N1qlQueryResult getQueryResult(String bucket, String query, String Condition){
N1qlQueryResult result = null;
// Connect to the bucket and open it
Bucket couchBucket = CouchbaseFactory.getCouchbaseCluster().openBucket(bucket);
// Create a N1QL Primary Index (but ignore if it exists)
couchBucket.bucketManager().createN1qlPrimaryIndex(true,false);
// Perform a N1QL Query
result = couchBucket.query(
N1qlQuery.parameterized(query, JsonArray.from(Condition))
);
closeBucket(couchBucket);
return result;
}
public static void upsertDocument(String bucket, String documentId, JsonObject json){
Bucket upsertBucket = CouchbaseFactory.getCouchbaseCluster().openBucket(bucket);
upsertBucket.upsert(JsonDocument.create(documentId,json));
logger.info("document created with ID: {}, in bucket: {}", documentId, bucket);
closeBucket(upsertBucket);
}
public static void deleteDocument(String bucket, String documentId){
Bucket delBucket = CouchbaseFactory.getCouchbaseCluster().openBucket(bucket);
delBucket.remove(documentId);
logger.info("document deleted with ID: {}, in bucket: {}", documentId, bucket);
closeBucket(delBucket);
}
public static JsonDocument getDocumentById(String bucket, String documentId){
Bucket getBucket = CouchbaseFactory.getCouchbaseCluster().openBucket(bucket);
JsonDocument document = getBucket.get(documentId);
closeBucket(getBucket);
return document;
}
private static void closeBucket(Bucket bucket){
bucket.close();
}
}
| apache-2.0 |
tkao1000/pinot | thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/dashboard/configs/FileBasedConfigDAOFactory.java | 6382 | package com.linkedin.thirdeye.dashboard.configs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.linkedin.thirdeye.api.CollectionSchema;
public class FileBasedConfigDAOFactory implements ConfigDAOFactory {
private static final Logger LOG = LoggerFactory.getLogger(FileBasedConfigDAOFactory.class);
private static String FILE_EXT = ".json";
private final String rootDir;
private AbstractConfigDAO<CollectionConfig> collectionConfigDAO;
private AbstractConfigDAO<DashboardConfig> dashboardConfigDAO;
private AbstractConfigDAO<WidgetConfig> widgetConfigDAO;
private AbstractConfigDAO<CollectionSchema> collectionSchemaDAO;
public FileBasedConfigDAOFactory(String rootDir) {
this.rootDir = rootDir;
}
@Override
public AbstractConfigDAO<CollectionSchema> getCollectionSchemaDAO() {
final FileBasedConfigDAO<CollectionSchema> fileBasedConfigDAO =
new FileBasedConfigDAO<>(rootDir, CollectionSchema.class.getSimpleName());
collectionSchemaDAO = createDAO(fileBasedConfigDAO, CollectionSchema.class.getSimpleName());
return collectionSchemaDAO;
}
@Override
public AbstractConfigDAO<CollectionConfig> getCollectionConfigDAO() {
final FileBasedConfigDAO<CollectionConfig> fileBasedConfigDAO =
new FileBasedConfigDAO<>(rootDir, CollectionConfig.class.getSimpleName());
collectionConfigDAO = createDAO(fileBasedConfigDAO, CollectionConfig.class.getSimpleName());
return collectionConfigDAO;
}
@Override
public AbstractConfigDAO<DashboardConfig> getDashboardConfigDAO() {
final FileBasedConfigDAO<DashboardConfig> fileBasedConfigDAO =
new FileBasedConfigDAO<>(rootDir, DashboardConfig.class.getSimpleName());
dashboardConfigDAO = createDAO(fileBasedConfigDAO, DashboardConfig.class.getSimpleName());
return dashboardConfigDAO;
}
@Override
public AbstractConfigDAO<WidgetConfig> getWidgetConfigDAO() {
final FileBasedConfigDAO<WidgetConfig> fileBasedConfigDAO =
new FileBasedConfigDAO<>(rootDir, WidgetConfig.class.getSimpleName());
widgetConfigDAO = createDAO(fileBasedConfigDAO, WidgetConfig.class.getSimpleName());
return widgetConfigDAO;
}
private <T extends AbstractConfig> AbstractConfigDAO<T> createDAO(
final FileBasedConfigDAO<T> fileBasedConfigDAO, String configType) {
return new AbstractConfigDAO<T>() {
@Override
public boolean update(String id, T config) throws Exception {
return fileBasedConfigDAO.update(id, config);
}
@Override
public T findById(String id) {
return fileBasedConfigDAO.findById(id);
}
@SuppressWarnings("unchecked")
@Override
public List<T> findAll() {
List<AbstractConfig> list = fileBasedConfigDAO.findAll();
List<T> ret = new ArrayList<>();
for (AbstractConfig config : list) {
ret.add((T) config);
}
return ret;
}
@Override
public boolean create(String id, T config) throws Exception {
return fileBasedConfigDAO.create(id, config);
}
};
}
class FileBasedConfigDAO<T extends AbstractConfig> {
private final File rootDir;
private final String configType;
Class<? extends AbstractConfig> configTypeClass;
// private Constructor<T> constructor;
public FileBasedConfigDAO(String rootDir, String configType) {
this.rootDir = new File(rootDir);
this.configType = configType;
if (configType.equalsIgnoreCase("collectionConfig")) {
configTypeClass = CollectionConfig.class;
} else if (configType.equalsIgnoreCase("dashboardConfig")) {
configTypeClass = DashboardConfig.class;
} else if (configType.equalsIgnoreCase("widgetConfig")) {
configTypeClass = WidgetConfig.class;
} else if (configType.equalsIgnoreCase("collectionSchema")) {
configTypeClass = CollectionSchema.class;
} else {
throw new IllegalArgumentException("Unknown configType:" + configType);
}
try {
// constructor = configTypeClass.getConstructor();
} catch (Exception e) {
throw new IllegalArgumentException(
"Error getting constructor for class :" + configTypeClass, e);
}
}
public List<AbstractConfig> findAll() {
File dir = getConfigTypeRootDir();
File[] listFiles = dir.listFiles();
if (listFiles == null || listFiles.length == 0) {
return Collections.emptyList();
}
List<AbstractConfig> list = new ArrayList<>();
for (File file : listFiles) {
AbstractConfig instance = parseFile(file);
list.add(instance);
}
return list;
}
private File getConfigTypeRootDir() {
return new File(rootDir, configType);
}
private File getFile(String id) {
return new File(getConfigTypeRootDir(), id + FILE_EXT);
}
private T parseFile(File file) {
if (!file.exists()) {
return null;
}
InputStream input = null;
try {
input = new FileInputStream(file);
String json = IOUtils.toString(input, "UTF-8");
T instance = AbstractConfig.fromJSON(json, configTypeClass);
return instance;
} catch (Exception e) {
LOG.error("Error parsing file:" + file, e);
} finally {
if (input != null) {
IOUtils.closeQuietly(input);
}
}
return null;
}
public T findById(String id) {
File file = getFile(id);
T t = parseFile(file);
return t;
}
public boolean create(String id, T config) throws Exception {
File file = getFile(id);
file.getParentFile().mkdirs();
System.out.println("Writing " + config.toJSON() + " at " + file.getAbsolutePath());
FileWriter fileWriter = new FileWriter(file);
IOUtils.write(config.toJSON(), fileWriter);
fileWriter.flush();
fileWriter.close();
return true;
}
public boolean update(String id, AbstractConfig config) throws Exception {
File file = getFile(id);
IOUtils.write(config.toJSON(), new FileWriter(file));
return true;
}
}
}
| apache-2.0 |
SMB-TEC/extended-objects | neo4j/src/test/java/com/buschmais/xo/neo4j/test/bootstrap/EmbeddedNeo4jBootstrapTest.java | 729 | package com.buschmais.xo.neo4j.test.bootstrap;
import com.buschmais.xo.api.XOManager;
import com.buschmais.xo.api.XOManagerFactory;
import com.buschmais.xo.api.bootstrap.XO;
import com.buschmais.xo.neo4j.test.bootstrap.composite.A;
import org.junit.Test;
public class EmbeddedNeo4jBootstrapTest {
@Test
public void bootstrap() {
XOManagerFactory xoManagerFactory = XO.createXOManagerFactory("Neo4jEmbedded");
XOManager xoManager = xoManagerFactory.createXOManager();
xoManager.currentTransaction().begin();
A a = xoManager.create(A.class);
a.setName("Test");
xoManager.currentTransaction().commit();
xoManager.close();
xoManagerFactory.close();
}
}
| apache-2.0 |
clive-jevons/joynr | java/messaging/messaging-common/src/main/java/io/joynr/arbitration/DiscoveryScope.java | 1329 | package io.joynr.arbitration;
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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%
*/
/**
* DiscoveryScope indicates whther only locally registered capabilities are to be used in discovery, or if the global registry is also to be used.
*
*/
public enum DiscoveryScope {
/**
* Only capabilities registered locally will be discovered
*/
LOCAL_ONLY,
/**
* local capabilities will be discovered if available; otherwise the global registry will be queried
*/
LOCAL_THEN_GLOBAL,
/**
* local capabilities and capabilities from the global registry will be combined and returned
*/
LOCAL_AND_GLOBAL,
/**
* Only the global registry will be queried during discovery
*/
GLOBAL_ONLY
}; | apache-2.0 |
MarcGuiot/globsframework | src/main/java/org/globsframework/model/globaccessor/set/GlobSetLongAccessor.java | 260 | package org.globsframework.model.globaccessor.set;
import org.globsframework.model.MutableGlob;
public interface GlobSetLongAccessor extends GlobSetAccessor {
void setNative(MutableGlob glob, long value);
void set(MutableGlob glob, Long value);
}
| apache-2.0 |
nosceon/titanite | titanite-scope-flash/src/test/java/org/nosceon/titanite/FlashE2ETest.java | 2465 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nosceon.titanite;
import org.junit.Test;
import static com.jayway.restassured.RestAssured.given;
import static org.nosceon.titanite.Method.GET;
import static org.nosceon.titanite.Response.ok;
import static org.nosceon.titanite.scope.Flash.enableFlash;
import static org.nosceon.titanite.scope.Flash.flash;
import static org.nosceon.titanite.scope.FlashFilter.DEFAULT_FLASH_COOKIE_NAME;
/**
* @author Johan Siebens
*/
public class FlashE2ETest extends AbstractE2ETest {
@Override
protected Shutdownable configureAndStartHttpServer(HttpServer server) {
return
server
.setFilter(enableFlash())
.register(GET, "/a", (r) -> {
flash(r).set("name", "titanite");
flash(r).set("lorem", "ipsum");
return ok().toFuture();
})
.register(GET, "/b",
req -> {
int count = flash(req).getInt("count", 0);
flash(req).set("count", count + 1);
return ok().text(String.valueOf(count)).toFuture();
}
)
.start();
}
@Test
public void testA() {
given().expect().statusCode(200).cookie(DEFAULT_FLASH_COOKIE_NAME, "\"lorem=ipsum&name=titanite\"").when().get(uri("/a"));
}
@Test
public void testB() {
given()
.cookie(DEFAULT_FLASH_COOKIE_NAME, "\"count=1\"")
.expect().statusCode(200).cookie(DEFAULT_FLASH_COOKIE_NAME, "\"count=2\"").when().get(uri("/b"));
}
@Test
public void testC() {
given()
.cookie(DEFAULT_FLASH_COOKIE_NAME, "\"lorem=ipsum\"")
.expect().statusCode(200).cookie(DEFAULT_FLASH_COOKIE_NAME, "\"count=1\"").when().get(uri("/b"));
}
}
| apache-2.0 |
QNJR-GROUP/EasyTransaction | easytrans-core/src/main/java/com/yiqiniu/easytrans/datasource/impl/DefaultTransStatusLoggerImpl.java | 5458 | package com.yiqiniu.easytrans.datasource.impl;
import static com.yiqiniu.easytrans.core.EasytransConstant.StringCodecKeys.APP_ID;
import static com.yiqiniu.easytrans.core.EasytransConstant.StringCodecKeys.BUSINESS_CODE;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import com.yiqiniu.easytrans.datasource.DataSourceSelector;
import com.yiqiniu.easytrans.datasource.TransStatusLogger;
import com.yiqiniu.easytrans.protocol.BusinessIdentifer;
import com.yiqiniu.easytrans.protocol.EasyTransRequest;
import com.yiqiniu.easytrans.protocol.TransactionId;
import com.yiqiniu.easytrans.stringcodec.StringCodec;
public class DefaultTransStatusLoggerImpl implements TransStatusLogger {
private String updateTransStatusWithPTrxId = "UPDATE executed_trans SET status = ? WHERE p_app_id = ? AND p_bus_code = ? AND p_trx_id = ? AND status != ?";
private String updateTransStatusWithTrxId = "UPDATE executed_trans SET status = ? WHERE app_id = ? AND bus_code = ? AND trx_id = ? AND status = ?";
private String insertExecutedTag = "INSERT INTO executed_trans (app_id, bus_code, trx_id,p_app_id, p_bus_code, p_trx_id,status) VALUES ( ?, ?, ?, ?, ?, ?, ?)";
private String checkTransExecuted = "select status from executed_trans where app_id = ? and bus_code = ? and trx_id = ? for update";
private DataSourceSelector selctor;
private StringCodec codec;
public DefaultTransStatusLoggerImpl(DataSourceSelector selctor, StringCodec codec, String tablePrefix) {
super();
this.selctor = selctor;
this.codec = codec;
if(!StringUtils.isEmpty(tablePrefix)) {
tablePrefix = tablePrefix.trim();
updateTransStatusWithPTrxId = updateTransStatusWithPTrxId.replace("executed_trans", tablePrefix + "executed_trans");
updateTransStatusWithTrxId = updateTransStatusWithTrxId.replace("executed_trans", tablePrefix + "executed_trans");
insertExecutedTag = insertExecutedTag.replace("executed_trans", tablePrefix + "executed_trans");
checkTransExecuted = checkTransExecuted.replace("executed_trans", tablePrefix + "executed_trans");
}
}
private ConcurrentHashMap<DataSource, JdbcTemplate> mapJdbcTemplate = new ConcurrentHashMap<DataSource, JdbcTemplate>();
@Override
public Boolean checkTransactionStatus(String appId, String busCode, long trxId) {
DataSource dataSource = selctor.selectDataSource(appId, busCode, trxId);
JdbcTemplate jdbcTemplate = getJdbcTemplate(dataSource);
//select * for update
List<Integer> statusList = jdbcTemplate.queryForList(checkTransExecuted,
new Object[]{
codec.findId(APP_ID, appId),
codec.findId(BUSINESS_CODE, busCode),
trxId},
Integer.class);
if(statusList == null || statusList.size() == 0) {
return false;
} else {
//it can only be 1 record,because it's search by primary key
int status = statusList.get(0);
switch(status){
case TransactionStatus.UNKNOWN:
//parent transaction status unknown
return null;
case TransactionStatus.COMMITTED:
//success
return true;
case TransactionStatus.ROLLBACKED:
return false;
default:
throw new IllegalArgumentException("unknown transaction status:" + status);
}
}
}
private JdbcTemplate getJdbcTemplate(DataSource dataSource) {
JdbcTemplate jdbcTemplate = mapJdbcTemplate.get(dataSource);
if(jdbcTemplate == null){
jdbcTemplate = new JdbcTemplate(dataSource);
mapJdbcTemplate.put(dataSource, jdbcTemplate);
}
return jdbcTemplate;
}
@Override
public void writeExecuteFlag(String appId, String busCode, long trxId, String pAppId, String pBusCode, Long pTrxId, int status) {
JdbcTemplate jdbcTemplate = getJdbcTemplate(selctor.selectDataSource(appId, busCode, trxId));
int update = jdbcTemplate.update(insertExecutedTag,
codec.findId(APP_ID, appId),
codec.findId(BUSINESS_CODE, busCode),
trxId,
pAppId != null?codec.findId(APP_ID, pAppId):null,
pBusCode != null?codec.findId(BUSINESS_CODE, pBusCode):null,
pTrxId != null? pTrxId:null,
status
);
if(update != 1){
throw new RuntimeException(String.format("insert count(%s) Error!%s %s %s %s %s %s %s", update,appId,busCode,trxId,pAppId,pBusCode,pTrxId,status));
}
}
@Override
public void updateExecuteFlagForSlaveTrx(TransactionId pId, EasyTransRequest<?, ?> request, int status) {
BusinessIdentifer businessIdentifer = request.getClass().getAnnotation(BusinessIdentifer.class);
JdbcTemplate jdbcTemplate = getJdbcTemplate(selctor.selectDataSource(businessIdentifer.appId(),businessIdentifer.busCode(),request));
jdbcTemplate.update(updateTransStatusWithPTrxId,
status,
codec.findId(APP_ID, pId.getAppId()),
codec.findId(BUSINESS_CODE, pId.getBusCode()),
pId.getTrxId(),
status);
}
@Override
public int updateMasterTransactionStatus(TransactionId trxId, int status) {
JdbcTemplate jdbcTemplate = getJdbcTemplate(selctor.selectDataSource(trxId.getAppId(),trxId.getBusCode(),trxId.getTrxId()));
return jdbcTemplate.update(updateTransStatusWithTrxId,
status,
codec.findId(APP_ID, trxId.getAppId()),
codec.findId(BUSINESS_CODE, trxId.getBusCode()),
trxId.getTrxId(),
2);
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Framework/Project/src/main/java/ghidra/framework/main/projectdata/actions/VersionControlCheckInAction.java | 4382 | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework.main.projectdata.actions;
import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import docking.action.MenuData;
import docking.action.ToolBarData;
import ghidra.framework.main.datatable.DomainFileContext;
import ghidra.framework.main.datatree.ChangedFilesDialog;
import ghidra.framework.main.datatree.CheckInTask;
import ghidra.framework.model.DomainFile;
import ghidra.framework.plugintool.Plugin;
import ghidra.util.Msg;
import resources.ResourceManager;
/**
* Action to check-in domain files to the repository.
*/
public class VersionControlCheckInAction extends VersionControlAction {
private Component parent;
/**
* Creates an action to check-in domain files to the repository.
* @param plugin the plug-in that owns this action.
* @param parent the component to be used as the parent of the check-in dialog.
*/
public VersionControlCheckInAction(Plugin plugin, Component parent) {
super("CheckIn", plugin.getName(), plugin.getTool());
this.parent = parent;
ImageIcon icon = ResourceManager.loadImage("images/vcCheckIn.png");
setPopupMenuData(new MenuData(new String[] { "Check In..." }, icon, GROUP));
setToolBarData(new ToolBarData(icon, GROUP));
setDescription("Check in file");
setEnabled(false);
}
@Override
public void actionPerformed(DomainFileContext context) {
doCheckIn(context.getSelectedFiles());
}
@Override
public boolean isEnabledForContext(DomainFileContext context) {
if (isFileSystemBusy()) {
return false; // don't block; we should get called again later
}
List<DomainFile> domainFiles = context.getSelectedFiles();
for (DomainFile domainFile : domainFiles) {
if (domainFile.isCheckedOut() && domainFile.modifiedSinceCheckout()) {
return true; // At least one checked out file selected.
}
}
return false;
}
/**
* Determines the list of modified, checked out files and then checks them in.
*/
private void doCheckIn(List<DomainFile> domainFiles) {
if (!checkRepositoryConnected()) {
return;
}
List<DomainFile> checkedOut = new ArrayList<>();
for (DomainFile domainFile : domainFiles) {
if (domainFile.isCheckedOut() && domainFile.modifiedSinceCheckout()) {
checkedOut.add(domainFile);
}
}
if (checkedOut.isEmpty()) {
Msg.showInfo(this, parent, "No Modified Files",
"No checked-out and modified files in the given selection");
return;
}
if (checkedOut.size() > 0) {
checkIn(checkedOut);
}
}
/**
* Check in the list of domain files.
* Domain files that cannot be closed are skipped in the list.
* @param fileList list of DomainFile objects
*/
public void checkIn(List<DomainFile> fileList) {
if (!checkRepositoryConnected()) {
return;
}
ArrayList<DomainFile> changedList = new ArrayList<>();
ArrayList<DomainFile> list = new ArrayList<>();
for (int i = 0; i < fileList.size(); i++) {
DomainFile df = fileList.get(i);
if (df != null && df.canCheckin()) {
if (!canCloseDomainFile(df)) {
continue;
}
list.add(df);
if (df.isChanged()) {
changedList.add(df);
}
}
}
if (changedList.size() > 0) {
ChangedFilesDialog dialog = new ChangedFilesDialog(tool, changedList);
dialog.setCancelToolTipText("Cancel Check In");
if (!dialog.showDialog()) { // blocks until the user hits Save or Cancel
tool.setStatusInfo("Checkin canceled");
return;
}
for (int i = 0; i < changedList.size(); i++) {
DomainFile df = changedList.get(i);
if (df.isChanged()) {
list.remove(df);
}
}
}
if (list.size() > 0) {
tool.execute(new CheckInTask(tool, list, parent));
}
else {
Msg.showError(this, tool.getToolFrame(), "Checkin Failed", "Unable to checkin file(s)");
}
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/database/module/FragmentDB.java | 10138 | /* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.program.database.module;
import java.io.IOException;
import java.util.Iterator;
import db.Field;
import db.DBRecord;
import ghidra.program.database.DBObjectCache;
import ghidra.program.database.DatabaseObject;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.*;
import ghidra.util.Lock;
import ghidra.util.exception.DuplicateNameException;
import ghidra.util.exception.NotFoundException;
/**
*
* Database implementation for Fragment.
*
*/
class FragmentDB extends DatabaseObject implements ProgramFragment {
private DBRecord record;
private ModuleManager moduleMgr;
private GroupDBAdapter adapter;
private AddressSetView addrSet;
private Lock lock;
/**
* Constructor
* @param moduleMgr
* @param cache
* @param record
* @param addrSet
*/
FragmentDB(ModuleManager moduleMgr, DBObjectCache<FragmentDB> cache, DBRecord record,
AddressSet addrSet) {
super(cache, record.getKey());
this.moduleMgr = moduleMgr;
this.record = record;
this.addrSet = addrSet;
adapter = moduleMgr.getGroupDBAdapter();
lock = moduleMgr.getLock();
}
@Override
protected boolean refresh() {
try {
DBRecord rec = adapter.getFragmentRecord(key);
if (rec != null) {
record = rec;
addrSet = moduleMgr.getFragmentAddressSet(key);
return true;
}
}
catch (IOException e) {
moduleMgr.dbError(e);
}
return false;
}
@Override
public boolean contains(CodeUnit codeUnit) {
return contains(codeUnit.getMinAddress());
}
@Override
public CodeUnitIterator getCodeUnits() {
checkIsValid();
return moduleMgr.getCodeUnits(this);
}
@Override
public String getComment() {
lock.acquire();
try {
checkIsValid();
return record.getString(TreeManager.FRAGMENT_COMMENTS_COL);
}
finally {
lock.release();
}
}
@Override
public String getName() {
lock.acquire();
try {
checkIsValid();
return record.getString(TreeManager.FRAGMENT_NAME_COL);
}
finally {
lock.release();
}
}
@Override
public int getNumParents() {
lock.acquire();
try {
checkIsValid();
Field[] keys = adapter.getParentChildKeys(-key, TreeManager.CHILD_ID_COL);
return keys.length;
}
catch (IOException e) {
moduleMgr.dbError(e);
}
finally {
lock.release();
}
return 0;
}
@Override
public String[] getParentNames() {
return moduleMgr.getParentNames(-key);
}
@Override
public ProgramModule[] getParents() {
return moduleMgr.getParents(-key);
}
@Override
public void move(Address min, Address max) throws NotFoundException {
lock.acquire();
try {
checkDeleted();
moduleMgr.move(this, min, max);
}
finally {
lock.release();
}
}
@Override
public void setComment(String comment) {
lock.acquire();
try {
checkDeleted();
String oldComments = record.getString(TreeManager.FRAGMENT_COMMENTS_COL);
if (oldComments == null || !oldComments.equals(comment)) {
record.setString(TreeManager.FRAGMENT_COMMENTS_COL, comment);
try {
adapter.updateFragmentRecord(record);
moduleMgr.commentsChanged(oldComments, this);
}
catch (IOException e) {
moduleMgr.dbError(e);
}
}
}
finally {
lock.release();
}
}
@Override
public void setName(String name) throws DuplicateNameException {
lock.acquire();
try {
checkIsValid();
DBRecord r = adapter.getFragmentRecord(name);
if (r != null) {
if (key != r.getKey()) {
throw new DuplicateNameException(name + " already exists");
}
return; // no changes
}
if (adapter.getModuleRecord(name) != null) {
throw new DuplicateNameException(name + " already exists");
}
String oldName = record.getString(TreeManager.FRAGMENT_NAME_COL);
record.setString(TreeManager.FRAGMENT_NAME_COL, name);
adapter.updateFragmentRecord(record);
moduleMgr.nameChanged(oldName, this);
}
catch (IOException e) {
moduleMgr.dbError(e);
}
finally {
lock.release();
}
}
@Override
public String getTreeName() {
return moduleMgr.getTreeName();
}
@Override
public boolean contains(Address start, Address end) {
lock.acquire();
try {
checkIsValid();
return addrSet.contains(start, end);
}
finally {
lock.release();
}
}
@Override
public boolean contains(Address addr) {
lock.acquire();
try {
checkIsValid();
return addrSet.contains(addr);
}
finally {
lock.release();
}
}
@Override
public boolean contains(AddressSetView rangeSet) {
lock.acquire();
try {
checkIsValid();
return addrSet.contains(rangeSet);
}
finally {
lock.release();
}
}
@Override
public boolean hasSameAddresses(AddressSetView view) {
lock.acquire();
try {
checkIsValid();
return addrSet.hasSameAddresses(view);
}
finally {
lock.release();
}
}
@Override
public AddressIterator getAddresses(boolean forward) {
lock.acquire();
try {
checkIsValid();
return addrSet.getAddresses(forward);
}
finally {
lock.release();
}
}
@Override
public AddressIterator getAddresses(Address start, boolean forward) {
lock.acquire();
try {
checkIsValid();
return addrSet.getAddresses(start, forward);
}
finally {
lock.release();
}
}
@Override
public AddressRangeIterator getAddressRanges() {
lock.acquire();
try {
checkIsValid();
return addrSet.getAddressRanges();
}
finally {
lock.release();
}
}
@Override
public Iterator<AddressRange> iterator() {
return getAddressRanges();
}
@Override
public AddressRangeIterator getAddressRanges(boolean atStart) {
lock.acquire();
try {
checkIsValid();
return addrSet.getAddressRanges(atStart);
}
finally {
lock.release();
}
}
@Override
public Address getMaxAddress() {
lock.acquire();
try {
checkIsValid();
return addrSet.getMaxAddress();
}
finally {
lock.release();
}
}
@Override
public Address getMinAddress() {
lock.acquire();
try {
checkIsValid();
return addrSet.getMinAddress();
}
finally {
lock.release();
}
}
@Override
public long getNumAddresses() {
lock.acquire();
try {
checkIsValid();
return addrSet.getNumAddresses();
}
finally {
lock.release();
}
}
@Override
public int getNumAddressRanges() {
lock.acquire();
try {
checkIsValid();
return addrSet.getNumAddressRanges();
}
finally {
lock.release();
}
}
@Override
public AddressSet intersect(AddressSetView view) {
lock.acquire();
try {
checkIsValid();
return addrSet.intersect(view);
}
finally {
lock.release();
}
}
@Override
public AddressSet intersectRange(Address start, Address end) {
lock.acquire();
try {
checkIsValid();
return addrSet.intersectRange(start, end);
}
finally {
lock.release();
}
}
@Override
public boolean intersects(Address start, Address end) {
lock.acquire();
try {
checkIsValid();
return addrSet.intersects(start, end);
}
finally {
lock.release();
}
}
@Override
public boolean intersects(AddressSetView set) {
lock.acquire();
try {
checkIsValid();
return addrSet.intersects(set);
}
finally {
lock.release();
}
}
@Override
public boolean isEmpty() {
lock.acquire();
try {
checkIsValid();
return addrSet.isEmpty();
}
finally {
lock.release();
}
}
@Override
public AddressSet subtract(AddressSetView set) {
lock.acquire();
try {
checkIsValid();
return addrSet.subtract(set);
}
finally {
lock.release();
}
}
@Override
public AddressSet union(AddressSetView set) {
lock.acquire();
try {
checkIsValid();
return addrSet.union(set);
}
finally {
lock.release();
}
}
@Override
public AddressSet xor(AddressSetView set) {
lock.acquire();
try {
checkIsValid();
return addrSet.xor(set);
}
finally {
lock.release();
}
}
ModuleManager getModuleManager() {
return moduleMgr;
}
void addRange(AddressRange range) {
addrSet = addrSet.union(new AddressSet(range));
}
void removeRange(AddressRange range) {
addrSet = addrSet.subtract(new AddressSet(range));
}
@Override
public String toString() {
return addrSet.toString();
}
@Override
public AddressRangeIterator getAddressRanges(Address start, boolean forward) {
lock.acquire();
try {
checkIsValid();
return addrSet.getAddressRanges(start, forward);
}
finally {
lock.release();
}
}
@Override
public AddressRange getFirstRange() {
lock.acquire();
try {
checkIsValid();
return addrSet.getFirstRange();
}
finally {
lock.release();
}
}
@Override
public AddressRange getLastRange() {
lock.acquire();
try {
checkIsValid();
return addrSet.getLastRange();
}
finally {
lock.release();
}
}
@Override
public AddressRange getRangeContaining(Address address) {
lock.acquire();
try {
checkIsValid();
return addrSet.getRangeContaining(address);
}
finally {
lock.release();
}
}
@Override
public Iterator<AddressRange> iterator(boolean forward) {
lock.acquire();
try {
checkIsValid();
return addrSet.iterator(forward);
}
finally {
lock.release();
}
}
@Override
public Iterator<AddressRange> iterator(Address start, boolean forward) {
lock.acquire();
try {
checkIsValid();
return addrSet.iterator(start, forward);
}
finally {
lock.release();
}
}
@Override
public Address findFirstAddressInCommon(AddressSetView set) {
lock.acquire();
try {
checkIsValid();
return addrSet.findFirstAddressInCommon(set);
}
finally {
lock.release();
}
}
}
| apache-2.0 |
dads-software-brotherhood/sekc | src/main/java/mx/infotec/dads/sekc/security/UserNotActivatedException.java | 516 | package mx.infotec.dads.sekc.security;
import org.springframework.security.core.AuthenticationException;
/**
* This exception is thrown in case of a not activated user trying to authenticate.
*/
public class UserNotActivatedException extends AuthenticationException {
private static final long serialVersionUID = 1L;
public UserNotActivatedException(String message) {
super(message);
}
public UserNotActivatedException(String message, Throwable t) {
super(message, t);
}
}
| apache-2.0 |
i49/pulp | pulp-api-ut/src/main/java/com/github/i49/pulp/api/publication/PublicationResourceTest.java | 4703 | /*
* Copyright 2017 The Pulp Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.i49.pulp.api.publication;
import static org.assertj.core.api.Assertions.*;
import java.net.URI;
import org.junit.Test;
import com.github.i49.pulp.api.publication.CoreMediaType;
import com.github.i49.pulp.api.publication.Epub;
import com.github.i49.pulp.api.publication.MediaType;
import com.github.i49.pulp.api.publication.PublicationResource;
import com.github.i49.pulp.api.publication.PublicationResourceBuilder;
import com.github.i49.pulp.api.publication.PublicationResourceBuilderFactory;
/**
* Unit tests for {@link PublicationResource}.
*/
public class PublicationResourceTest {
private static final URI BASE_URI = URI.create("EPUB/package.opf");
private PublicationResourceBuilder newBuilder(String location) {
PublicationResourceBuilderFactory factory = Epub.createResourceBuilderFactory(BASE_URI);
return factory.newBuilder(location);
}
/* getLocation() */
@Test
public void getLocation_shouldReturnLocalLocation() {
// local location
PublicationResource resource = newBuilder("chapter1.xhtml").build();
assertThat(resource.getLocation()).isEqualTo(URI.create("EPUB/chapter1.xhtml"));
}
@Test
public void getLocation_shouldReturnRemoteLocation() {
String remoteLocation = "http://example.org/chapter1.xhtml";
PublicationResource resource = newBuilder(remoteLocation).build();
assertThat(resource.getLocation()).isEqualTo(URI.create(remoteLocation));
}
/* isLocal() */
@Test
public void isLocal_shouldReturnTrueForLocalResource() {
// local location
PublicationResource resource = newBuilder("chapter1.xhtml").build();
assertThat(resource.isLocal()).isTrue();
}
@Test
public void isLocal_shouldReturnFalseForRemoteResource() {
// remote location
PublicationResource resource = newBuilder("http://example.org/chapter1.xhtml").build();
assertThat(resource.isLocal()).isFalse();
}
/* isRemote() */
@Test
public void isRemote_shouldReturnTrueForRemoteResource() {
// remote location
PublicationResource resource = newBuilder("http://example.org/chapter1.xhtml").build();
assertThat(resource.isRemote()).isTrue();
}
@Test
public void isRemote_shouldReturnFalseForLocalResource() {
// local location
PublicationResource resource = newBuilder("chapter1.xhtml").build();
assertThat(resource.isRemote()).isFalse();
}
/* getMediaType */
@Test
public void getMediaType_shouldReturnCoreMediaType() {
PublicationResource resource = newBuilder("chapter1.xhtml")
.ofType(CoreMediaType.APPLICATION_XHTML_XML)
.build();
assertThat(resource.getMediaType()).isEqualTo(CoreMediaType.APPLICATION_XHTML_XML);
}
@Test
public void getMediaType_shouldReturnForeignMediaType() {
PublicationResource resource = newBuilder("chapter1.pdf")
.ofType("application/pdf")
.build();
MediaType mediaType = resource.getMediaType();
assertThat(mediaType.getType()).isEqualTo("application");
assertThat(mediaType.getSubtype()).isEqualTo("pdf");
}
/* isNative() */
@Test
public void isNative_shouldReturnTrueForCoreMediaTypeResource() {
PublicationResource resource = newBuilder("chapter1.xhtml")
.ofType(CoreMediaType.APPLICATION_XHTML_XML)
.build();
assertThat(resource.isNative()).isTrue();
}
@Test
public void isNative_shouldReturnFalseForForeignResource() {
PublicationResource resource = newBuilder("chapter1.pdf")
.ofType("application/pdf")
.build();
assertThat(resource.isNative()).isFalse();
}
/* isForeign() */
@Test
public void isForeign_shouldReturnTrueForForeignResource() {
PublicationResource resource = newBuilder("chapter1.pdf")
.ofType("application/pdf")
.build();
assertThat(resource.isForeign()).isTrue();
}
@Test
public void isForeign_shouldReturnFalseForCoreMediaTypeResource() {
PublicationResource resource = newBuilder("chapter1.xhtml")
.ofType(CoreMediaType.APPLICATION_XHTML_XML)
.build();
assertThat(resource.isForeign()).isFalse();
}
}
| apache-2.0 |
p2p-sync/aggregator | src/main/java/org/rmatil/sync/event/aggregator/config/Config.java | 983 | package org.rmatil.sync.event.aggregator.config;
import org.rmatil.sync.commons.hashing.HashingAlgorithm;
/**
* The configuration for this component
*/
public enum Config {
/**
* The default configuration. It
* uses sha256 to generate hashes from files
*/
DEFAULT(HashingAlgorithm.SHA_256);
/**
* The hashing algorithm
*/
private HashingAlgorithm hashingAlgorithm;
/**
* @param hashingAlgorithm The hashing algorithm to use
*/
Config(HashingAlgorithm hashingAlgorithm) {
this.hashingAlgorithm = hashingAlgorithm;
}
/**
* Returns the default configuration
*
* @return The default configuration
*/
public static Config getDefaultConfiguration() {
return DEFAULT;
}
/**
* Returns the used hashing algorithm
*
* @return The used hashing algorithm
*/
public HashingAlgorithm getHashingAlgorithm() {
return hashingAlgorithm;
}
}
| apache-2.0 |
mortias/Toc.ui | toc-config/src/main/java/com/mitc/config/Parameters.java | 3820 | package com.mitc.config;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
public class Parameters {
private int width;
private int height;
private int restPort;
private int vertxPort;
private int hawtioPort;
private boolean hawtio;
private boolean monitoring;
private String key;
private String root;
private String theme;
private String mode;
private String pathSep;
private String host;
private String proxyUser;
private String proxyHost;
private String proxyPass;
private Integer proxyPort;
private boolean encrypted;
public Parameters() {
theme = "cupertino";
mode = "jquery-ui";
restPort = 9999;
vertxPort = 8888;
hawtio = false;
hawtioPort = 7777;
try {
pathSep = System.getProperty("file.separator");
root = FilenameUtils.getFullPath(new File("test.txt").getCanonicalPath());
host = Inet4Address.getLocalHost().getHostAddress();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public String getPathSep() {
return pathSep;
}
public void setPathSep(String pathSep) {
this.pathSep = pathSep;
}
public String getRoot() {
return root;
}
public void setRoot(String root) {
this.root = root;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public boolean isEncrypted() {
return encrypted;
}
public void setEncrypted(boolean encrypted) {
this.encrypted = encrypted;
}
public int getVertxPort() {
return vertxPort;
}
public void setVertxPort(int vertxPort) {
this.vertxPort = vertxPort;
}
public int getRestPort() {
return restPort;
}
public void setRestPort(int restPort) {
this.restPort = restPort;
}
public int getHawtioPort() {
return hawtioPort;
}
public void setHawtioPort(int hawtioPort) {
this.hawtioPort = hawtioPort;
}
public boolean getHawtio() {
return hawtio;
}
public void setHawtio(boolean hawtio) {
this.hawtio = hawtio;
}
public boolean getMonitoring() {
return monitoring;
}
public void setMonitoring(boolean monitoring) {
this.monitoring = monitoring;
}
public String getProxyUser() {
return proxyUser;
}
public void setProxyUser(String proxyUser) {
this.proxyUser = proxyUser;
}
public String getProxyHost() {
return proxyHost;
}
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public String getProxyPass() {
return proxyPass;
}
public void setProxyPass(String proxyPass) {
this.proxyPass = proxyPass;
}
public Integer getProxyPort() {
return proxyPort;
}
public void setProxyPort(Integer proxyPort) {
this.proxyPort = proxyPort;
}
public String getMode() {
return mode;
}
public void setMode(String mode) {
this.mode = mode;
}
} | apache-2.0 |
googleapis/java-appengine-admin | proto-google-cloud-appengine-admin-v1/src/main/java/com/google/appengine/v1/InstanceOrBuilder.java | 10347 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/appengine/v1/instance.proto
package com.google.appengine.v1;
public interface InstanceOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.appengine.v1.Instance)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Output only. Full path to the Instance resource in the API.
* Example: `apps/myapp/services/default/versions/v1/instances/instance-1`.
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The name.
*/
java.lang.String getName();
/**
*
*
* <pre>
* Output only. Full path to the Instance resource in the API.
* Example: `apps/myapp/services/default/versions/v1/instances/instance-1`.
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for name.
*/
com.google.protobuf.ByteString getNameBytes();
/**
*
*
* <pre>
* Output only. Relative name of the instance within the version.
* Example: `instance-1`.
* </pre>
*
* <code>string id = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The id.
*/
java.lang.String getId();
/**
*
*
* <pre>
* Output only. Relative name of the instance within the version.
* Example: `instance-1`.
* </pre>
*
* <code>string id = 2 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for id.
*/
com.google.protobuf.ByteString getIdBytes();
/**
*
*
* <pre>
* Output only. App Engine release this instance is running on.
* </pre>
*
* <code>string app_engine_release = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The appEngineRelease.
*/
java.lang.String getAppEngineRelease();
/**
*
*
* <pre>
* Output only. App Engine release this instance is running on.
* </pre>
*
* <code>string app_engine_release = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for appEngineRelease.
*/
com.google.protobuf.ByteString getAppEngineReleaseBytes();
/**
*
*
* <pre>
* Output only. Availability of the instance.
* </pre>
*
* <code>
* .google.appengine.v1.Instance.Availability availability = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The enum numeric value on the wire for availability.
*/
int getAvailabilityValue();
/**
*
*
* <pre>
* Output only. Availability of the instance.
* </pre>
*
* <code>
* .google.appengine.v1.Instance.Availability availability = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The availability.
*/
com.google.appengine.v1.Instance.Availability getAvailability();
/**
*
*
* <pre>
* Output only. Name of the virtual machine where this instance lives. Only applicable
* for instances in App Engine flexible environment.
* </pre>
*
* <code>string vm_name = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The vmName.
*/
java.lang.String getVmName();
/**
*
*
* <pre>
* Output only. Name of the virtual machine where this instance lives. Only applicable
* for instances in App Engine flexible environment.
* </pre>
*
* <code>string vm_name = 5 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for vmName.
*/
com.google.protobuf.ByteString getVmNameBytes();
/**
*
*
* <pre>
* Output only. Zone where the virtual machine is located. Only applicable for instances
* in App Engine flexible environment.
* </pre>
*
* <code>string vm_zone_name = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The vmZoneName.
*/
java.lang.String getVmZoneName();
/**
*
*
* <pre>
* Output only. Zone where the virtual machine is located. Only applicable for instances
* in App Engine flexible environment.
* </pre>
*
* <code>string vm_zone_name = 6 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for vmZoneName.
*/
com.google.protobuf.ByteString getVmZoneNameBytes();
/**
*
*
* <pre>
* Output only. Virtual machine ID of this instance. Only applicable for instances in
* App Engine flexible environment.
* </pre>
*
* <code>string vm_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The vmId.
*/
java.lang.String getVmId();
/**
*
*
* <pre>
* Output only. Virtual machine ID of this instance. Only applicable for instances in
* App Engine flexible environment.
* </pre>
*
* <code>string vm_id = 7 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for vmId.
*/
com.google.protobuf.ByteString getVmIdBytes();
/**
*
*
* <pre>
* Output only. Time that this instance was started.
* @OutputOnly
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return Whether the startTime field is set.
*/
boolean hasStartTime();
/**
*
*
* <pre>
* Output only. Time that this instance was started.
* @OutputOnly
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The startTime.
*/
com.google.protobuf.Timestamp getStartTime();
/**
*
*
* <pre>
* Output only. Time that this instance was started.
* @OutputOnly
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 8 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder();
/**
*
*
* <pre>
* Output only. Number of requests since this instance was started.
* </pre>
*
* <code>int32 requests = 9 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The requests.
*/
int getRequests();
/**
*
*
* <pre>
* Output only. Number of errors since this instance was started.
* </pre>
*
* <code>int32 errors = 10 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The errors.
*/
int getErrors();
/**
*
*
* <pre>
* Output only. Average queries per second (QPS) over the last minute.
* </pre>
*
* <code>float qps = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The qps.
*/
float getQps();
/**
*
*
* <pre>
* Output only. Average latency (ms) over the last minute.
* </pre>
*
* <code>int32 average_latency = 12 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The averageLatency.
*/
int getAverageLatency();
/**
*
*
* <pre>
* Output only. Total memory in use (bytes).
* </pre>
*
* <code>int64 memory_usage = 13 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The memoryUsage.
*/
long getMemoryUsage();
/**
*
*
* <pre>
* Output only. Status of the virtual machine where this instance lives. Only applicable
* for instances in App Engine flexible environment.
* </pre>
*
* <code>string vm_status = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The vmStatus.
*/
java.lang.String getVmStatus();
/**
*
*
* <pre>
* Output only. Status of the virtual machine where this instance lives. Only applicable
* for instances in App Engine flexible environment.
* </pre>
*
* <code>string vm_status = 14 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for vmStatus.
*/
com.google.protobuf.ByteString getVmStatusBytes();
/**
*
*
* <pre>
* Output only. Whether this instance is in debug mode. Only applicable for instances in
* App Engine flexible environment.
* </pre>
*
* <code>bool vm_debug_enabled = 15 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The vmDebugEnabled.
*/
boolean getVmDebugEnabled();
/**
*
*
* <pre>
* Output only. The IP address of this instance. Only applicable for instances in App
* Engine flexible environment.
* </pre>
*
* <code>string vm_ip = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The vmIp.
*/
java.lang.String getVmIp();
/**
*
*
* <pre>
* Output only. The IP address of this instance. Only applicable for instances in App
* Engine flexible environment.
* </pre>
*
* <code>string vm_ip = 16 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
*
* @return The bytes for vmIp.
*/
com.google.protobuf.ByteString getVmIpBytes();
/**
*
*
* <pre>
* Output only. The liveness health check of this instance. Only applicable for instances
* in App Engine flexible environment.
* </pre>
*
* <code>
* .google.appengine.v1.Instance.Liveness.LivenessState vm_liveness = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The enum numeric value on the wire for vmLiveness.
*/
int getVmLivenessValue();
/**
*
*
* <pre>
* Output only. The liveness health check of this instance. Only applicable for instances
* in App Engine flexible environment.
* </pre>
*
* <code>
* .google.appengine.v1.Instance.Liveness.LivenessState vm_liveness = 17 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*
* @return The vmLiveness.
*/
com.google.appengine.v1.Instance.Liveness.LivenessState getVmLiveness();
}
| apache-2.0 |
synk/armeria | src/main/java/com/linecorp/armeria/client/RemoteInvokerOptions.java | 7681 | /*
* Copyright 2015 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.client;
import static com.linecorp.armeria.client.RemoteInvokerOption.CONNECT_TIMEOUT;
import static com.linecorp.armeria.client.RemoteInvokerOption.EVENT_LOOP_GROUP;
import static com.linecorp.armeria.client.RemoteInvokerOption.IDLE_TIMEOUT;
import static com.linecorp.armeria.client.RemoteInvokerOption.MAX_CONCURRENCY;
import static com.linecorp.armeria.client.RemoteInvokerOption.MAX_FRAME_LENGTH;
import static com.linecorp.armeria.client.RemoteInvokerOption.POOL_HANDLER_DECORATOR;
import static com.linecorp.armeria.client.RemoteInvokerOption.TRUST_MANAGER_FACTORY;
import static java.util.Objects.requireNonNull;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import javax.net.ssl.TrustManagerFactory;
import com.linecorp.armeria.client.pool.KeyedChannelPoolHandler;
import com.linecorp.armeria.client.pool.PoolKey;
import com.linecorp.armeria.common.util.AbstractOptions;
import io.netty.channel.EventLoopGroup;
/**
* A set of {@link RemoteInvokerOption}s and their respective values.
*/
public class RemoteInvokerOptions extends AbstractOptions {
private static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofMillis(3200);
private static final Duration DEFAULT_IDLE_TIMEOUT = Duration.ofSeconds(10);
private static final int DEFAULT_MAX_FRAME_LENGTH = 10 * 1024 * 1024; // 10 MB
private static final Integer DEFAULT_MAX_CONCURRENCY = Integer.MAX_VALUE;
private static final RemoteInvokerOptionValue<?>[] DEFAULT_OPTION_VALUES = {
CONNECT_TIMEOUT.newValue(DEFAULT_CONNECTION_TIMEOUT),
IDLE_TIMEOUT.newValue(DEFAULT_IDLE_TIMEOUT),
MAX_FRAME_LENGTH.newValue(DEFAULT_MAX_FRAME_LENGTH),
MAX_CONCURRENCY.newValue(DEFAULT_MAX_CONCURRENCY)
};
/**
* The default {@link RemoteInvokerOptions}.
*/
public static final RemoteInvokerOptions DEFAULT = new RemoteInvokerOptions(DEFAULT_OPTION_VALUES);
/**
* Creates a new {@link RemoteInvokerOptions} with the specified {@link RemoteInvokerOptionValue}s.
*/
public static RemoteInvokerOptions of(RemoteInvokerOptionValue<?>... options) {
return new RemoteInvokerOptions(DEFAULT, options);
}
/**
* Returns the {@link RemoteInvokerOptions} with the specified {@link RemoteInvokerOptionValue}s.
*/
public static RemoteInvokerOptions of(Iterable<RemoteInvokerOptionValue<?>> options) {
return new RemoteInvokerOptions(DEFAULT, options);
}
private static <T> RemoteInvokerOptionValue<T> validateValue(RemoteInvokerOptionValue<T> optionValue) {
requireNonNull(optionValue, "value");
RemoteInvokerOption<?> option = optionValue.option();
T value = optionValue.value();
if (option == CONNECT_TIMEOUT) {
validateConnectionTimeout((Duration) value);
} else if (option == MAX_FRAME_LENGTH) {
validateMaxFrameLength((Integer) value);
} else if (option == IDLE_TIMEOUT) {
validateIdleTimeout((Duration) value);
} else if (option == MAX_CONCURRENCY) {
validateMaxConcurrency((Integer) value);
}
return optionValue;
}
private static int validateMaxFrameLength(int maxFrameLength) {
if (maxFrameLength <= 0) {
throw new IllegalArgumentException("maxFrameLength: " + maxFrameLength + " (expected: > 0)");
}
return maxFrameLength;
}
private static Duration validateConnectionTimeout(Duration connectionTimeout) {
requireNonNull(connectionTimeout, "connectionTimeout");
if (connectionTimeout.isNegative() || connectionTimeout.isZero()) {
throw new IllegalArgumentException(
"connectTimeout: " + connectionTimeout + " (expected: > 0)");
}
return connectionTimeout;
}
private static Duration validateIdleTimeout(Duration idleTimeout) {
requireNonNull(idleTimeout, "idleTimeout");
if (idleTimeout.isNegative()) {
throw new IllegalArgumentException(
"idleTimeout: " + idleTimeout + " (expected: >= 0)");
}
return idleTimeout;
}
private static int validateMaxConcurrency(int maxConcurrency) {
if (maxConcurrency <= 0) {
throw new IllegalArgumentException("maxConcurrency: " + maxConcurrency + " (expected: > 0)");
}
return maxConcurrency;
}
private RemoteInvokerOptions(RemoteInvokerOptionValue<?>... options) {
super(RemoteInvokerOptions::validateValue, options);
}
private RemoteInvokerOptions(RemoteInvokerOptions baseOptions, RemoteInvokerOptionValue<?>... options) {
super(RemoteInvokerOptions::validateValue, baseOptions, options);
}
private RemoteInvokerOptions(
RemoteInvokerOptions baseOptions, Iterable<RemoteInvokerOptionValue<?>> options) {
super(RemoteInvokerOptions::validateValue, baseOptions, options);
}
/**
* Returns the value of the specified {@link RemoteInvokerOption}.
*
* @return the value of the {@link RemoteInvokerOption}, or
* {@link Optional#empty()} if the default value of the specified {@link RemoteInvokerOption} is
* not available
*/
public <T> Optional<T> get(RemoteInvokerOption<T> option) {
return get0(option);
}
/**
* Returns the value of the specified {@link RemoteInvokerOption}.
*
* @return the value of the {@link RemoteInvokerOption}, or
* {@code defaultValue} if the specified {@link RemoteInvokerOption} is not set.
*/
public <T> T getOrElse(RemoteInvokerOption<T> option, T defaultValue) {
return getOrElse0(option, defaultValue);
}
/**
* Converts this {@link RemoteInvokerOptions} to a {@link Map}.
*/
public Map<RemoteInvokerOption<Object>, RemoteInvokerOptionValue<Object>> asMap() {
return asMap0();
}
public Duration connectTimeout() {
return getOrElse(CONNECT_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
}
public long connectTimeoutMillis() {
return connectTimeout().toMillis();
}
public Optional<EventLoopGroup> eventLoopGroup() {
return get(EVENT_LOOP_GROUP);
}
public Optional<TrustManagerFactory> trustManagerFactory() {
return get(TRUST_MANAGER_FACTORY);
}
public Duration idleTimeout() {
return getOrElse(IDLE_TIMEOUT, DEFAULT_IDLE_TIMEOUT);
}
public long idleTimeoutMillis() {
return idleTimeout().toMillis();
}
public int maxFrameLength() {
return getOrElse(MAX_FRAME_LENGTH, DEFAULT_MAX_FRAME_LENGTH);
}
public int maxConcurrency() {
return getOrElse(MAX_CONCURRENCY, DEFAULT_MAX_CONCURRENCY);
}
public Function<KeyedChannelPoolHandler<PoolKey>, KeyedChannelPoolHandler<PoolKey>> poolHandlerDecorator() {
return getOrElse(POOL_HANDLER_DECORATOR, Function.identity());
}
}
| apache-2.0 |
DirkBrand/Pokemaps | src/com/pokemaps/pokemaps/data/Item.java | 1859 | package com.pokemaps.pokemaps.data;
import java.io.Serializable;
import com.j256.ormlite.field.DatabaseField;
public class Item implements Serializable {
/**
* Model Class for Pokemon database table
*/
private static final long serialVersionUID = -8755734209725555655L;
public final static String ITEM_ID_FIELD_NAME = "item_id";
public final static String NAME_FIELD_NAME = "name";
public final static String DESCRIPTION_FIELD_NAME = "description";
public final static String IMAGE_ID_FIELD_NAME = "image_id";
public final static String EXTRA_VALUE_FIELD_NAME = "extra_value";
@DatabaseField(generatedId = true, columnName = ITEM_ID_FIELD_NAME)
private long id;
@DatabaseField(columnName = NAME_FIELD_NAME)
private String name;
@DatabaseField(columnName = IMAGE_ID_FIELD_NAME)
private int image_id;
@DatabaseField(columnName = DESCRIPTION_FIELD_NAME)
private String description;
@DatabaseField(columnName = EXTRA_VALUE_FIELD_NAME)
private int extra_value;
public Item() {}
public Item (String name, String description, int imageId) {
this.name = name;
this.description = description;
this.image_id = imageId;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getImageId() {
return image_id;
}
public void setImageId(int id) {
this.image_id = id;
}
public int getExtraValue() {
return extra_value;
}
public void setExtraValue(int val) {
this.extra_value = val;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
// Will be used by the ArrayAdapter in the ListView
@Override
public String toString() {
return name;
}
}
| apache-2.0 |
MrxMo/MDNavBarView | mnavbarviewlib/src/test/java/com/mrmo/mnavbarviewlib/ExampleUnitTest.java | 401 | package com.mrmo.mnavbarviewlib;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
sauloperez/sos | src/core/api/src/main/java/org/n52/sos/request/GetObservationRequest.java | 13142 | /**
* Copyright (C) 2013
* by 52 North Initiative for Geospatial Open Source Software GmbH
*
* Contact: Andreas Wytzisk
* 52 North Initiative for Geospatial Open Source Software GmbH
* Martin-Luther-King-Weg 24
* 48155 Muenster, Germany
* info@52north.org
*
* This program is free software; you can redistribute and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* This program is distributed WITHOUT ANY WARRANTY; even without the implied
* WARRANTY OF MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program (see gnu-gpl v2.txt). If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or
* visit the Free Software Foundation web page, http://www.fsf.org.
*/
package org.n52.sos.request;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.n52.sos.ogc.filter.ComparisonFilter;
import org.n52.sos.ogc.filter.SpatialFilter;
import org.n52.sos.ogc.filter.TemporalFilter;
import org.n52.sos.ogc.gml.time.TimeInstant;
import org.n52.sos.ogc.sos.Sos2Constants;
import org.n52.sos.ogc.sos.SosConstants;
import org.n52.sos.ogc.sos.SosConstants.SosIndeterminateTime;
import org.n52.sos.util.CollectionHelper;
import org.n52.sos.util.StringHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* SOS GetObservation request
*
* @since 4.0.0
*/
public class GetObservationRequest extends AbstractServiceRequest implements SpatialFeatureQueryRequest {
/**
* Request as String
*/
private String requestString;
/**
* SRID
*/
private int srid = -1;
/**
* Offerings list
*/
private List<String> offerings = Lists.newLinkedList();
/**
* Temporal filters list
*/
private List<TemporalFilter> temporalFilters = Lists.newLinkedList();
/**
* Procedures list
*/
private List<String> procedures = Lists.newLinkedList();
/**
* ObservedProperties list
*/
private List<String> observedProperties = Lists.newLinkedList();
/**
* FOI identifiers list
*/
private List<String> featureIdentifiers = Lists.newLinkedList();
/**
* Spatial filters list
*/
private SpatialFilter spatialFilter;
/**
* Result filters list
*/
private ComparisonFilter result;
/**
* Response format
*/
private String responseFormat;
/**
* Result model
*/
private String resultModel;
private Map<String, String> namespaces = Maps.newHashMap();
/**
* Response mode
*/
private String responseMode;
/*
* (non-Javadoc)
*
* @see org.n52.sos.request.AbstractSosRequest#getOperationName()
*/
@Override
public String getOperationName() {
return SosConstants.Operations.GetObservation.name();
}
/**
* Get temporal filters
*
* @return temporal filters
*/
public List<TemporalFilter> getTemporalFilters() {
return temporalFilters;
}
/**
* Set temporal filters
*
* @param temporalFilters
* temporal filters
*/
public void setTemporalFilters(List<TemporalFilter> temporalFilters) {
this.temporalFilters = temporalFilters;
}
/**
* Get FOI identifiers
*
* @return FOI identifiers
*/
@Override
public List<String> getFeatureIdentifiers() {
return featureIdentifiers;
}
/**
* Set FOI identifiers
*
* @param featureIdentifiers
* FOI identifiers
*/
@Override
public void setFeatureIdentifiers(List<String> featureIdentifiers) {
this.featureIdentifiers = featureIdentifiers;
}
/**
* Get observableProperties
*
* @return observableProperties
*/
public List<String> getObservedProperties() {
return observedProperties;
}
/**
* Set observedProperties
*
* @param observedProperties
* observedProperties
*/
public void setObservedProperties(List<String> observedProperties) {
this.observedProperties = observedProperties;
}
/**
* Get offerings
*
* @return offerings
*/
public List<String> getOfferings() {
return offerings;
}
/**
* Set offerings
*
* @param offerings
* offerings
*/
public void setOfferings(List<String> offerings) {
this.offerings = offerings;
}
/**
* Get procedures
*
* @return procedures
*/
public List<String> getProcedures() {
return procedures;
}
/**
* Set procedures
*
* @param procedures
* procedures
*/
public void setProcedures(List<String> procedures) {
this.procedures = procedures;
}
/**
* Get response format
*
* @return response format
*/
public String getResponseFormat() {
return responseFormat;
}
/**
* Set response format
*
* @param responseFormat
* response format
*/
public void setResponseFormat(String responseFormat) {
this.responseFormat = responseFormat;
}
/**
* Get response mode
*
* @return response mode
*/
public String getResponseMode() {
return responseMode;
}
/**
* Set response mode
*
* @param responseMode
* response mode
*/
public void setResponseMode(String responseMode) {
this.responseMode = responseMode;
}
/**
* Get result filters
*
* @return result filters
*/
public ComparisonFilter getResult() {
return result;
}
/**
* Set result filters
*
* @param result
* result filters
*/
public void setResult(ComparisonFilter result) {
this.result = result;
}
/**
* Get result model
*
* @return result model
*/
public String getResultModel() {
return resultModel;
}
/**
* Set result model
*
* @param resultModel
* result model
*/
public void setResultModel(String resultModel) {
this.resultModel = resultModel;
}
/**
* Get SRID
*
* @return SRID
*/
public int getSrid() {
return srid;
}
/**
* Set SRID
*
* @param srid
* SRID
*/
public void setSrid(int srid) {
this.srid = srid;
}
/**
* Get request as String
*
* @return request as String
*/
public String getRequestString() {
return requestString;
}
/**
* Set request as String
*
* @param requestString
* request as String
*/
public void setRequestString(String requestString) {
this.requestString = requestString;
}
/**
* Get spatial filter
*
* @return spatial filter
*/
@Override
public SpatialFilter getSpatialFilter() {
return spatialFilter;
}
/**
* Set spatial filter
*
* @param resultSpatialFilter
* spatial filter
*/
@Override
public void setSpatialFilter(SpatialFilter resultSpatialFilter) {
this.spatialFilter = resultSpatialFilter;
}
/**
* Create a copy of this request with defined observableProperties
*
* @param obsProps
* defined observableProperties
* @return SOS GetObservation request copy
*/
public GetObservationRequest copyOf(List<String> obsProps) {
GetObservationRequest res = new GetObservationRequest();
res.setTemporalFilters(this.temporalFilters);
res.setObservedProperties(obsProps);
res.setOfferings(this.offerings);
res.setProcedures(this.procedures);
res.setResponseFormat(this.responseFormat);
res.setResponseMode(this.responseMode);
res.setSpatialFilter(this.spatialFilter);
res.setResult(this.result);
res.setResultModel(this.resultModel);
res.setFeatureIdentifiers(this.featureIdentifiers);
res.setService(this.getService());
res.setSrid(this.srid);
res.setRequestString(this.requestString);
return res;
}
public void setNamespaces(Map<String, String> namespaces) {
this.namespaces = namespaces;
}
public Map<String, String> getNamespaces() {
return namespaces;
}
public boolean isSetOffering() {
if (offerings != null && !offerings.isEmpty()) {
return true;
}
return false;
}
public boolean isSetObservableProperty() {
if (observedProperties != null && !observedProperties.isEmpty()) {
return true;
}
return false;
}
public boolean isSetProcedure() {
if (procedures != null && !procedures.isEmpty()) {
return true;
}
return false;
}
@Override
public boolean isSetFeatureOfInterest() {
if (featureIdentifiers != null && !featureIdentifiers.isEmpty()) {
return true;
}
return false;
}
public boolean isSetTemporalFilter() {
if (temporalFilters != null && !temporalFilters.isEmpty()) {
return true;
}
return false;
}
@Override
public boolean isSetSpatialFilter() {
if (spatialFilter != null) {
return true;
}
return false;
}
public boolean hasFirstLatestTemporalFilter() {
for (TemporalFilter temporalFilter : temporalFilters) {
if (temporalFilter.getTime() instanceof TimeInstant) {
TimeInstant ti = (TimeInstant) temporalFilter.getTime();
if (ti.isSetSosIndeterminateTime()) {
return true;
}
}
}
return false;
}
public List<SosIndeterminateTime> getFirstLatestTemporalFilter() {
List<SosIndeterminateTime> tf = new LinkedList<SosIndeterminateTime>();
for (TemporalFilter temporalFilter : temporalFilters) {
if (temporalFilter.getTime() instanceof TimeInstant) {
TimeInstant ti = (TimeInstant) temporalFilter.getTime();
if (ti.isSetSosIndeterminateTime()) {
tf.add(ti.getSosIndeterminateTime());
}
}
}
return tf;
}
public List<TemporalFilter> getNotFirstLatestTemporalFilter() {
List<TemporalFilter> tf = new LinkedList<TemporalFilter>();
for (TemporalFilter temporalFilter : temporalFilters) {
if (temporalFilter.getTime() instanceof TimeInstant) {
TimeInstant ti = (TimeInstant) temporalFilter.getTime();
if (!ti.isSetSosIndeterminateTime()) {
tf.add(temporalFilter);
}
} else {
tf.add(temporalFilter);
}
}
return tf;
}
public boolean hasTemporalFilters() {
return temporalFilters != null && !temporalFilters.isEmpty();
}
public boolean isSetResultModel() {
return resultModel != null;
}
public boolean isEmpty() {
return !isSetOffering() && !isSetObservableProperty() && !isSetProcedure() && !isSetFeatureOfInterest()
&& !isSetTemporalFilter() && !isSetSpatialFilter();
}
@Override
public boolean hasSpatialFilteringProfileSpatialFilter() {
return isSetSpatialFilter()
&& getSpatialFilter().getValueReference().equals(
Sos2Constants.VALUE_REFERENCE_SPATIAL_FILTERING_PROFILE);
}
public boolean isSetRequestString() {
return StringHelper.isNotEmpty(getRequestString());
}
public boolean isSetSrid() {
return getSrid() <= 0;
}
public boolean isSetResult() {
return getResult() != null;
}
public boolean isSetResponseFormat() {
return StringHelper.isNotEmpty(getResponseFormat());
}
public boolean isSetNamespaces() {
return CollectionHelper.isNotEmpty(getNamespaces());
}
public boolean isSetResponseMode() {
return StringHelper.isNotEmpty(getResponseMode());
}
}
| apache-2.0 |
mygreen/xlsmapper | src/test/java/com/gh/mygreen/xlsmapper/fieldprocessor/AnnoSheetTest.java | 27519 | package com.gh.mygreen.xlsmapper.fieldprocessor;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static com.gh.mygreen.xlsmapper.TestUtils.*;
import static org.assertj.core.api.Assertions.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.gh.mygreen.xlsmapper.AnnotationInvalidException;
import com.gh.mygreen.xlsmapper.SheetNotFoundException;
import com.gh.mygreen.xlsmapper.XlsMapper;
import com.gh.mygreen.xlsmapper.annotation.XlsSheet;
import com.gh.mygreen.xlsmapper.annotation.XlsSheetName;
import com.gh.mygreen.xlsmapper.validation.MultipleSheetBindingErrors;
import com.gh.mygreen.xlsmapper.validation.SheetBindingErrors;
import com.gh.mygreen.xlsmapper.validation.SheetErrorFormatter;
/**
* アノテーション{@link XlsSheet}のテスト
*
* @since 2.0
* @author T.TSUCHIE
*
*/
public class AnnoSheetTest {
/**
* テスト結果ファイルの出力ディレクトリ
*/
private static File OUT_DIR;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
OUT_DIR = createOutDir();
}
/**
* 読み込み用のファイルの定義
*/
private File inputFile = new File("src/test/data/anno_Sheet.xlsx");
/**
* 出力用のテンプレートファイルの定義
*/
private File templateFile = new File("src/test/data/anno_Sheet_template.xlsx");
/**
* 出力用のファイル名の定義
*/
private String outFilename = "anno_Sheet_out.xlsx";
/**
* エラーメッセージのコンバーター
*/
private SheetErrorFormatter errorFormatter;
@Before
public void setUp() throws Exception {
this.errorFormatter = new SheetErrorFormatter();
}
/**
* 読み込みのテスト - シート名の指定
*/
@Test
public void test_load_sheet_name() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
SheetBindingErrors<NamedSheet> errors = mapper.loadDetail(in, NamedSheet.class);
NamedSheet sheet = errors.getTarget();
assertThat(sheet.sheetName, is("シート名(1)"));
}
}
@Test
public void test_load_sheet_name_notFound() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
assertThatThrownBy(() -> mapper.loadDetail(in, NamedSheet2.class))
.isInstanceOf(SheetNotFoundException.class)
.hasMessageContaining("シート名'シート名(2)'が見つかりません。");
}
}
@Test
public void test_loadMultple_sheet_name_notFound() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
assertThatThrownBy(() -> mapper.loadMultiple(in, NamedSheet2.class))
.isInstanceOf(SheetNotFoundException.class)
.hasMessageContaining("シート名'シート名(2)'が見つかりません。");
}
}
@Test
public void test_loadMultple_sheet_name_notFound2() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
assertThatThrownBy(() -> mapper.loadMultiple(in, new Class[]{NamedSheet2.class}))
.isInstanceOf(SheetNotFoundException.class)
.hasMessageContaining("シート名'シート名(2)'が見つかりません。");
}
}
/**
* シートが見つからなくてもスキップする設定
*
*/
@Test
public void test_load_sheet_skip_notFound() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true)
.setIgnoreSheetNotFound(true);
try(InputStream in = new FileInputStream(inputFile)) {
SheetBindingErrors<NamedSheet2> errors = mapper.loadDetail(in, NamedSheet2.class);
assertThat(errors).isNull();
}
}
/**
* シートが見つからなくてもスキップする設定
*
*/
@Test
public void testMultple_load_sheet_skip_notFound() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true)
.setIgnoreSheetNotFound(true);
try(InputStream in = new FileInputStream(inputFile)) {
MultipleSheetBindingErrors<NamedSheet2> errors = mapper.loadMultipleDetail(in, NamedSheet2.class);
assertThat(errors.getAll()).isEmpty();
}
}
/**
* シートが見つからなくてもスキップする設定
*
*/
@Test
public void testMultple_load_sheet_skip_notFound2() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true)
.setIgnoreSheetNotFound(true);
try(InputStream in = new FileInputStream(inputFile)) {
MultipleSheetBindingErrors<?> errors = mapper.loadMultipleDetail(in, new Class[]{NamedSheet2.class});
assertThat(errors.getAll()).isEmpty();
}
}
@Test
public void test_load_sheet_indexed() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
SheetBindingErrors<IndexedSheet> errors = mapper.loadDetail(in, IndexedSheet.class);
IndexedSheet sheet = errors.getTarget();
assertThat(sheet.sheetName, is("あいう"));
}
}
@Test
public void test_load_sheet_indexed_nofFound() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
assertThatThrownBy(() -> mapper.loadDetail(in, IndexedSheet2.class))
.isInstanceOf(SheetNotFoundException.class)
.hasMessageContaining("シート番号'10'が見つかりません。ワークブックにはシート数が'4'個しかありません。");
}
}
/**
* 正規表現指定 - シート1つ
*/
@Test
public void test_load_sheet_regexp_single() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
SheetBindingErrors<RegexpSheet> errors = mapper.loadDetail(in, RegexpSheet.class);
RegexpSheet sheet = errors.getTarget();
assertThat(sheet.sheetName, is("編集条件(1)"));
}
}
/**
* 正規表現指定 - シート1つ - シートが見つからない場合
*/
@Test
public void test_load_sheet_regexp_single_notFound() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
assertThatThrownBy(() -> mapper.loadDetail(in, RegexpSheet2.class))
.isInstanceOf(SheetNotFoundException.class)
.hasMessageContaining("シート名'チェック条件.+'が見つかりません。");
}
}
/**
* 正規表現指定 - シート複数
*/
@Test
public void test_load_sheetName_regexp_multiple() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
RegexpSheet[] sheet = mapper.loadMultiple(in, RegexpSheet.class);
assertThat(sheet[0].sheetName, is("編集条件(1)"));
assertThat(sheet[1].sheetName, is("編集条件(2)"));
}
}
/**
* アノテーションにシートの指定がない場合
*/
@Test
public void test_load_sheet_noSetting() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
assertThatThrownBy(() -> mapper.loadDetail(in, NoSettingSheet.class))
.isInstanceOf(AnnotationInvalidException.class)
.hasMessageContaining("において、アノテーション'@XlsSheet'の何れか属性[name or number or regex]の設定は必須です。");
}
}
/**
* シート用のアノテーションがない場合
*/
@Test
public void test_load_sheet_noGrant() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
assertThatThrownBy(() -> mapper.load(in, NoGrantSheet.class))
.isInstanceOf(AnnotationInvalidException.class)
.hasMessageContaining("において、アノテーション'@XlsSheet'が見つかりません。");
}
}
/**
* シート用のアノテーションがない場合
*/
@Test
public void test_loadMultiple_sheet_noGrant() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
assertThatThrownBy(() -> mapper.loadMultiple(in, NoGrantSheet.class))
.isInstanceOf(AnnotationInvalidException.class)
.hasMessageContaining("において、アノテーション'@XlsSheet'が見つかりません。");
}
}
/**
* シート用のアノテーションがない場合
*/
@Test
public void test_loadMultiple_sheet_noGrant2() throws Exception {
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
try(InputStream in = new FileInputStream(inputFile)) {
assertThatThrownBy(() -> mapper.loadMultiple(in, new Class[]{NoGrantSheet.class}))
.isInstanceOf(AnnotationInvalidException.class)
.hasMessageContaining("において、アノテーション'@XlsSheet'が見つかりません。");
}
}
/**
* 書き込みのテスト - シート名の指定
*/
@Test
public void test_save_sheet_name() throws Exception {
// テストデータの作成
final NamedSheet outSheet = new NamedSheet();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
mapper.save(template, out, outSheet);
}
// 書き込んだファイルを読み込み値の検証を行う。
try(InputStream in = new FileInputStream(outFile)) {
SheetBindingErrors<NamedSheet> errors = mapper.loadDetail(in, NamedSheet.class);
NamedSheet sheet = errors.getTarget();
assertThat(sheet.sheetName, is(outSheet.sheetName));
}
}
/**
* 書き込みのテスト - シート名の指定:指定したシートが存在しない。
*/
@Test
public void test_save_sheet_name_nofFound() throws Exception {
// テストデータの作成
final NamedSheet2 outSheet = new NamedSheet2();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
assertThatThrownBy(() -> mapper.save(template, out, outSheet))
.isInstanceOf(SheetNotFoundException.class)
.hasMessageContaining("シート名'シート名(2)'が見つかりません。");
}
}
/**
* 書き込みのテスト - シート名の指定:指定したシートが存在しない。
*/
@Test
public void test_saveMultiple_sheet_name_nofFound() throws Exception {
// テストデータの作成
final NamedSheet2 outSheet = new NamedSheet2();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
assertThatThrownBy(() -> mapper.saveMultiple(template, out, new Object[]{outSheet}))
.isInstanceOf(SheetNotFoundException.class)
.hasMessageContaining("シート名'シート名(2)'が見つかりません。");
}
}
/**
* 書き込みのテスト - シートが見つからなくてもスキップする設定
*/
@Test
public void test_save_sheet_skip_notFound() throws Exception {
// テストデータの作成
final NamedSheet2 outSheet = new NamedSheet2();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true)
.setIgnoreSheetNotFound(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
mapper.save(template, out, outSheet);
assertThat(outSheet.sheetName, is(nullValue()));
}
}
/**
* 書き込みのテスト - シートが見つからなくてもスキップする設定
*/
@Test
public void test_saveMultiple_sheet_skip_notFound() throws Exception {
// テストデータの作成
final NamedSheet2 outSheet = new NamedSheet2();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true)
.setIgnoreSheetNotFound(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
mapper.saveMultiple(template, out, new Object[]{outSheet});
assertThat(outSheet.sheetName, is(nullValue()));
}
}
/**
* 書き込みのテスト - インデックス指定
*/
@Test
public void test_save_sheet_indexed() throws Exception {
// テストデータの作成
final IndexedSheet outSheet = new IndexedSheet();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true)
.setIgnoreSheetNotFound(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
mapper.save(template, out, outSheet);
assertThat(outSheet.sheetName, is("あいう"));
}
}
/**
* 書き込みのテスト - インデックス指定。シートが見つからない場合
*/
@Test
public void test_save_sheet_indexed_notFound() throws Exception {
// テストデータの作成
final IndexedSheet2 outSheet = new IndexedSheet2();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
assertThatThrownBy(() -> mapper.save(template, out, outSheet))
.isInstanceOf(SheetNotFoundException.class)
.hasMessageContaining("シート番号'10'が見つかりません。ワークブックにはシート数が'4'個しかありません。");
}
}
/**
* 書き込みのテスト - 正規表現の指定。シートが1つ。
*/
@Test
public void test_save_sheet_regexp_single() throws Exception {
// テストデータの作成
final RegexpSheet outSheet = new RegexpSheet();
outSheet.sheetName = "編集条件(1)";
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
mapper.save(template, out, outSheet);
assertThat(outSheet.sheetName, is("編集条件(1)"));
}
}
/**
* 書き込みのテスト - 正規表現の指定。シートが見つからない場合
*/
@Test
public void test_save_sheet_regexp_single_notFound() throws Exception {
// テストデータの作成
final RegexpSheet2 outSheet = new RegexpSheet2();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
assertThatThrownBy(() -> mapper.save(template, out, outSheet))
.isInstanceOf(SheetNotFoundException.class)
.hasMessageContaining("シート名'チェック条件.+'が見つかりません。");
}
}
/**
* 書き込みのテスト - 正規表現の指定。複数のシートがヒットした場合。
*/
@Test
public void test_save_sheet_regexp_single_notFound2() throws Exception {
// テストデータの作成
final RegexpSheet outSheet = new RegexpSheet();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
assertThatThrownBy(() -> mapper.save(template, out, outSheet))
.isInstanceOf(SheetNotFoundException.class)
.hasMessageContaining("正規表現によるシート名'編集条件.+'に該当するシート[編集条件(1),編集条件(2)]が複数存在します。保存処理のときにはシートが一意に決まるように設定してください。");
}
}
/**
* 書き込みのテスト - 正規表現の指定。シートが2つ。
*/
@Test
public void test_save_sheetName_regexp_multiple() throws Exception {
// テストデータの作成
final RegexpSheet outSheet1 = new RegexpSheet();
outSheet1.sheetName = "編集条件(1)";
final RegexpSheet outSheet2 = new RegexpSheet();
outSheet2.sheetName = "編集条件(2)";
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
mapper.saveMultiple(template, out, new Object[]{outSheet1, outSheet2});
assertThat(outSheet1.sheetName, is("編集条件(1)"));
assertThat(outSheet2.sheetName, is("編集条件(2)"));
}
}
/**
* 書き込みのテスト - アノテーションにシートの指定がない場合
*/
@Test
public void test_save_sheet_noSetting() throws Exception {
// テストデータの作成
final NoSettingSheet outSheet = new NoSettingSheet();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
assertThatThrownBy(() -> mapper.save(template, out, outSheet))
.isInstanceOf(AnnotationInvalidException.class)
.hasMessageContaining("において、アノテーション'@XlsSheet'の何れか属性[name or number or regex]の設定は必須です。");
}
}
/**
* 書き込みのテスト - アノテーションにシートの指定がない場合
*/
@Test
public void test_saveMultiple_sheet_noSetting() throws Exception {
// テストデータの作成
final NoSettingSheet outSheet = new NoSettingSheet();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
assertThatThrownBy(() -> mapper.saveMultiple(template, out, new Object[]{outSheet}))
.isInstanceOf(AnnotationInvalidException.class)
.hasMessageContaining("において、アノテーション'@XlsSheet'の何れか属性[name or number or regex]の設定は必須です。");
}
}
/**
* 書き込みのテスト - アノテーション {@literal @XlsSheet}のが付与されていない
* @since 2.0
*/
@Test
public void test_save_sheet_notGrant() throws Exception {
// テストデータの作成
final NoGrantSheet outSheet = new NoGrantSheet();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
assertThatThrownBy(() -> mapper.save(template, out, outSheet))
.isInstanceOf(AnnotationInvalidException.class)
.hasMessageContaining("において、アノテーション'@XlsSheet'が見つかりません。");
}
}
/**
* 書き込みのテスト - アノテーション {@literal @XlsSheet}のが付与されていない
* @since 2.0
*/
@Test
public void test_saveMultiple_sheet_notGrant() throws Exception {
// テストデータの作成
final NoGrantSheet outSheet = new NoGrantSheet();
// ファイルへの書き込み
XlsMapper mapper = new XlsMapper();
mapper.getConfiguration().setContinueTypeBindFailure(true);
File outFile = new File(OUT_DIR, outFilename);
try(InputStream template = new FileInputStream(templateFile);
OutputStream out = new FileOutputStream(outFile)) {
assertThatThrownBy(() -> mapper.saveMultiple(template, out, new Object[]{outSheet}))
.isInstanceOf(AnnotationInvalidException.class)
.hasMessageContaining("において、アノテーション'@XlsSheet'が見つかりません。");
}
}
/**
* 名前によるシート指定
*
*/
@XlsSheet(name="シート名(1)")
private static class NamedSheet {
@XlsSheetName
private String sheetName;
}
/**
* 名前によるシート指定 - 存在しないシート
*
*/
@XlsSheet(name="シート名(2)")
private static class NamedSheet2 {
@XlsSheetName
private String sheetName;
}
/**
* インデックス番号によるシート指定
*
*/
@XlsSheet(number=1)
private static class IndexedSheet {
@XlsSheetName
private String sheetName;
}
/**
* インデックス番号によるシート指定 - 存在しないインデックス
*
*/
@XlsSheet(number=10)
private static class IndexedSheet2 {
@XlsSheetName
private String sheetName;
}
/**
* 正規表現によるシート指定
*
*/
@XlsSheet(regex="編集条件.+")
private static class RegexpSheet {
@XlsSheetName
private String sheetName;
}
/**
* 正規表現によるシート指定 - 存在しない名前
*
*/
@XlsSheet(regex="チェック条件.+")
private static class RegexpSheet2 {
@XlsSheetName
private String sheetName;
}
/**
* シートの設定が何もされていない場合
*
*/
@XlsSheet
private static class NoSettingSheet {
@XlsSheetName
private String sheetName;
}
/**
* シートのアノテーションが設定されていない場合
*
*/
private static class NoGrantSheet {
@XlsSheetName
private String sheetName;
}
}
| apache-2.0 |
motorina0/flowable-engine | modules/flowable-form-engine/src/main/java/org/flowable/form/engine/impl/cmd/GetTableCountCmd.java | 1089 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.form.engine.impl.cmd;
import java.io.Serializable;
import java.util.Map;
import org.flowable.form.engine.impl.interceptor.Command;
import org.flowable.form.engine.impl.interceptor.CommandContext;
/**
* @author Tom Baeyens
*/
public class GetTableCountCmd implements Command<Map<String, Long>>, Serializable {
private static final long serialVersionUID = 1L;
public Map<String, Long> execute(CommandContext commandContext) {
return commandContext.getTableDataManager().getTableCount();
}
}
| apache-2.0 |
motorina0/flowable-engine | modules/flowable-process-validation/src/main/java/org/flowable/validation/validator/Constraints.java | 1218 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.validation.validator;
/**
* @author Erik Winlof
*/
public class Constraints {
/**
* Max length database field ACT_RE_PROCDEF.CATEGORY
*/
public static final int BPMN_MODEL_TARGET_NAMESPACE_MAX_LENGTH = 255;
/**
* Max length database field ACT_RE_PROCDEF.KEY
*/
public static final int PROCESS_DEFINITION_ID_MAX_LENGTH = 255;
/**
* Max length database field ACT_RE_PROCDEF.NAME
*/
public static final int PROCESS_DEFINITION_NAME_MAX_LENGTH = 255;
/**
* Max length of database field ACT_RE_PROCDEF.DESCRIPTION
*/
public static final int PROCESS_DEFINITION_DOCUMENTATION_MAX_LENGTH = 2000;
}
| apache-2.0 |
avrecko/weld-guiceconfig | test/weld/guiceconfig/AbstractGuiceConfigTest.java | 2312 | /*
* Copyright (C) 2010 Alen Vrecko
*
* 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 weld.guiceconfig;
import com.google.inject.Module;
import junit.framework.TestCase;
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import java.lang.annotation.Annotation;
import java.util.Set;
/**
* Infrastructure for tests. See {@link weld.guiceconfig.basics.BasicTest} for usage example.
*
* @author Alen Vrecko
*/
public abstract class AbstractGuiceConfigTest extends TestCase {
protected BeanManager manager;
Weld weld;
protected abstract Iterable<? extends Module> getModules();
@Override
public void setUp() {
GuiceConfigTestModule.register(getModules());
weld = new Weld();
WeldContainer container = weld.initialize();
manager = container.getBeanManager();
}
@Override
public void tearDown() {
weld.shutdown();
}
public <T> T getReference(Class<T> clazz, Annotation... bindings) {
Set<Bean<?>> beans = manager.getBeans(clazz, bindings);
if (beans.isEmpty()) {
throw new RuntimeException("No bean found with class: " + clazz + " and bindings " + bindings.toString());
} else if (beans.size() != 1) {
StringBuilder bs = new StringBuilder("[");
for (Annotation a : bindings) {
bs.append(a.toString() + ",");
}
bs.append("]");
throw new RuntimeException("More than one bean found with class: " + clazz + " and bindings " + bs);
}
Bean bean = beans.iterator().next();
return (T) bean.create(manager.createCreationalContext(bean));
}
}
| apache-2.0 |
atmelino/JATexperimental | src/jat/coreNOSA/cm/eom/TwoBodyCSI.java | 4544 | /* JAT: Java Astrodynamics Toolkit
*
* Copyright (c) 2003 National Aeronautics and Space Administration. All rights reserved.
*
* This file is part of JAT. JAT is free software; you can
* redistribute it and/or modify it under the terms of the
* NASA Open Source Agreement
*
*
* 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
* NASA Open Source Agreement for more details.
*
* You should have received a copy of the NASA Open Source Agreement
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
package jat.coreNOSA.cm.eom;
import jat.coreNOSA.algorithm.VectorTimeFunction;
import jat.coreNOSA.algorithm.integrators.Derivatives;
import jat.coreNOSA.cm.KeplerElements;
import jat.coreNOSA.cm.TwoBody;
import jat.coreNOSA.math.MatrixVector.data.VectorN;
/**
* Equations of motion for a powered spacecraft with constant specific impulse
* in the force field of the two-body problem
*
* @author Tobias Berthold
* @version 1.0
*/
public class TwoBodyCSI extends TwoBody implements Derivatives /*, Printable*/
{
int n = 7;
double T; // Thrust magnitude (parameter but always max when on)
double Isp; // Specific Impulse
double c; // Exhaust velocity
double g0 = 0.00981;
//double b=-T/c;
VectorTimeFunction u; // thrust direction
public VectorN rvm; // vector containing position, velocity, and mass
/** Create the equations of motion for a spacecraft with a constant specific
* impulse engine in a two-body force field. The initial state of the spacecraft
* is given by a state on a two-body orbit. The thrust direction u is a callback
* function that the user must implement.
* @param k Orbital elements of the initial state
* @param mu
* @param m initial mass in kg
* @param u thrust direction at a given time
* @param T maximum thrust magnitude in kg*m/s^2
* @param Isp Specific impulse in seconds
*/
public TwoBodyCSI(KeplerElements k, double mu, double m, VectorTimeFunction u, double T, double Isp)
{
super(mu, k);
this.u = u;
this.Isp = Isp;
this.c = Isp * g0;
this.T = T;
rvm = new VectorN(7);
rvm.x[0] = rv.x[0];
rvm.x[1] = rv.x[1];
rvm.x[2] = rv.x[2];
rvm.x[3] = rv.x[3];
rvm.x[4] = rv.x[4];
rvm.x[5] = rv.x[5];
rvm.x[6] = m;
}
public double[] derivs(double t, double[] x_)
{
double x = x_[0], y = x_[1], z = x_[2];
double vx = x_[3], vy = x_[4], vz = x_[5];
double m = x_[6];
double dxdt[] = new double[n];
double ux, uy, uz; // components of thrust direction vector
double r = Math.sqrt(x * x + y * y + z * z);
double rcubed = r * r * r;
double muorc = -1.0 * this.mu / rcubed;
// Terms
//r = Math.sqrt(x * x + y * y + z * z);
//r3 = r * r * r;
//T = Math.sqrt(Tx * Tx + Ty * Ty + Tz * Tz);
// get thrust direction for given state and time
VectorN nxf = new VectorN(x_);
VectorN cf = u.evaluate(nxf, t);
//cf.print();
ux = cf.x[0];
uy = cf.x[1];
uz = cf.x[2];
// Derivatives
dxdt[0] = vx;
dxdt[1] = vy;
dxdt[2] = vz;
dxdt[3] = muorc * x + T/m * ux ;
dxdt[4] = muorc * y + T/m * uy ;
dxdt[5] = muorc * z + T/m * uz ;
dxdt[6] = -T / c;
return dxdt;
}
}
/*
public double[] integrate_TCT(double[] x0, double t_0, double t_s1, double t_s2, double t, double T)
{
double[] x;
// Thrust arc
if ( t<=t_s1 )
{
x=integrate(x0, t_0, t, T);
}
else
{
x=integrate(x0, t_0, t_s1, T);
// Coast arc
if ( t<=t_s2 )
x=integrate(x, t_s1, t, 0.);
else
{
x=integrate(x, t_s1, t_s2, 0.);
// Thrust arc
x=integrate(x, t_s2, t, T);
}
}
//myutil.print_Matrix(new Matrix(x,1).transpose(),"state x");
return x;
}
double[] integrate(double[] x0, double t_start, double t_final, double T)
{
this.T=T;
return integrate(x0, t_start, t_final);
}
double[] integrate(double[] x0, double t_start, double t_f)
{
double[] x,tmp_x0=new double[n];
myutil.copy(x0, tmp_x0, n);
x=super.integrate(tmp_x0, t_start, t_f);
return x;
}
public double switching_function(double[] x0, double t_0, double t_s1, double t_s2, double t_s, double T)
{
double[] x_=integrate_TCT(x0, t_0, t_s1, t_s2, t_s, T);
double x=x_[0],y=x_[1],z=x_[2],vx=x_[3],vy=x_[4],vz=x_[5],m=x_[6];
double lx=x_[7],ly=x_[8],lz=x_[9],lvx=x_[10],lvy=x_[11],lvz=x_[12],lm=x_[13];
double lv=Math.sqrt(lvx*lvx+lvy*lvy+lvz*lvz);
double c=Isp*g0;
return lv/m-lm/c;
}
*/
| apache-2.0 |
LittleLazyCat/TXEYXXK | perfect-ssm/src/test/java/test/simpleTest.java | 1273 | package test;
import com.ssm.promotion.core.util.MD5Util;
import org.junit.Test;
/**
* Created by 13 on 2017/3/30.
*/
public class simpleTest {
/**
* 得到MD5加密的内容
*/
@Test
public void md5Test() {
System.out.println(MD5Util.MD5Encode("perfect-ssm-secret", "UTF-8"));
//dce781f1a0189c9cf24e8b3a831fe078
}
/**
* 通过substring()获取文件名
*/
@Test
public void subStringTest() {
//通过substring()获取文件名
String url = "https://s.doubanio.com/f/shire/5522dd1f5b742d1e1394a17f44d590646b63871d/pics/book-default-medium.gif";
url = url.substring(url.lastIndexOf("/") + 1);
System.out.println(url);
String ss = "qrscene_123erqwerqwe";
System.out.println(ss.substring(0, 8));
}
@Test
public void arrayTest() {
String ids = "12,";
String idss = "12,22,32,";
String[] idsStr = ids.split(",");
String[] idsStrs = idss.split(",");
System.out.println(idsStr.length);
System.out.println(idsStrs.length);
}
@Test
public void dateTest() {
String s = "2015-09-15 12:59:28";
String ss = s.replace("09-15", "09-31");
System.out.println(ss);
}
}
| apache-2.0 |
OpenUniversity/ovirt-engine | backend/manager/modules/extensions-manager/src/main/java/org/ovirt/engine/core/extensions/mgr/ExtensionsManager.java | 16708 | package org.ovirt.engine.core.extensions.mgr;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Observable;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoadException;
import org.jboss.modules.ModuleLoader;
import org.ovirt.engine.api.extensions.Base;
import org.ovirt.engine.api.extensions.ExtKey;
import org.ovirt.engine.api.extensions.ExtMap;
import org.ovirt.engine.api.extensions.Extension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is responsible for loading the required {@code Configuration} in order to create an extension. It holds
* the logic of ordering and solving conflicts during loading the configuration
*/
public class ExtensionsManager extends Observable {
private static final Logger log = LoggerFactory.getLogger(ExtensionsManager.class);
private static final Logger traceLog = LoggerFactory.getLogger(ExtensionsManager.class.getName() + ".trace");
public static final ExtKey TRACE_LOG_CONTEXT_KEY = new ExtKey("EXTENSION_MANAGER_TRACE_LOG",
Logger.class,
"863db666-3ea7-4751-9695-918a3197ad83");
public static final ExtKey CAUSE_OUTPUT_KEY = new ExtKey("EXTENSION_MANAGER_CAUSE_OUTPUT_KEY", Throwable.class, "894e1c86-518b-40a2-a92b-29ea1eb0403d");
private static interface BindingsLoader {
ExtensionProxy load(Properties props) throws Exception;
}
private static class JBossBindingsLoader implements BindingsLoader {
private Map<String, Module> loadedModules = new HashMap<>();
private Module loadModule(String moduleSpec) {
// If the module was not already loaded, load it
try {
Module module = loadedModules.get(moduleSpec);
if (module == null) {
ModuleLoader loader = ModuleLoader.forClass(this.getClass());
if (loader == null) {
throw new ConfigurationException(String.format("The module '%1$s' cannot be loaded as the module system isn't enabled.",
moduleSpec));
}
module = loader.loadModule(ModuleIdentifier.fromString(moduleSpec));
loadedModules.put(moduleSpec, module);
}
return module;
} catch (ModuleLoadException exception) {
throw new ConfigurationException(String.format("The module '%1$s' cannot be loaded: %2$s", moduleSpec, exception.getMessage()),
exception);
}
}
private <T extends Class> T lookupService(Module module, T serviceInterface, String serviceClassName) {
T serviceClass = null;
for (Object service : module.loadService(serviceInterface)) {
if (service.getClass().getName().equals(serviceClassName)) {
serviceClass = (T)service.getClass();
break;
}
}
if (serviceClass == null) {
throw new ConfigurationException(String.format("The module '%1$s' does not contain the service '%2$s'.",
module.getIdentifier().getName(),
serviceClassName));
}
return serviceClass;
}
public ExtensionProxy load(Properties props) throws Exception {
Module module = loadModule(
props.getProperty(Base.ConfigKeys.BINDINGS_JBOSSMODULE_MODULE)
);
return new ExtensionProxy(
module.getClassLoader(),
lookupService(
module,
Extension.class,
props.getProperty(Base.ConfigKeys.BINDINGS_JBOSSMODULE_CLASS)
).newInstance()
);
}
}
private static class ExtensionEntry {
private static int extensionNameIndex = 0;
private String name;
private File file;
private boolean enabled;
private boolean initialized;
private ExtensionProxy extension;
private ExtensionEntry(Properties props, File file) {
this.file = file;
this.name = props.getProperty(
Base.ConfigKeys.NAME,
String.format("__unamed_%1$03d__", extensionNameIndex++)
);
this.enabled = Boolean.valueOf(props.getProperty(Base.ConfigKeys.ENABLED, "true"));
}
private String getFileName() {
return file != null ? file.getAbsolutePath() : "N/A";
}
}
private static final Map<String, BindingsLoader> bindingsLoaders = new HashMap<>();
static {
bindingsLoaders.put(Base.ConfigBindingsMethods.JBOSSMODULE, new JBossBindingsLoader());
};
private ConcurrentMap<String, ExtensionEntry> loadedEntries = new ConcurrentHashMap<>();
private ConcurrentMap<String, ExtensionEntry> initializedEntries = new ConcurrentHashMap<>();
private ExtMap globalContext = new ExtMap().mput(Base.GlobalContextKeys.EXTENSIONS, new ArrayList<ExtMap>());
public String load(Properties configuration) {
return loadImpl(configuration, null);
}
public String load(File file) {
try (
InputStream is = new FileInputStream(file);
Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
) {
Properties props = new Properties();
props.load(reader);
return loadImpl(props, file);
} catch (IOException exception) {
throw new ConfigurationException(String.format("Can't load object configuration file '%1$s': %2$s",
file.getAbsolutePath(), exception.getMessage()), exception);
}
}
private void dumpConfig(ExtensionProxy extension) {
Logger traceLogger = extension.getContext().<Logger> get(TRACE_LOG_CONTEXT_KEY);
if (traceLogger.isDebugEnabled()) {
Collection sensitive = extension.getContext().<Collection>get(Base.ContextKeys.CONFIGURATION_SENSITIVE_KEYS);
traceLogger.debug("Config BEGIN");
for (Map.Entry<Object, Object> entry : extension.getContext().<Properties>get(Base.ContextKeys.CONFIGURATION).entrySet()) {
traceLogger.debug(
String.format(
"%s: %s",
entry.getKey(),
sensitive.contains(entry.getKey()) ? "***" : entry.getValue()
)
);
}
traceLogger.debug("Config END");
}
}
private Collection<String> splitString(String s) {
return new ArrayList<>(Arrays.asList(s.trim().split("\\s*,\\s*", 0)));
}
private synchronized String loadImpl(Properties props, File confFile) {
ExtensionEntry entry = new ExtensionEntry(props, confFile);
if (!entry.enabled) {
return null;
}
ExtensionEntry alreadyLoadedEntry = loadedEntries.get(entry.name);
if (alreadyLoadedEntry != null) {
throw new ConfigurationException(String.format(
"Could not load the configuration '%1$s' from file %2$s. A configuration with the same name was already loaded from file %3$s",
entry.name,
entry.getFileName(),
alreadyLoadedEntry.getFileName()
));
}
try {
entry.extension = loadExtension(props);
entry.extension.getContext().mput(
Base.ContextKeys.GLOBAL_CONTEXT,
globalContext
).mput(
TRACE_LOG_CONTEXT_KEY,
traceLog
).mput(
Base.ContextKeys.INTERFACE_VERSION_MIN,
0
).mput(
Base.ContextKeys.INTERFACE_VERSION_MAX,
Base.INTERFACE_VERSION_CURRENT
).mput(
Base.ContextKeys.LOCALE,
Locale.getDefault().toString()
).mput(
Base.ContextKeys.CONFIGURATION_FILE,
entry.file == null ? null : entry.file.getAbsolutePath()
).mput(
Base.ContextKeys.CONFIGURATION,
props
).mput(
Base.ContextKeys.CONFIGURATION_SENSITIVE_KEYS,
splitString(props.getProperty(Base.ConfigKeys.SENSITIVE_KEYS, ""))
).mput(
Base.ContextKeys.INSTANCE_NAME,
entry.name
).mput(
Base.ContextKeys.PROVIDES,
splitString(props.getProperty(Base.ConfigKeys.PROVIDES, ""))
);
log.info("Loading extension '{}'", entry.name);
ExtMap output = entry.extension.invoke(
new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Base.InvokeCommands.LOAD
)
);
log.info("Extension '{}' loaded", entry.name);
entry.extension.getContext().put(
TRACE_LOG_CONTEXT_KEY,
LoggerFactory.getLogger(
String.format(
"%1$s.%2$s.%3$s",
traceLog.getName(),
entry.extension.getContext().get(Base.ContextKeys.EXTENSION_NAME),
entry.extension.getContext().get(Base.ContextKeys.INSTANCE_NAME)
)
)
);
if (output.<Integer>get(Base.InvokeKeys.RESULT) != Base.InvokeResult.SUCCESS) {
throw new RuntimeException(
String.format("Invoke of LOAD returned with error code: %1$s",
output.<Integer>get(Base.InvokeKeys.RESULT)
)
);
}
} catch (Exception e) {
throw new RuntimeException(String.format("Error loading extension '%1$s': %2$s", entry.name, e.getMessage()), e);
}
loadedEntries.put(entry.name, entry);
dumpConfig(entry.extension);
setChanged();
notifyObservers();
return entry.name;
}
public ExtMap getGlobalContext() {
return globalContext;
}
public List<ExtensionProxy> getExtensionsByService(String provides) {
List<ExtensionProxy> results = new ArrayList<>();
for (ExtensionEntry entry : initializedEntries.values()) {
if (entry.extension.getContext().<Collection<String>> get(Base.ContextKeys.PROVIDES).contains(provides)) {
results.add(entry.extension);
}
}
return results;
}
public ExtensionProxy getExtensionByName(String name) throws ConfigurationException {
if (name == null) {
throw new ConfigurationException(String.format("Extension was not specified"));
}
ExtensionEntry entry = initializedEntries.get(name);
if (entry == null) {
throw new ConfigurationException(String.format("Extension %1$s could not be found", name));
}
return entry.extension;
}
public List<ExtensionProxy> getLoadedExtensions() {
List<ExtensionProxy> results = new ArrayList<>(loadedEntries.size());
for (ExtensionEntry entry : loadedEntries.values()) {
results.add(entry.extension);
}
return results;
}
public List<ExtensionProxy> getExtensions() {
List<ExtensionProxy> results = new ArrayList<>(initializedEntries.size());
for (ExtensionEntry entry : initializedEntries.values()) {
results.add(entry.extension);
}
return results;
}
public ExtensionProxy initialize(String extensionName) {
ExtensionEntry entry = loadedEntries.get(extensionName);
if (entry == null) {
throw new RuntimeException(String.format("No extensioned with instance name %1$s could be found",
extensionName));
}
try {
log.info("Initializing extension '{}'", entry.name);
ExtMap output = entry.extension.invoke(
new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Base.InvokeCommands.INITIALIZE
)
);
log.info("Extension '{}' initialized", entry.name);
} catch (Exception ex) {
log.error("Error in activating extension '{}': {}", entry.name, ex.getMessage());
if (log.isDebugEnabled()) {
log.debug(ex.toString(), ex);
}
throw new RuntimeException(ex);
}
entry.initialized = true;
initializedEntries.put(extensionName, entry);
synchronized (globalContext) {
globalContext.<Collection<ExtMap>> get(Base.GlobalContextKeys.EXTENSIONS).add(
new ExtMap().mput(
Base.ExtensionRecord.INSTANCE_NAME,
entry.extension.getContext().get(Base.ContextKeys.INSTANCE_NAME)
).mput(
Base.ExtensionRecord.PROVIDES,
entry.extension.getContext().get(Base.ContextKeys.PROVIDES)
).mput(
Base.ExtensionRecord.CLASS_LOADER,
entry.extension.getClassLoader()
).mput(
Base.ExtensionRecord.EXTENSION,
entry.extension.getExtension()
).mput(
Base.ExtensionRecord.CONTEXT,
entry.extension.getContext()
)
);
}
setChanged();
notifyObservers();
return entry.extension;
}
private ExtensionProxy loadExtension(Properties props) throws Exception {
BindingsLoader loader = bindingsLoaders.get(props.getProperty(Base.ConfigKeys.BINDINGS_METHOD));
if (loader == null) {
throw new ConfigurationException(String.format("Invalid binding method '%1$s'.",
props.getProperty(Base.ConfigKeys.BINDINGS_METHOD)));
}
return loader.load(props);
}
public void dump() {
log.info("Start of enabled extensions list");
for (ExtensionEntry entry : loadedEntries.values()) {
if (entry.extension != null) {
ExtMap context = entry.extension.getContext();
log.info("Instance name: '{}', Extension name: '{}', Version: '{}', Notes: '{}', License: '{}', Home: '{}', Author '{}', Build interface Version: '{}', File: '{}', Initialized: '{}'",
emptyIfNull(context.get(Base.ContextKeys.INSTANCE_NAME)),
emptyIfNull(context.get(Base.ContextKeys.EXTENSION_NAME)),
emptyIfNull(context.get(Base.ContextKeys.VERSION)),
emptyIfNull(context.get(Base.ContextKeys.EXTENSION_NOTES)),
emptyIfNull(context.get(Base.ContextKeys.LICENSE)),
emptyIfNull(context.get(Base.ContextKeys.HOME_URL)),
emptyIfNull(context.get(Base.ContextKeys.AUTHOR)),
emptyIfNull(context.get(Base.ContextKeys.BUILD_INTERFACE_VERSION)),
entry.getFileName(),
entry.initialized
);
}
}
log.info("End of enabled extensions list");
}
private Object emptyIfNull(Object value) {
return value == null ? "" : value;
}
}
| apache-2.0 |
ralgond/injectsocks | src/main/java/ht/misc/injectsocks/InjectSockstTransformerImpl.java | 5217 | /**
* 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 ht.misc.injectsocks;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
/**
* @author tenghuang (ht201509@163.com)
*/
public class InjectSockstTransformerImpl implements ClassFileTransformer{
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
if (!ConfigReader.isNeedInject(className)) {
return classfileBuffer;
}
System.out.println("INFO: Injecting class: "+className);
return inject(classfileBuffer);
}
public byte[] inject(byte[] classfileBuffer) {
try {
ClassReader cr = new ClassReader(classfileBuffer);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
ArrayList<AbstractInsnNode> injectPos = new ArrayList<AbstractInsnNode>();
@SuppressWarnings("unchecked")
List<MethodNode> methods = (List<MethodNode>)cn.methods;
for (int i = 0; i < methods.size(); ++i) {
MethodNode method = methods.get(i);
InsnList instructions = method.instructions;
if (instructions.size() <= 0)
continue;
//System.out.println("Method: "+method.name+" ");
for (int j = 0; j < instructions.size(); ++j) {
AbstractInsnNode insn = (AbstractInsnNode)instructions.get(j);
//System.out.println("\tInsn: opc="+OpcodeUtil.getOpcode(insn.getOpcode())+", type="+insn.getType());
if (insn.getType() == AbstractInsnNode.METHOD_INSN) {
MethodInsnNode min = (MethodInsnNode)insn;
//System.out.printf("\t\towner=%s, name=%s, desc=%s\n", min.owner, min.name, min.desc);
if (min.owner.equals("java/net/Socket") && min.name.equals("<init>") && min.desc.equals("()V")) {
min.desc = "(Ljava/net/Proxy;)V";
injectPos.add(min);
}
}
}
for (int k = 0; k < injectPos.size(); k++) {
AbstractInsnNode pos = injectPos.get(k);
MethodInsnNode newMin = new MethodInsnNode(
Opcodes.INVOKESTATIC,
"ht/misc/injectsocks/ProxyManager",
"getProxy",
"()Ljava/net/Proxy;",
false);
instructions.insertBefore(pos, newMin);
}
}
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cn.accept(cw);
byte[] injectedClassfileBuffer = cw.toByteArray();
System.out.printf("INFO: classfileBuffer.legnth=%d, injectedClassfileBuffer.length=%d\n",
classfileBuffer.length, injectedClassfileBuffer.length);
return injectedClassfileBuffer;
} catch (Throwable e) {
e.printStackTrace();
return classfileBuffer;
}
}
public void printClassByteCode(byte code[]) {
ClassReader cr = new ClassReader(code);
ClassNode cn = new ClassNode();
cr.accept(cn, 0);
@SuppressWarnings("unchecked")
List<MethodNode> methods = (List<MethodNode>)cn.methods;
for (int i = 0; i < methods.size(); ++i) {
MethodNode method = methods.get(i);
InsnList instructions = method.instructions;
if (instructions.size() <= 0)
continue;
System.out.println("Method: "+method.name+" ");
for (int j = 0; j < instructions.size(); ++j) {
AbstractInsnNode insn = (AbstractInsnNode)instructions.get(j);
System.out.println("\tInsn: opc="+OpcodeUtil.getOpcode(insn.getOpcode())+", type="+insn.getType());
if (insn.getType() == AbstractInsnNode.METHOD_INSN) {
MethodInsnNode min = (MethodInsnNode)insn;
System.out.printf("\t\towner=%s, name=%s, desc=%s\n", min.owner, min.name, min.desc);
}
}
}
}
}
| apache-2.0 |
googleads/google-ads-java | google-ads-examples/src/main/java/com/google/ads/googleads/examples/advancedoperations/AddBiddingDataExclusion.java | 7023 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.ads.googleads.examples.advancedoperations;
import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v10.enums.AdvertisingChannelTypeEnum.AdvertisingChannelType;
import com.google.ads.googleads.v10.enums.SeasonalityEventScopeEnum.SeasonalityEventScope;
import com.google.ads.googleads.v10.errors.GoogleAdsError;
import com.google.ads.googleads.v10.errors.GoogleAdsException;
import com.google.ads.googleads.v10.resources.BiddingDataExclusion;
import com.google.ads.googleads.v10.services.BiddingDataExclusionOperation;
import com.google.ads.googleads.v10.services.BiddingDataExclusionServiceClient;
import com.google.ads.googleads.v10.services.MutateBiddingDataExclusionsResponse;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Adds a data exclusion for all search campaigns that excludes conversions from being used by Smart
* Bidding for the time interval specified.
*
* <p>For more information on using data exclusions, see
* https://developers.google.com/google-ads/api/docs/campaigns/bidding/data-exclusions.
*/
public class AddBiddingDataExclusion {
private static class AddBiddingDataExclusionParams extends CodeSampleParams {
@Parameter(
names = ArgumentNames.CUSTOMER_ID,
required = true,
description =
"The client customer ID of the Google Ads account that the data exclusion will"
+ " be added to.")
private Long customerId;
@Parameter(
names = ArgumentNames.START_DATE_TIME,
required = true,
description =
"The start date time in yyyy-MM-dd HH:mm:ss format of the data exclusion period.")
private String startDateTime;
@Parameter(
names = ArgumentNames.END_DATE_TIME,
required = true,
description =
"The end date time in yyyy-MM-dd HH:mm:ss format of the data exclusion period.")
private String endDateTime;
}
public static void main(String[] args) throws IOException {
AddBiddingDataExclusionParams params = new AddBiddingDataExclusionParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
params.startDateTime = "INSERT_START_DATE_TIME_HERE";
params.endDateTime = "INSERT_END_DATE_TIME_HERE";
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new AddBiddingDataExclusion()
.runExample(googleAdsClient, params.customerId, params.startDateTime, params.endDateTime);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Adds a "CHANNEL" scoped data exclusion for the client customer ID and dates specified.
*
* @param googleAdsClient the GoogleAdsClient
* @param customerId the client ID of the Google Ads account
* @param startDateTime the start time of the data exclusion (in yyyy-MM-dd HH:mm:ss format) in
* the account's timezone
* @param endDateTime the end time of the data exclusion (in yyyy-MM-dd HH:mm:ss format) in the
* account's timezone
*/
private void runExample(
GoogleAdsClient googleAdsClient, Long customerId, String startDateTime, String endDateTime) {
try (BiddingDataExclusionServiceClient DataExclusionServiceClient =
googleAdsClient.getLatestVersion().createBiddingDataExclusionServiceClient()) {
// [START add_bidding_data_exclusion]
BiddingDataExclusion DataExclusion =
BiddingDataExclusion.newBuilder()
// A unique name is required for every data exclusion.
.setName("Data exclusion #" + getPrintableDateTime())
// The CHANNEL scope applies the data exclusion to all campaigns of specific
// advertising channel types. In this example, the exclusion will only apply to
// Search campaigns. Use the CAMPAIGN scope to instead limit the scope to specific
// campaigns.
.setScope(SeasonalityEventScope.CHANNEL)
.addAdvertisingChannelTypes(AdvertisingChannelType.SEARCH)
// If setting scope CAMPAIGN, add individual campaign resource name(s) according to
// the commented out line below.
// .addCampaigns("INSERT_CAMPAIGN_RESOURCE_NAME_HERE")
.setStartDateTime(startDateTime)
.setEndDateTime(endDateTime)
.build();
BiddingDataExclusionOperation operation =
BiddingDataExclusionOperation.newBuilder().setCreate(DataExclusion).build();
MutateBiddingDataExclusionsResponse response =
DataExclusionServiceClient.mutateBiddingDataExclusions(
customerId.toString(), ImmutableList.of(operation));
System.out.printf(
"Added data exclusion with resource name: %s%n",
response.getResults(0).getResourceName());
// [END add_bidding_data_exclusion]
}
}
}
| apache-2.0 |
seava/seava.mod.ad | seava.mod.ad.domain/src/main/java/seava/ad/domain/impl/report/ReportServer.java | 2008 | /**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.domain.impl.report;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.QueryHint;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.eclipse.persistence.config.HintValues;
import org.eclipse.persistence.config.QueryHints;
import seava.j4e.domain.impl.AbstractType;
@NamedQueries({@NamedQuery(name = ReportServer.NQ_FIND_BY_NAME, query = "SELECT e FROM ReportServer e WHERE e.clientId = :clientId and e.name = :name", hints = @QueryHint(name = QueryHints.BIND_PARAMETERS, value = HintValues.TRUE))})
@Entity
@Table(name = ReportServer.TABLE_NAME, uniqueConstraints = {@UniqueConstraint(name = ReportServer.TABLE_NAME
+ "_UK1", columnNames = {"CLIENTID", "NAME"})})
public class ReportServer extends AbstractType implements Serializable {
public static final String TABLE_NAME = "AD_RPT_SRV";
private static final long serialVersionUID = -8865917134914502125L;
/**
* Named query find by unique key: Name.
*/
public static final String NQ_FIND_BY_NAME = "ReportServer.findByName";
@Column(name = "URL", length = 255)
private String url;
@Column(name = "QUERY_BLD_CLASS", length = 255)
private String queryBuilderClass;
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getQueryBuilderClass() {
return this.queryBuilderClass;
}
public void setQueryBuilderClass(String queryBuilderClass) {
this.queryBuilderClass = queryBuilderClass;
}
@PrePersist
public void prePersist() {
super.prePersist();
}
@PreUpdate
public void preUpdate() {
super.preUpdate();
}
}
| apache-2.0 |
Lordician/Tinkers-Fantasy | src/main/java/lordician/tinkersFantasy/common/ClientProxy.java | 976 | package lordician.tinkersFantasy.common;
import lordician.tinkersFantasy.ModInfo;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
public class ClientProxy extends CommonProxy {
@Override
public void preInit(FMLPreInitializationEvent event) {
super.preInit(event);
}
@Override
public void init(FMLInitializationEvent event) {
super.init(event);
}
@Override
public void postInit(FMLPostInitializationEvent event) {
super.postInit(event);
}
public void registerItemRenderer(Item item, int meta, String id) {
ModelLoader.setCustomModelResourceLocation(item, meta, new ModelResourceLocation(ModInfo.MODID + ":" + id, "inventory"));
}
}
| apache-2.0 |
halober/ovirt-engine | backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/GetNextAvailableDiskAliasNameByVMIdQueryTest.java | 4344 | package org.ovirt.engine.core.bll;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dao.VmDAO;
@RunWith(MockitoJUnitRunner.class)
public class GetNextAvailableDiskAliasNameByVMIdQueryTest extends AbstractUserQueryTest<IdQueryParameters, GetNextAvailableDiskAliasNameByVMIdQuery<IdQueryParameters>> {
@Mock
private VmDAO vmDAO;
private VM vm;
private final Guid vmId = Guid.newGuid();
private final String VM_NAME = "VmTESTNaME";
@Override
protected void setUpSpyQuery() throws Exception {
super.setUpSpyQuery();
doNothing().when(getQuery()).updateDisksFromDb(any(VM.class));
}
@Test
public void testExecuteQueryVmWithNoDisks() throws Exception {
mockDAOForQuery();
vm = mockVmAndReturnFromDAO();
String diskAliasName = ImagesHandler.getDefaultDiskAlias(vm.getName(), "1");
// Execute query.
getQuery().executeQueryCommand();
assertEquals(diskAliasName, getQuery().getQueryReturnValue().getReturnValue().toString());
}
@Test
public void testExecuteQueryWithInValidVmIdOrMissingPermissions() throws Exception {
mockDAOForQuery();
vm = mockVm();
// Execute query.
getQuery().executeQueryCommand();
assertEquals(null, getQuery().getQueryReturnValue().getReturnValue());
}
@Test
public void testExecuteQueryVmWithMultipleDisks() throws Exception {
mockDAOForQuery();
vm = mockVmAndReturnFromDAO();
populateVmDiskMap(vm, 5);
String expectedDiskAlias = ImagesHandler.getDefaultDiskAlias(vm.getName(), "6");
getQuery().executeQueryCommand();
assertEquals(expectedDiskAlias, getQuery().getQueryReturnValue().getReturnValue());
}
/**
* When removing a disk from VM with n disks the default disk alias will be VM_DISK{n} yet this alias is already
* taken since we created n disks to begin with, this test asserts that the suggested alias returned by this query
* will be VM_DISK{n+1}
*/
@Test
public void testExecuteQueryNotOverlappingExisting() throws Exception {
mockDAOForQuery();
vm = mockVmAndReturnFromDAO();
populateVmDiskMap(vm, 5);
vm.getDiskMap().remove(vm.getDiskMap().entrySet().iterator().next());
String expectedDiskAlias = ImagesHandler.getDefaultDiskAlias(vm.getName(), "6");
getQuery().executeQueryCommand();
assertEquals(expectedDiskAlias, getQuery().getQueryReturnValue().getReturnValue());
}
/**
* Populates the VM disk map with the amount of disks specified, each with a default disk alias
*/
private void populateVmDiskMap(VM vm, int numOfDisks) {
Map<Guid, Disk> diskMap = vm.getDiskMap();
for (Integer i = 0; i < numOfDisks; i++) {
DiskImage diskImage = new DiskImage();
diskImage.setId(Guid.newGuid());
diskImage.setDiskAlias(ImagesHandler.getDefaultDiskAlias(vm.getName(), i.toString()));
diskMap.put(diskImage.getId(), diskImage);
}
}
/**
* Initialize DAO to be used in query.
*
* @throws Exception
*/
private void mockDAOForQuery() throws Exception {
when(getDbFacadeMockInstance().getVmDao()).thenReturn(vmDAO);
when(getQueryParameters().getId()).thenReturn(vmId);
}
private VM mockVm() {
vm = new VM();
vm.setId(vmId);
vm.setName(VM_NAME);
vm.setDiskMap(new HashMap<Guid, Disk>());
return vm;
}
private VM mockVmAndReturnFromDAO() {
vm = mockVm();
when(vmDAO.get(vmId, getQuery().getUserID(), getQueryParameters().isFiltered())).thenReturn(vm);
return vm;
}
}
| apache-2.0 |
kevoree-modeling/kmf | dsl/src/main/java/org/kevoree/modeling/ast/impl/Index.java | 1421 | package org.kevoree.modeling.ast.impl;
import org.kevoree.modeling.ast.KClass;
import org.kevoree.modeling.ast.KIndex;
import org.kevoree.modeling.ast.KProperty;
import java.util.Set;
import java.util.TreeSet;
public class Index implements KIndex {
private final Set<KProperty> literals;
private final String pack;
private final String name;
private final KClass clazz;
public Index(String fqn, KClass clazz) {
this.clazz = clazz;
if (fqn.contains(".")) {
name = fqn.substring(fqn.lastIndexOf('.') + 1);
pack = fqn.substring(0, fqn.lastIndexOf('.'));
} else {
name = fqn;
pack = null;
}
literals = new TreeSet<KProperty>();
}
@Override
public KProperty[] properties() {
return literals.toArray(new KProperty[literals.size()]);
}
@Override
public void addProperty(String value) {
KProperty prop = clazz.property(value);
literals.add(prop);
prop.addIndex(this);
}
@Override
public KClass type() {
return this.clazz;
}
@Override
public String name() {
return name;
}
@Override
public String fqn() {
if (pack != null) {
return pack + "." + name;
} else {
return name;
}
}
@Override
public String pack() {
return pack;
}
}
| apache-2.0 |
dbeaver/dbeaver | plugins/org.jkiss.dbeaver.ui/src/org/jkiss/dbeaver/ui/controls/DoubleClickMouseAdapter.java | 1539 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2022 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ui.controls;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.ui.UIUtils;
public class DoubleClickMouseAdapter extends MouseAdapter {
private boolean singleClick = false;
public void onMouseSingleClick(@NotNull MouseEvent e) {
// do nothing
}
public void onMouseDoubleClick(@NotNull MouseEvent e) {
// do nothing
}
@Override
public final void mouseDoubleClick(MouseEvent e) {
singleClick = false;
onMouseDoubleClick(e);
}
@Override
public final void mouseDown(MouseEvent e) {
singleClick = true;
UIUtils.timerExec(UIUtils.getDisplay().getDoubleClickTime(), () -> {
if (singleClick) {
onMouseSingleClick(e);
}
});
}
}
| apache-2.0 |
ryansgot/forsuredbcompiler | sqlitelib/src/main/java/com/fsryan/forsuredb/sqlitelib/AddForeignKeyGenerator.java | 6778 | /*
forsuredbsqlitelib, sqlite library for the forsuredb project
Copyright 2015 Ryan Scott
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.fsryan.forsuredb.sqlitelib;
import com.fsryan.forsuredb.api.migration.QueryGenerator;
import com.fsryan.forsuredb.info.ColumnInfo;
import com.fsryan.forsuredb.info.TableInfo;
import com.fsryan.forsuredb.migration.Migration;
import java.util.*;
import static com.fsryan.forsuredb.sqlitelib.ApiInfo.DEFAULT_COLUMN_MAP;
/**
* <p>
* For backwards compatibilty with forsuredbcompiler versions that produce
* {@link Migration.Type#ADD_FOREIGN_KEY_REFERENCE} migrations.
* </p>
*/
@Deprecated
public class AddForeignKeyGenerator extends QueryGenerator {
private final TableInfo table;
private final List<ColumnInfo> newForeignKeyColumns;
private final Map<String, TableInfo> targetSchema;
/**
* <p>
* Add only one foreign key column to the table
* </p>
* @param table the table to which foreign key columns should be added
* @param column the foreign key column to add
*/
public AddForeignKeyGenerator(TableInfo table, ColumnInfo column, Map<String, TableInfo> targetSchema) {
this(table, new ArrayList<>(Arrays.asList(column)), targetSchema);
}
/**
* <p>
* Use this when there are multiple foreign keys to add to the same table
* </p>
* @param table the table to which foreign key columns should be added
* @param newForeignKeyColumns a list of all new foreign key columns to add
*/
public AddForeignKeyGenerator(TableInfo table, List<ColumnInfo> newForeignKeyColumns, Map<String, TableInfo> targetSchema) {
super(table.tableName(), Migration.Type.ADD_FOREIGN_KEY_REFERENCE);
this.table = table;
this.newForeignKeyColumns = newForeignKeyColumns;
this.targetSchema = targetSchema;
}
@Override
public List<String> generate() {
List<String> retList = new LinkedList<>();
retList.addAll(new CreateTempTableFromExisting(table, newForeignKeyColumns).generate());
retList.addAll(new DropTableGenerator(getTableName()).generate());
retList.addAll(recreateTableWithAllForeignKeysQuery());
retList.addAll(allColumnAdditionQueries());
retList.add(reinsertDataQuery());
retList.addAll(new DropTableGenerator(tempTableName()).generate());
return retList;
}
private List<String> recreateTableWithAllForeignKeysQuery() {
final List<String> retList = new LinkedList<>();
List<String> normalCreationQueries = new LegacyCreateTableGenerator(getTableName(), targetSchema).generate();
// add the default columns to the normal TABLE CREATE query
StringBuffer buf = new StringBuffer(normalCreationQueries.remove(0));
buf.delete(buf.length() - 2, buf.length()); // <-- removes );
List<ColumnInfo> foreignKeyColumns = table.getForeignKeyColumns();
addColumnDefinitionsToBuffer(buf, foreignKeyColumns);
for (ColumnInfo fKeyColumn : newForeignKeyColumns) {
addColumnDefinitionToBuffer(buf, fKeyColumn);
}
addForeignKeyDefinitionsToBuffer(buf, foreignKeyColumns);
for (ColumnInfo fKeyColumn : newForeignKeyColumns) {
addForeignKeyDefinitionToBuffer(buf, fKeyColumn);
}
retList.add(buf.append(");").toString());
// add all remaining table create queries
while (normalCreationQueries.size() > 0) {
retList.add(normalCreationQueries.remove(0));
}
return retList;
}
private List<String> allColumnAdditionQueries() {
List<String> retList = new LinkedList<>();
for (ColumnInfo columnInfo : table.getNonForeignKeyColumns()) {
if (DEFAULT_COLUMN_MAP.containsKey(columnInfo.getColumnName()) || columnInfo.unique()) {
continue; // <-- these columns were added in the CREATE TABLE query
}
retList.addAll(new AddColumnGenerator(getTableName(), columnInfo).generate());
}
return retList;
}
private String reinsertDataQuery() {
StringBuffer buf = new StringBuffer("INSERT INTO ").append(getTableName()).append(" SELECT ");
List<ColumnInfo> tableColumns = new LinkedList<>(table.getColumns());
Collections.sort(tableColumns);
for (ColumnInfo tableColumn : tableColumns) {
if (newForeignKeyColumns.contains(tableColumn)) {
buf.append(", null AS ").append(tableColumn.getColumnName());
} else {
buf.append("_id".equals(tableColumn.getColumnName()) ? "" : ", ").append(tableColumn.getColumnName());
}
}
return buf.append(" FROM ").append(tempTableName()).append(";").toString();
}
private String tempTableName() {
return "temp_" + getTableName();
}
private void addColumnDefinitionsToBuffer(StringBuffer buf, List<ColumnInfo> columns) {
for (ColumnInfo column : columns) {
if (!newForeignKeyColumns.contains(column)) {
addColumnDefinitionToBuffer(buf, column);
}
}
}
private void addColumnDefinitionToBuffer(StringBuffer buf, ColumnInfo column) {
buf.append(", ").append(column.getColumnName())
.append(" ").append(TypeTranslator.from(column.getQualifiedType()).getSqlString());
}
private void addForeignKeyDefinitionsToBuffer(StringBuffer buf, List<ColumnInfo> columns) {
for (ColumnInfo column : columns) {
if (!newForeignKeyColumns.contains(column)) {
addForeignKeyDefinitionToBuffer(buf, column);
}
}
}
private void addForeignKeyDefinitionToBuffer(StringBuffer buf, ColumnInfo column) {
buf.append(", FOREIGN KEY(").append(column.getColumnName())
.append(") REFERENCES ").append(column.foreignKeyInfo().tableName())
.append("(").append(column.foreignKeyInfo().columnName())
.append(")")
.append(" ON UPDATE ").append(column.foreignKeyInfo().updateAction())
.append(" ON DELETE ").append(column.foreignKeyInfo().deleteAction());
}
}
| apache-2.0 |
mifos/1.4.x | application/src/main/java/org/mifos/application/customer/client/struts/action/ClientTransferAction.java | 8425 | /*
* Copyright (c) 2005-2009 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.application.customer.client.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.mifos.application.customer.business.service.CustomerBusinessService;
import org.mifos.application.customer.client.business.ClientBO;
import org.mifos.application.customer.client.business.service.ClientBusinessService;
import org.mifos.application.customer.client.struts.actionforms.ClientTransferActionForm;
import org.mifos.application.customer.client.util.helpers.ClientConstants;
import org.mifos.application.customer.group.business.GroupBO;
import org.mifos.application.customer.util.helpers.CustomerConstants;
import org.mifos.application.customer.util.helpers.CustomerSearchInputView;
import org.mifos.application.office.business.OfficeBO;
import org.mifos.application.office.business.service.OfficeBusinessService;
import org.mifos.application.util.helpers.ActionForwards;
import org.mifos.framework.business.service.BusinessService;
import org.mifos.framework.business.service.ServiceFactory;
import org.mifos.framework.exceptions.ServiceException;
import org.mifos.framework.security.util.ActionSecurity;
import org.mifos.framework.security.util.SecurityConstants;
import org.mifos.framework.struts.action.BaseAction;
import org.mifos.framework.util.helpers.BusinessServiceName;
import org.mifos.framework.util.helpers.CloseSession;
import org.mifos.framework.util.helpers.Constants;
import org.mifos.framework.util.helpers.SessionUtils;
import org.mifos.framework.util.helpers.TransactionDemarcate;
public class ClientTransferAction extends BaseAction {
@Override
protected BusinessService getService() throws ServiceException {
return getCustomerBusinessService();
}
@Override
protected boolean skipActionFormToBusinessObjectConversion(String method) {
return true;
}
public static ActionSecurity getSecurity() {
ActionSecurity security = new ActionSecurity("clientTransferAction");
security.allow("loadParents", SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP);
security.allow("loadBranches", SecurityConstants.CIENT_TRANSFER_THE_CLIENT);
security.allow("previewBranchTransfer", SecurityConstants.VIEW);
security.allow("previewParentTransfer", SecurityConstants.VIEW);
security.allow("updateParent", SecurityConstants.CIENT_CHANGE_GROUP_MEMBERSHIP);
security.allow("transferToBranch", SecurityConstants.CIENT_TRANSFER_THE_CLIENT);
return security;
}
@TransactionDemarcate(joinToken = true)
public ActionForward loadBranches(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
return mapping.findForward(ActionForwards.loadBranches_success.toString());
}
@TransactionDemarcate(joinToken = true)
public ActionForward previewBranchTransfer(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
return mapping.findForward(ActionForwards.previewBranchTransfer_success.toString());
}
@TransactionDemarcate(validateAndResetToken = true)
@CloseSession
public ActionForward transferToBranch(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ClientTransferActionForm actionForm = (ClientTransferActionForm) form;
OfficeBO officeToTransfer = getOfficelBusinessService().getOffice(actionForm.getOfficeIdValue());
ClientBO clientInSession = (ClientBO) SessionUtils.getAttribute(Constants.BUSINESS_KEY, request);
ClientBO client = (ClientBO) getCustomerBusinessService().getCustomer(clientInSession.getCustomerId());
checkVersionMismatch(clientInSession.getVersionNo(), client.getVersionNo());
client.setVersionNo(clientInSession.getVersionNo());
client.setUserContext(getUserContext(request));
setInitialObjectForAuditLogging(client);
client.transferToBranch(officeToTransfer);
clientInSession = null;
officeToTransfer = null;
SessionUtils.setAttribute(Constants.BUSINESS_KEY, client, request);
return mapping.findForward(ActionForwards.update_success.toString());
}
@TransactionDemarcate(validateAndResetToken = true)
public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
return mapping.findForward(ActionForwards.cancel_success.toString());
}
@TransactionDemarcate(joinToken = true)
public ActionForward loadParents(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
CustomerSearchInputView clientSearchInput = new CustomerSearchInputView();
clientSearchInput.setOfficeId(getUserContext(request).getBranchId());
clientSearchInput.setCustomerInputPage(ClientConstants.INPUT_GROUP_TRANSFER);
SessionUtils.setAttribute(CustomerConstants.CUSTOMER_SEARCH_INPUT, clientSearchInput, request.getSession());
return mapping.findForward(ActionForwards.loadParents_success.toString());
}
@TransactionDemarcate(joinToken = true)
public ActionForward previewParentTransfer(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
return mapping.findForward(ActionForwards.previewParentTransfer_success.toString());
}
@CloseSession
@TransactionDemarcate(validateAndResetToken = true)
public ActionForward updateParent(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ClientTransferActionForm actionForm = (ClientTransferActionForm) form;
GroupBO transferToGroup = (GroupBO) getCustomerBusinessService()
.getCustomer(actionForm.getParentGroupIdValue());
transferToGroup.setUserContext(getUserContext(request));
ClientBO clientInSession = (ClientBO) SessionUtils.getAttribute(Constants.BUSINESS_KEY, request);
ClientBO client = getClientBusinessService().getClient(clientInSession.getCustomerId());
checkVersionMismatch(clientInSession.getVersionNo(), client.getVersionNo());
client.setVersionNo(clientInSession.getVersionNo());
client.setUserContext(getUserContext(request));
setInitialObjectForAuditLogging(client);
client.transferToGroup(transferToGroup);
clientInSession = null;
transferToGroup = null;
SessionUtils.setAttribute(Constants.BUSINESS_KEY, client, request);
return mapping.findForward(ActionForwards.update_success.toString());
}
private CustomerBusinessService getCustomerBusinessService() throws ServiceException {
return (CustomerBusinessService) ServiceFactory.getInstance().getBusinessService(BusinessServiceName.Customer);
}
private ClientBusinessService getClientBusinessService() throws ServiceException {
return (ClientBusinessService) ServiceFactory.getInstance().getBusinessService(BusinessServiceName.Client);
}
private OfficeBusinessService getOfficelBusinessService() throws ServiceException {
return (OfficeBusinessService) ServiceFactory.getInstance().getBusinessService(BusinessServiceName.Office);
}
}
| apache-2.0 |
amient/affinity | api/src/main/java/io/amient/affinity/core/serde/AbstractSerde.java | 1174 | /*
* Copyright 2016 Michal Harish, michal.harish@gmail.com
*
* 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 io.amient.affinity.core.serde;
import java.io.Closeable;
public interface AbstractSerde<T> extends Closeable {
T fromBytes(byte[] bytes);
byte[] toBytes(T obj);
default byte[] prefix(Class<? extends T> cls, Object... prefix) {
throw new UnsupportedOperationException();
}
}
| apache-2.0 |
sebadiaz/kafka | clients/src/main/java/org/apache/kafka/common/security/plain/internal/PlainSaslServer.java | 7529 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.common.security.plain.internal;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Map;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslException;
import javax.security.sasl.SaslServer;
import javax.security.sasl.SaslServerFactory;
import org.apache.kafka.common.errors.SaslAuthenticationException;
import org.apache.kafka.common.security.plain.PlainAuthenticateCallback;
/**
* Simple SaslServer implementation for SASL/PLAIN. In order to make this implementation
* fully pluggable, authentication of username/password is fully contained within the
* server implementation.
* <p>
* Valid users with passwords are specified in the Jaas configuration file. Each user
* is specified with user_<username> as key and <password> as value. This is consistent
* with Zookeeper Digest-MD5 implementation.
* <p>
* To avoid storing clear passwords on disk or to integrate with external authentication
* servers in production systems, this module can be replaced with a different implementation.
*
*/
public class PlainSaslServer implements SaslServer {
public static final String PLAIN_MECHANISM = "PLAIN";
private final CallbackHandler callbackHandler;
private boolean complete;
private String authorizationId;
public PlainSaslServer(CallbackHandler callbackHandler) {
this.callbackHandler = callbackHandler;
}
/**
* @throws SaslAuthenticationException if username/password combination is invalid or if the requested
* authorization id is not the same as username.
* <p>
* <b>Note:</b> This method may throw {@link SaslAuthenticationException} to provide custom error messages
* to clients. But care should be taken to avoid including any information in the exception message that
* should not be leaked to unauthenticated clients. It may be safer to throw {@link SaslException} in
* some cases so that a standard error message is returned to clients.
* </p>
*/
@Override
public byte[] evaluateResponse(byte[] response) throws SaslException, SaslAuthenticationException {
/*
* Message format (from https://tools.ietf.org/html/rfc4616):
*
* message = [authzid] UTF8NUL authcid UTF8NUL passwd
* authcid = 1*SAFE ; MUST accept up to 255 octets
* authzid = 1*SAFE ; MUST accept up to 255 octets
* passwd = 1*SAFE ; MUST accept up to 255 octets
* UTF8NUL = %x00 ; UTF-8 encoded NUL character
*
* SAFE = UTF1 / UTF2 / UTF3 / UTF4
* ;; any UTF-8 encoded Unicode character except NUL
*/
String[] tokens;
try {
tokens = new String(response, "UTF-8").split("\u0000");
} catch (UnsupportedEncodingException e) {
throw new SaslException("UTF-8 encoding not supported", e);
}
if (tokens.length != 3)
throw new SaslException("Invalid SASL/PLAIN response: expected 3 tokens, got " + tokens.length);
String authorizationIdFromClient = tokens[0];
String username = tokens[1];
String password = tokens[2];
if (username.isEmpty()) {
throw new SaslException("Authentication failed: username not specified");
}
if (password.isEmpty()) {
throw new SaslException("Authentication failed: password not specified");
}
NameCallback nameCallback = new NameCallback("username", username);
PlainAuthenticateCallback authenticateCallback = new PlainAuthenticateCallback(password.toCharArray());
try {
callbackHandler.handle(new Callback[]{nameCallback, authenticateCallback});
} catch (Throwable e) {
throw new SaslAuthenticationException("Authentication failed: credentials for user could not be verified", e);
}
if (!authenticateCallback.authenticated())
throw new SaslAuthenticationException("Authentication failed: Invalid username or password");
if (!authorizationIdFromClient.isEmpty() && !authorizationIdFromClient.equals(username))
throw new SaslAuthenticationException("Authentication failed: Client requested an authorization id that is different from username");
this.authorizationId = username;
complete = true;
return new byte[0];
}
@Override
public String getAuthorizationID() {
if (!complete)
throw new IllegalStateException("Authentication exchange has not completed");
return authorizationId;
}
@Override
public String getMechanismName() {
return PLAIN_MECHANISM;
}
@Override
public Object getNegotiatedProperty(String propName) {
if (!complete)
throw new IllegalStateException("Authentication exchange has not completed");
return null;
}
@Override
public boolean isComplete() {
return complete;
}
@Override
public byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException {
if (!complete)
throw new IllegalStateException("Authentication exchange has not completed");
return Arrays.copyOfRange(incoming, offset, offset + len);
}
@Override
public byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException {
if (!complete)
throw new IllegalStateException("Authentication exchange has not completed");
return Arrays.copyOfRange(outgoing, offset, offset + len);
}
@Override
public void dispose() throws SaslException {
}
public static class PlainSaslServerFactory implements SaslServerFactory {
@Override
public SaslServer createSaslServer(String mechanism, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh)
throws SaslException {
if (!PLAIN_MECHANISM.equals(mechanism))
throw new SaslException(String.format("Mechanism \'%s\' is not supported. Only PLAIN is supported.", mechanism));
return new PlainSaslServer(cbh);
}
@Override
public String[] getMechanismNames(Map<String, ?> props) {
if (props == null) return new String[]{PLAIN_MECHANISM};
String noPlainText = (String) props.get(Sasl.POLICY_NOPLAINTEXT);
if ("true".equals(noPlainText))
return new String[]{};
else
return new String[]{PLAIN_MECHANISM};
}
}
}
| apache-2.0 |
tombujok/hazelcast | hazelcast/src/main/java/com/hazelcast/spi/impl/eventservice/impl/LocalEventDispatcher.java | 2348 | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.spi.impl.eventservice.impl;
import com.hazelcast.spi.EventPublishingService;
import com.hazelcast.util.executor.StripedRunnable;
import com.hazelcast.util.executor.TimeoutRunnable;
import java.util.concurrent.TimeUnit;
/**
* A {@link StripedRunnable} responsible of processing the {@link #event} on a thread defined by the {@link #orderKey}.
* Processes the event by dispatching it on the responsible {@link EventPublishingService} together with the listener
* responsible for the event.
*
* @see EventPublishingService#dispatchEvent(Object, Object)
*/
public final class LocalEventDispatcher implements StripedRunnable, TimeoutRunnable {
private EventServiceImpl eventService;
private final String serviceName;
private final Object event;
private final Object listener;
private final int orderKey;
private final long timeoutMs;
LocalEventDispatcher(EventServiceImpl eventService, String serviceName, Object event, Object listener,
int orderKey, long timeoutMs) {
this.eventService = eventService;
this.serviceName = serviceName;
this.event = event;
this.listener = listener;
this.orderKey = orderKey;
this.timeoutMs = timeoutMs;
}
@Override
public long getTimeout() {
return timeoutMs;
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.MILLISECONDS;
}
@Override
public void run() {
final EventPublishingService<Object, Object> service = eventService.nodeEngine.getService(serviceName);
service.dispatchEvent(event, listener);
}
@Override
public int getKey() {
return orderKey;
}
}
| apache-2.0 |
mike10004/appengine-imaging | gaecompat-awt-imaging/src/sanselan/org/apache/sanselan/formats/png/chunks/PNGChunkgAMA.java | 1496 | /*
* 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.sanselan.formats.png.chunks;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.apache.sanselan.ImageReadException;
public class PNGChunkgAMA extends PNGChunk
{
public final int Gamma;
public PNGChunkgAMA(int Length, int ChunkType, int CRC, byte bytes[])
throws ImageReadException, IOException
{
super(Length, ChunkType, CRC, bytes);
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
Gamma = read4Bytes("Gamma", is, "Not a Valid Png File: gAMA Corrupt");
}
public double getGamma()
{
return 1.0 / (Gamma / 100000.0);
}
} | apache-2.0 |
jexp/idea2 | platform/platform-api/src/com/intellij/util/IconUtil.java | 5006 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util;
import com.intellij.ide.FileIconPatcher;
import com.intellij.ide.FileIconProvider;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.IconDeferrer;
import com.intellij.ui.RowIcon;
import com.intellij.ui.LayeredIcon;
import com.intellij.util.ui.EmptyIcon;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class IconUtil {
private IconUtil() {
}
private static class FileIconKey {
private final VirtualFile myFile;
private final Project myProject;
private final int myFlags;
private FileIconKey(final VirtualFile file, final Project project, final int flags) {
myFile = file;
myProject = project;
myFlags = flags;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (!(o instanceof FileIconKey)) return false;
final FileIconKey that = (FileIconKey)o;
if (myFlags != that.myFlags) return false;
if (!myFile.equals(that.myFile)) return false;
if (myProject != null ? !myProject.equals(that.myProject) : that.myProject != null) return false;
return true;
}
@Override
public int hashCode() {
int result = myFile.hashCode();
result = 31 * result + (myProject != null ? myProject.hashCode() : 0);
result = 31 * result + myFlags;
return result;
}
public VirtualFile getFile() {
return myFile;
}
public Project getProject() {
return myProject;
}
public int getFlags() {
return myFlags;
}
}
public static Icon getIcon(final VirtualFile file, final int flags, final Project project) {
return IconDeferrer.getInstance().defer(file.getIcon(), new FileIconKey(file, project, flags), new Function<FileIconKey, Icon>() {
public Icon fun(final FileIconKey key) {
VirtualFile file = key.getFile();
int flags = key.getFlags();
Project project = key.getProject();
if (!file.isValid() || project != null && project.isDisposed()) return null;
Icon providersIcon = getProvidersIcon(file, flags, project);
Icon icon = providersIcon == null ? file.getIcon() : providersIcon;
final boolean dumb = project != null && DumbService.getInstance(project).isDumb();
for (FileIconPatcher patcher : getPatchers()) {
if (dumb && !(patcher instanceof DumbAware)) {
continue;
}
icon = patcher.patchIcon(icon, file, flags, project);
}
if ((flags & Iconable.ICON_FLAG_READ_STATUS) != 0 && !file.isWritable()) {
return new LayeredIcon(icon, Icons.LOCKED_ICON);
}
return icon;
}
});
}
@Nullable
private static Icon getProvidersIcon(VirtualFile file, int flags, Project project) {
for (FileIconProvider provider : getProviders()) {
final Icon icon = provider.getIcon(file, flags, project);
if (icon != null) return icon;
}
return null;
}
public static Icon getEmptyIcon(boolean showVisibility) {
RowIcon baseIcon = new RowIcon(2);
baseIcon.setIcon(createEmptyIconLike(Icons.CLASS_ICON_PATH), 0);
if (showVisibility) {
baseIcon.setIcon(createEmptyIconLike(Icons.PUBLIC_ICON_PATH), 1);
}
return baseIcon;
}
@Nullable
private static Icon createEmptyIconLike(final String baseIconPath) {
Icon baseIcon = IconLoader.findIcon(baseIconPath);
if (baseIcon == null) {
return new EmptyIcon(16, 16);
}
return new EmptyIcon(baseIcon.getIconWidth(), baseIcon.getIconHeight());
}
private static class FileIconProviderHolder {
private static final FileIconProvider[] ourProviders = Extensions.getExtensions(FileIconProvider.EP_NAME);
}
private static FileIconProvider[] getProviders() {
return FileIconProviderHolder.ourProviders;
}
private static class FileIconPatcherHolder {
private static final FileIconPatcher[] ourPatchers = Extensions.getExtensions(FileIconPatcher.EP_NAME);
}
private static FileIconPatcher[] getPatchers() {
return FileIconPatcherHolder.ourPatchers;
}
}
| apache-2.0 |
Codeforces/codeforces-commons | code/src/main/java/com/codeforces/commons/io/http/HttpClientUtil.java | 34233 | package com.codeforces.commons.io.http;
import com.codeforces.commons.io.IoUtil;
import com.codeforces.commons.process.ThreadUtil;
import com.codeforces.commons.properties.internal.CommonsPropertiesUtil;
import com.codeforces.commons.text.StringUtil;
import com.codeforces.commons.text.UrlUtil;
import org.apache.http.*;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestExecutor;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author Maxim Shipko (sladethe@gmail.com)
* Date: 07.11.11
*/
@SuppressWarnings({"OverloadedVarargsMethod", "deprecation"})
@Deprecated
public class HttpClientUtil {
private static final int CONNECTION_POOL_DEFAULT_MAX_SIZE = 50;
private static final int CONNECTION_POOL_DEFAULT_MAX_SIZE_PER_HOST = 25;
private static final ExecutorService timedRequestExecutor = new ThreadPoolExecutor(
0, Short.MAX_VALUE, 5L, TimeUnit.MINUTES, new LinkedBlockingQueue<>(),
ThreadUtil.getCustomPoolThreadFactory(new ThreadUtil.ThreadCustomizer() {
private final AtomicLong threadIndex = new AtomicLong();
@Override
public void customize(Thread thread) {
thread.setDaemon(true);
thread.setName(String.format(
"%s#RequestExecutionThread-%d",
HttpClientUtil.class.getSimpleName(), threadIndex.incrementAndGet()
));
}
})
);
private HttpClientUtil() {
throw new UnsupportedOperationException();
}
public static void executeGetRequest(
@Nullable HttpClient httpClient, boolean encodeParameters, String url, Object... parameters
) throws IOException {
internalExecuteGetRequest(httpClient, encodeParameters, url, parameters);
}
@SuppressWarnings("ConstantConditions")
public static void executeGetRequest(
long executionTimeoutMillis, HttpClient httpClient, boolean encodeParameters,
String url, Object... parameters) throws IOException {
internalExecuteLimitedTimeRequest(executionTimeoutMillis, url, () -> {
executeGetRequest(httpClient, encodeParameters, url, parameters);
return null;
});
}
public static void executeGetRequest(
boolean encodeParameters, String url, Object... parameters) throws IOException {
executeGetRequest(null, encodeParameters, url, parameters);
}
@SuppressWarnings("ConstantConditions")
public static void executeGetRequest(
long executionTimeoutMillis, boolean encodeParameters,
String url, Object... parameters) throws IOException {
internalExecuteLimitedTimeRequest(executionTimeoutMillis, url, () -> {
executeGetRequest(encodeParameters, url, parameters);
return null;
});
}
public static void executeGetRequest(String url, Object... parameters) throws IOException {
executeGetRequest(false, url, parameters);
}
@SuppressWarnings("ConstantConditions")
public static void executeGetRequest(
long executionTimeoutMillis, String url, Object... parameters) throws IOException {
internalExecuteLimitedTimeRequest(executionTimeoutMillis, url, () -> {
executeGetRequest(url, parameters);
return null;
});
}
public static byte[] executeGetRequestAndReturnResponseBytes(
@Nullable HttpClient httpClient, boolean encodeParameters, String url, Object... parameters
) throws IOException {
HttpResponse httpResponse = internalExecuteGetRequest(httpClient, encodeParameters, url, parameters);
InputStream inputStream = httpResponse.getEntity().getContent();
return IoUtil.toByteArray(inputStream);
}
public static byte[] executeGetRequestAndReturnResponseBytes(
long executionTimeoutMillis, HttpClient httpClient, boolean encodeParameters,
String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url,
() -> executeGetRequestAndReturnResponseBytes(httpClient, encodeParameters, url, parameters)
);
}
public static byte[] executeGetRequestAndReturnResponseBytes(
boolean encodeParameters, String url, Object... parameters) throws IOException {
return executeGetRequestAndReturnResponseBytes(null, encodeParameters, url, parameters);
}
public static byte[] executeGetRequestAndReturnResponseBytes(
long executionTimeoutMillis, boolean encodeParameters,
String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url,
() -> executeGetRequestAndReturnResponseBytes(encodeParameters, url, parameters)
);
}
public static byte[] executeGetRequestAndReturnResponseBytes(String url, Object... parameters) throws IOException {
return executeGetRequestAndReturnResponseBytes(false, url, parameters);
}
public static byte[] executeGetRequestAndReturnResponseBytes(
long executionTimeoutMillis, String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url,
() -> executeGetRequestAndReturnResponseBytes(url, parameters)
);
}
public static String executeGetRequestAndReturnResponseAsString(
@Nullable HttpClient httpClient, boolean encodeParameters, String url, Object... parameters
) throws IOException {
HttpResponse httpResponse = internalExecuteGetRequest(httpClient, encodeParameters, url, parameters);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();
return httpEntity.getContentEncoding() == null
? IoUtil.toString(inputStream)
: IoUtil.toString(inputStream, httpEntity.getContentEncoding().getValue());
}
public static String executeGetRequestAndReturnResponseAsString(
long executionTimeoutMillis, HttpClient httpClient, boolean encodeParameters,
String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url,
() -> executeGetRequestAndReturnResponseAsString(httpClient, encodeParameters, url, parameters)
);
}
public static String executeGetRequestAndReturnResponseAsString(
boolean encodeParameters, String url, Object... parameters) throws IOException {
return executeGetRequestAndReturnResponseAsString(null, encodeParameters, url, parameters);
}
public static String executeGetRequestAndReturnResponseAsString(
long executionTimeoutMillis, boolean encodeParameters,
String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url,
() -> executeGetRequestAndReturnResponseAsString(encodeParameters, url, parameters)
);
}
public static String executeGetRequestAndReturnResponseAsString(
String url, Object... parameters) throws IOException {
return executeGetRequestAndReturnResponseAsString(false, url, parameters);
}
public static String executeGetRequestAndReturnResponseAsString(
long executionTimeoutMillis, String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url, () -> executeGetRequestAndReturnResponseAsString(url, parameters)
);
}
@Nonnull
public static Response executeGetRequestAndReturnResponse(
@Nullable HttpClient httpClient, boolean encodeParameters, String url, Object... parameters
) throws IOException {
HttpResponse httpResponse = internalExecuteGetRequest(httpClient, encodeParameters, url, parameters);
HttpEntity httpEntity = httpResponse.getEntity();
return new Response(
httpResponse.getStatusLine().getStatusCode(),
httpEntity.getContent(),
httpEntity.getContentEncoding() == null ? null : httpEntity.getContentEncoding().getValue(),
httpEntity.getContentLength(),
httpResponse
);
}
public static Response executeGetRequestAndReturnResponse(
long executionTimeoutMillis, HttpClient httpClient, boolean encodeParameters,
String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url,
() -> executeGetRequestAndReturnResponse(httpClient, encodeParameters, url, parameters)
);
}
@Nonnull
public static Response executeGetRequestAndReturnResponse(
boolean encodeParameters, String url, Object... parameters) throws IOException {
return executeGetRequestAndReturnResponse(null, encodeParameters, url, parameters);
}
public static Response executeGetRequestAndReturnResponse(
long executionTimeoutMillis, boolean encodeParameters,
String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url, () -> executeGetRequestAndReturnResponse(encodeParameters, url, parameters)
);
}
@Nonnull
public static Response executeGetRequestAndReturnResponse(String url, Object... parameters) throws IOException {
return executeGetRequestAndReturnResponse(false, url, parameters);
}
@Nonnull
public static Response executeGetRequestAndReturnResponse(
long executionTimeoutMillis, String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url, () -> executeGetRequestAndReturnResponse(url, parameters)
);
}
private static HttpResponse internalExecuteGetRequest(
@Nullable HttpClient httpClient, boolean encodeParameters, String url, Object... parameters
) throws IOException {
parameters = validateAndPreprocessParameters(encodeParameters, url, parameters);
for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex += 2) {
url = UrlUtil.appendParameterToUrl(
url, (String) parameters[parameterIndex], parameters[parameterIndex + 1].toString()
);
}
httpClient = httpClient == null ? newHttpClient() : httpClient;
HttpGet request = new HttpGet(url);
return httpClient.execute(request);
}
public static void executePostRequest(
@Nullable HttpClient httpClient, String url, Object... parameters) throws IOException {
internalExecutePostRequest(httpClient, url, parameters);
}
@SuppressWarnings("ConstantConditions")
public static void executePostRequest(
long executionTimeoutMillis, HttpClient httpClient,
String url, Object... parameters) throws IOException {
internalExecuteLimitedTimeRequest(executionTimeoutMillis, url, () -> {
executePostRequest(httpClient, url, parameters);
return null;
});
}
public static void executePostRequest(String url, Object... parameters) throws IOException {
executePostRequest(null, url, parameters);
}
@SuppressWarnings("ConstantConditions")
public static void executePostRequest(
long executionTimeoutMillis, String url, Object... parameters) throws IOException {
internalExecuteLimitedTimeRequest(executionTimeoutMillis, url, () -> {
executePostRequest(url, parameters);
return null;
});
}
@Nullable
public static byte[] executePostRequestAndReturnResponseBytes(
@Nullable HttpClient httpClient, String url, Object... parameters) throws IOException {
HttpResponse httpResponse = internalExecutePostRequest(httpClient, url, parameters);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
return null;
}
InputStream inputStream = httpEntity.getContent();
return IoUtil.toByteArray(inputStream);
}
@Nullable
public static byte[] executePostRequestAndReturnResponseBytes(
long executionTimeoutMillis, HttpClient httpClient,
String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(executionTimeoutMillis, url, new Callable<byte[]>() {
@Nullable
@Override
public byte[] call() throws Exception {
return executePostRequestAndReturnResponseBytes(httpClient, url, parameters);
}
});
}
@Nullable
public static byte[] executePostRequestAndReturnResponseBytes(String url, Object... parameters) throws IOException {
return executePostRequestAndReturnResponseBytes(null, url, parameters);
}
@Nullable
public static byte[] executePostRequestAndReturnResponseBytes(
long executionTimeoutMillis, String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(executionTimeoutMillis, url, new Callable<byte[]>() {
@Nullable
@Override
public byte[] call() throws Exception {
return executePostRequestAndReturnResponseBytes(url, parameters);
}
});
}
@Nullable
public static String executePostRequestAndReturnResponseAsString(
@Nullable HttpClient httpClient, String url, Object... parameters) throws IOException {
HttpResponse httpResponse = internalExecutePostRequest(httpClient, url, parameters);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
return null;
}
InputStream inputStream = httpEntity.getContent();
return httpEntity.getContentEncoding() == null
? IoUtil.toString(inputStream)
: IoUtil.toString(inputStream, httpEntity.getContentEncoding().getValue());
}
@Nullable
public static String executePostRequestAndReturnResponseAsString(
long executionTimeoutMillis, HttpClient httpClient,
String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(executionTimeoutMillis, url, new Callable<String>() {
@Nullable
@Override
public String call() throws Exception {
return executePostRequestAndReturnResponseAsString(httpClient, url, parameters);
}
});
}
@Nullable
public static String executePostRequestAndReturnResponseAsString(
String url, Object... parameters) throws IOException {
return executePostRequestAndReturnResponseAsString(null, url, parameters);
}
@Nullable
public static String executePostRequestAndReturnResponseAsString(
long executionTimeoutMillis, String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(executionTimeoutMillis, url, new Callable<String>() {
@Nullable
@Override
public String call() throws Exception {
return executePostRequestAndReturnResponseAsString(url, parameters);
}
});
}
public static Response executePostRequestAndReturnResponse(
@Nullable HttpClient httpClient, String url, Object... parameters) throws IOException {
HttpResponse httpResponse = internalExecutePostRequest(httpClient, url, parameters);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
return new Response(httpResponse.getStatusLine().getStatusCode(), null, null, 0, httpResponse);
} else {
return new Response(
httpResponse.getStatusLine().getStatusCode(),
httpEntity.getContent(),
httpEntity.getContentEncoding() == null ? null : httpEntity.getContentEncoding().getValue(),
httpEntity.getContentLength(),
httpResponse
);
}
}
public static Response executePostRequestAndReturnResponse(
long executionTimeoutMillis, HttpClient httpClient,
String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url, () -> executePostRequestAndReturnResponse(httpClient, url, parameters)
);
}
public static Response executePostRequestAndReturnResponse(String url, Object... parameters) throws IOException {
return executePostRequestAndReturnResponse(null, url, parameters);
}
public static Response executePostRequestAndReturnResponse(
long executionTimeoutMillis, String url, Object... parameters) throws IOException {
return internalExecuteLimitedTimeRequest(
executionTimeoutMillis, url, () -> executePostRequestAndReturnResponse(url, parameters)
);
}
private static HttpResponse internalExecutePostRequest(
@Nullable HttpClient httpClient, String url, Object... parameters) throws IOException {
parameters = validateAndPreprocessParameters(false, url, parameters);
httpClient = httpClient == null ? newHttpClient() : httpClient;
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> postParameters = new ArrayList<>();
for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex += 2) {
postParameters.add(new BasicNameValuePair(
(String) parameters[parameterIndex],
parameters[parameterIndex + 1].toString()
));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters, "UTF-8");
httpPost.setEntity(entity);
return httpClient.execute(httpPost);
}
@SuppressWarnings("OverlyComplexMethod")
private static Object[] validateAndPreprocessParameters(
boolean encodeParameters, String url, Object... parameters) {
if (!UrlUtil.isValidUrl(url)) {
throw new IllegalArgumentException('\'' + url + "' is not valid URL.");
}
boolean secureHost;
try {
secureHost = CommonsPropertiesUtil.getSecureHosts().contains(new URL(url).getHost());
} catch (MalformedURLException e) {
throw new IllegalArgumentException('\'' + url + "' is not valid URL.", e);
}
int parameterCount = parameters.length;
if (parameterCount % 2 != 0) {
throw new IllegalArgumentException("Argument 'parameters' should contain even number of elements, " +
"i.e. should consist of key-value pairs."
);
}
List<String> securePasswords = CommonsPropertiesUtil.getSecurePasswords();
boolean preprocessParameters = encodeParameters || !secureHost && !securePasswords.isEmpty();
Object[] parameterCopies = preprocessParameters ? new Object[parameterCount] : null;
for (int parameterIndex = 0; parameterIndex < parameterCount; parameterIndex += 2) {
Object parameterName = parameters[parameterIndex];
Object parameterValue = parameters[parameterIndex + 1];
if (!(parameterName instanceof String) || StringUtil.isBlank((String) parameterName)) {
throw new IllegalArgumentException(String.format(
"Each parameter name should be non-blank string, but found: '%s'.", parameterName
));
}
if (parameterValue == null) {
throw new IllegalArgumentException(String.format("Parameter '%s' is 'null'.", parameterName));
}
if (preprocessParameters) {
try {
parameterCopies[parameterIndex] = encodeParameters
? URLEncoder.encode((String) parameterName, "UTF-8")
: parameterName;
parameterCopies[parameterIndex + 1] = securePasswords.contains(parameterValue.toString())
? ""
: parameterValue;
if (encodeParameters) {
parameterCopies[parameterIndex + 1] = URLEncoder.encode(
parameterCopies[parameterIndex + 1].toString(), "UTF-8"
);
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 is unsupported.", e);
}
}
}
return preprocessParameters ? parameterCopies : parameters;
}
private static <R> R internalExecuteLimitedTimeRequest(
long executionTimeoutMillis, String url, Callable<R> httpTask) throws IOException {
Future<R> requestFuture = timedRequestExecutor.submit(httpTask);
try {
return requestFuture.get(executionTimeoutMillis, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
requestFuture.cancel(true);
throw new IOException("Unexpectedly interrupted while executing HTTP request.", e);
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
} else {
throw new IOException("Can't execute HTTP request.", e);
}
} catch (TimeoutException e) {
new Thread(() -> {
ThreadUtil.sleep(executionTimeoutMillis);
requestFuture.cancel(true);
}).start();
throw new IOException(String.format(
"Can't execute HTTP request to '%s' in %d ms.", url, executionTimeoutMillis
), e);
}
}
public static CloseableHttpClient newHttpClient() {
return internalNewHttpClient(getBasicConnectionManagerBuilder());
}
public static CloseableHttpClient newHttpClient(int connectionTimeoutMillis, int socketTimeoutMillis) {
return internalNewHttpClient(connectionTimeoutMillis, socketTimeoutMillis, getBasicConnectionManagerBuilder());
}
public static CloseableHttpClient newPoolingHttpClient() {
return internalNewHttpClient(getPoolingConnectionManagerBuilder(
CONNECTION_POOL_DEFAULT_MAX_SIZE_PER_HOST, CONNECTION_POOL_DEFAULT_MAX_SIZE
));
}
public static CloseableHttpClient newPoolingHttpClient(int connectionTimeoutMillis, int socketTimeoutMillis) {
return newPoolingHttpClient(
connectionTimeoutMillis, socketTimeoutMillis,
CONNECTION_POOL_DEFAULT_MAX_SIZE_PER_HOST, CONNECTION_POOL_DEFAULT_MAX_SIZE
);
}
public static CloseableHttpClient newPoolingHttpClient(
int connectionTimeoutMillis, int socketTimeoutMillis, int maxPoolSizePerHost, int maxPoolSize) {
return internalNewHttpClient(connectionTimeoutMillis, socketTimeoutMillis, getPoolingConnectionManagerBuilder(
maxPoolSizePerHost, maxPoolSize
));
}
private static CloseableHttpClient internalNewHttpClient(
HttpClientConnectionManagerBuilder connectionManagerBuilder) {
SocketConfig socketConfig = getSocketConfig();
RequestConfig requestConfig = getRequestConfig();
HttpClientConnectionManager connectionManager = connectionManagerBuilder.build(socketConfig);
return internalNewHttpClient(socketConfig, requestConfig, connectionManager);
}
private static CloseableHttpClient internalNewHttpClient(
int connectionTimeoutMillis, int socketTimeoutMillis,
HttpClientConnectionManagerBuilder connectionManagerBuilder) {
SocketConfig socketConfig = getSocketConfig(socketTimeoutMillis);
RequestConfig requestConfig = getRequestConfig(connectionTimeoutMillis, socketTimeoutMillis);
HttpClientConnectionManager connectionManager = connectionManagerBuilder.build(socketConfig);
return internalNewHttpClient(socketConfig, requestConfig, connectionManager);
}
private static CloseableHttpClient internalNewHttpClient(
SocketConfig socketConfig, RequestConfig requestConfig, HttpClientConnectionManager connectionManager) {
return HttpClientBuilder.create()
.setDefaultConnectionConfig(HttpClientImmutableFieldHolder.CONNECTION_CONFIG)
.setDefaultSocketConfig(socketConfig)
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.setRequestExecutor(HttpClientImmutableFieldHolder.HTTP_REQUEST_EXECUTOR)
.setProxy(HttpClientImmutableFieldHolder.HTTP_PROXY)
.build();
}
@Nonnull
private static HttpClientConnectionManagerBuilder getBasicConnectionManagerBuilder() {
return socketConfig -> {
BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
connectionManager.setConnectionConfig(HttpClientImmutableFieldHolder.CONNECTION_CONFIG);
connectionManager.setSocketConfig(socketConfig);
return connectionManager;
};
}
@Nonnull
private static HttpClientConnectionManagerBuilder getPoolingConnectionManagerBuilder(
int maxPoolSizePerHost, int maxPoolSize) {
return socketConfig -> {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
1L, TimeUnit.HOURS
);
connectionManager.setDefaultMaxPerRoute(maxPoolSizePerHost);
connectionManager.setMaxTotal(maxPoolSize);
connectionManager.setDefaultConnectionConfig(HttpClientImmutableFieldHolder.CONNECTION_CONFIG);
connectionManager.setDefaultSocketConfig(socketConfig);
return connectionManager;
};
}
private static SocketConfig getSocketConfig() {
return SocketConfig.DEFAULT;
}
private static SocketConfig getSocketConfig(int socketTimeoutMillis) {
return SocketConfig.copy(SocketConfig.DEFAULT)
.setSoTimeout(socketTimeoutMillis)
.build();
}
private static RequestConfig getRequestConfig() {
return RequestConfig.copy(RequestConfig.DEFAULT)
.setProxy(HttpClientImmutableFieldHolder.HTTP_PROXY)
.build();
}
private static RequestConfig getRequestConfig(int connectionTimeoutMillis, int socketTimeoutMillis) {
return RequestConfig.copy(RequestConfig.DEFAULT)
.setConnectTimeout(connectionTimeoutMillis)
.setConnectionRequestTimeout(connectionTimeoutMillis)
.setSocketTimeout(socketTimeoutMillis)
.setProxy(HttpClientImmutableFieldHolder.HTTP_PROXY)
.build();
}
public static void closeQuietly(
@Nullable CloseableHttpClient httpClient, @Nullable HttpPost request, @Nullable HttpResponse response) {
closeQuietly(response);
closeQuietly(request);
closeQuietly(httpClient);
}
/**
* @param httpClient http client to close
* @param request http request to close
* @param response http response to close
* @deprecated Use {@link #closeQuietly(CloseableHttpClient, HttpPost, HttpResponse)}.
*/
@SuppressWarnings("deprecation")
@Deprecated
public static void closeQuietly(
@Nullable HttpClient httpClient, @Nullable HttpPost request, @Nullable HttpResponse response) {
closeQuietly(response);
closeQuietly(request);
closeQuietly(httpClient);
}
public static void closeQuietly(@Nullable CloseableHttpClient httpClient) {
IoUtil.closeQuietly(httpClient);
}
/**
* @param httpClient http client to close
* @deprecated Use {@link #closeQuietly(CloseableHttpClient)}.
*/
@SuppressWarnings("deprecation")
@Deprecated
public static void closeQuietly(@Nullable HttpClient httpClient) {
if (httpClient instanceof Closeable) {
IoUtil.closeQuietly((AutoCloseable) httpClient);
} else if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
}
public static void closeQuietly(@Nullable HttpPost request) {
if (request != null) {
request.abort();
}
}
public static void closeQuietly(@Nullable HttpResponse response) {
if (response != null) {
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
InputStream content = entity.getContent();
if (content != null) {
content.close();
}
} catch (IllegalStateException | IOException ignored) {
// No operations.
}
}
if (response instanceof Closeable) {
IoUtil.closeQuietly((AutoCloseable) response);
}
}
}
public static final class Response implements Closeable {
private final int responseCode;
@Nullable
private final InputStream inputStream;
@Nullable
private final String charsetName;
private final long contentLength;
private final HttpResponse internalHttpResponse;
private Response(
int responseCode, @Nullable InputStream inputStream, @Nullable String charsetName, long contentLength,
@Nonnull HttpResponse internalHttpResponse) {
this.responseCode = responseCode;
this.inputStream = inputStream;
this.charsetName = charsetName;
this.contentLength = contentLength;
this.internalHttpResponse = internalHttpResponse;
}
public int getResponseCode() {
return responseCode;
}
@Nullable
public InputStream getInputStream() {
return inputStream;
}
@Nullable
public String getCharsetName() {
return charsetName;
}
public long getContentLength() {
return contentLength;
}
@Override
public void close() {
closeQuietly(internalHttpResponse);
}
}
private static final class HttpClientImmutableFieldHolder {
private static final ConnectionConfig CONNECTION_CONFIG = ConnectionConfig.copy(ConnectionConfig.DEFAULT)
.setBufferSize(IoUtil.BUFFER_SIZE)
.build();
private static final HttpRequestExecutor HTTP_REQUEST_EXECUTOR = getHttpRequestExecutor();
@Nullable
private static final HttpHost HTTP_PROXY = getHttpProxy();
@Nonnull
private static HttpRequestExecutor getHttpRequestExecutor() {
return new HttpRequestExecutor() {
@Override
public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context)
throws IOException, HttpException {
try {
return super.execute(request, conn, context);
} catch (IOException e) {
throw new IOException("Can't execute " + request + '.', e);
}
}
};
}
@SuppressWarnings("AccessOfSystemProperties")
@Nullable
private static HttpHost getHttpProxy() {
if (!Boolean.parseBoolean(System.getProperty("proxySet"))) {
return null;
}
String proxyHost = System.getProperty("http.proxyHost");
if (StringUtil.isBlank(proxyHost)) {
return null;
}
int proxyPort;
try {
proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
if (proxyPort <= 0 || proxyPort > 65535) {
return null;
}
} catch (NumberFormatException ignored) {
return null;
}
return new HttpHost(proxyHost, proxyPort);
}
}
private interface HttpClientConnectionManagerBuilder {
HttpClientConnectionManager build(SocketConfig socketConfig);
}
}
| apache-2.0 |
DiceHoldingsInc/orientdb | core/src/test/java/com/orientechnologies/orient/core/db/record/ridbag/sbtree/OSBTreeRidBagConcurrencySingleRidBag.java | 7318 | package com.orientechnologies.orient.core.db.record.ridbag.sbtree;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
import com.orientechnologies.orient.core.exception.OConcurrentModificationException;
import com.orientechnologies.orient.core.id.OClusterPositionFactory;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.intent.OIntentMassiveInsert;
import com.orientechnologies.orient.core.record.impl.ODocument;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
@Test
public class OSBTreeRidBagConcurrencySingleRidBag {
public static final String URL = "plocal:target/testdb/OSBTreeRidBagConcurrencySingleRidBag";
private final AtomicInteger positionCounter = new AtomicInteger();
private final ConcurrentSkipListSet<ORID> ridTree = new ConcurrentSkipListSet<ORID>();
private ORID docContainerRid;
private final CountDownLatch latch = new CountDownLatch(1);
private ExecutorService threadExecutor = Executors.newCachedThreadPool();
private volatile boolean cont = true;
private boolean firstLevelCache;
private boolean secondLevelCache;
private int topThreshold;
private int bottomThreshold;
@BeforeMethod
public void beforeMethod() {
firstLevelCache = OGlobalConfiguration.CACHE_LOCAL_ENABLED.getValueAsBoolean();
topThreshold = OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.getValueAsInteger();
bottomThreshold = OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.getValueAsInteger();
OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(30);
OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.setValue(20);
OGlobalConfiguration.CACHE_LOCAL_ENABLED.setValue(false);
}
@AfterMethod
public void afterMethod() {
OGlobalConfiguration.CACHE_LOCAL_ENABLED.setValue(firstLevelCache);
OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(topThreshold);
OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.setValue(bottomThreshold);
}
public void testConcurrency() throws Exception {
ODatabaseDocumentTx db = new ODatabaseDocumentTx(URL);
if (db.exists()) {
db.open("admin", "admin");
db.drop();
}
db.create();
db.declareIntent(new OIntentMassiveInsert());
ODocument document = new ODocument();
ORidBag ridBag = new ORidBag();
ridBag.setAutoConvertToRecord(false);
document.field("ridBag", ridBag);
for (int i = 0; i < 100; i++) {
final ORID ridToAdd = new ORecordId(0, OClusterPositionFactory.INSTANCE.valueOf(positionCounter.incrementAndGet()));
ridBag.add(ridToAdd);
ridTree.add(ridToAdd);
}
document.save();
docContainerRid = document.getIdentity();
List<Future<Void>> futures = new ArrayList<Future<Void>>();
for (int i = 0; i < 5; i++)
futures.add(threadExecutor.submit(new RidAdder(i)));
for (int i = 0; i < 5; i++)
futures.add(threadExecutor.submit(new RidDeleter(i)));
latch.countDown();
Thread.sleep(30 * 60000);
cont = false;
for (Future<Void> future : futures)
future.get();
document = db.load(document.getIdentity());
document.setLazyLoad(false);
ridBag = document.field("ridBag");
for (OIdentifiable identifiable : ridBag)
Assert.assertTrue(ridTree.remove(identifiable.getIdentity()));
Assert.assertTrue(ridTree.isEmpty());
System.out.println("Result size is " + ridBag.size());
db.close();
}
public class RidAdder implements Callable<Void> {
private final int id;
public RidAdder(int id) {
this.id = id;
}
@Override
public Void call() throws Exception {
latch.await();
int addedRecords = 0;
ODatabaseDocumentTx db = new ODatabaseDocumentTx(URL);
db.open("admin", "admin");
db.declareIntent(new OIntentMassiveInsert());
try {
while (cont) {
List<ORID> ridsToAdd = new ArrayList<ORID>();
for (int i = 0; i < 10; i++) {
ridsToAdd.add(new ORecordId(0, OClusterPositionFactory.INSTANCE.valueOf(positionCounter.incrementAndGet())));
}
while (true) {
ODocument document = db.load(docContainerRid);
document.setLazyLoad(false);
ORidBag ridBag = document.field("ridBag");
for (ORID rid : ridsToAdd)
ridBag.add(rid);
try {
document.save();
} catch (OConcurrentModificationException e) {
continue;
}
break;
}
ridTree.addAll(ridsToAdd);
addedRecords += ridsToAdd.size();
}
} finally {
db.close();
}
System.out.println(RidAdder.class.getSimpleName() + ":" + id + "-" + addedRecords + " were added.");
return null;
}
}
public class RidDeleter implements Callable<Void> {
private final int id;
public RidDeleter(int id) {
this.id = id;
}
@Override
public Void call() throws Exception {
latch.await();
int deletedRecords = 0;
Random rnd = new Random();
ODatabaseDocumentTx db = new ODatabaseDocumentTx(URL);
db.open("admin", "admin");
db.declareIntent(new OIntentMassiveInsert());
try {
while (cont) {
while (true) {
ODocument document = db.load(docContainerRid);
document.setLazyLoad(false);
ORidBag ridBag = document.field("ridBag");
Iterator<OIdentifiable> iterator = ridBag.iterator();
List<ORID> ridsToDelete = new ArrayList<ORID>();
int counter = 0;
while (iterator.hasNext()) {
OIdentifiable identifiable = iterator.next();
if (rnd.nextBoolean()) {
iterator.remove();
counter++;
ridsToDelete.add(identifiable.getIdentity());
}
if (counter >= 5)
break;
}
try {
document.save();
} catch (OConcurrentModificationException e) {
continue;
}
ridTree.removeAll(ridsToDelete);
deletedRecords += ridsToDelete.size();
break;
}
}
} finally {
db.close();
}
System.out.println(RidDeleter.class.getSimpleName() + ":" + id + "-" + deletedRecords + " were deleted.");
return null;
}
}
}
| apache-2.0 |
dragonzhou/humor | src/dutylink/request/RaiseMoneyReq.java | 782 | package dutylink.request;
import dutylink.RequestTypeEnum;
/**
* ¼ÓнÇëÇó
*
* @author: zhoujinlong2014169
* @version: yamen_v3.0
* @time: 2014-10-16
*/
public class RaiseMoneyReq extends Request
{
private int expectedMoney;
public RaiseMoneyReq(String name, RequestTypeEnum requestType, int number)
{
super(name, requestType, number);
}
public int getExpectedMoney()
{
return expectedMoney;
}
public RaiseMoneyReq(String name, RequestTypeEnum requestType, int number, int expectedMoney)
{
super(name, requestType, number);
this.expectedMoney = expectedMoney;
}
public void setExpectedMoney(int expectedMoney)
{
this.expectedMoney = expectedMoney;
}
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_4916.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_4916 {
}
| apache-2.0 |
lessthanoptimal/BoofCV | main/boofcv-sfm/src/test/java/boofcv/alg/sfm/d3/structure/TestSelectTracksInFrameForBundleAdjustment.java | 5012 | /*
* Copyright (c) 2020, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.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 boofcv.alg.sfm.d3.structure;
import boofcv.alg.sfm.d3.structure.SelectTracksInFrameForBundleAdjustment.Info;
import boofcv.alg.sfm.d3.structure.VisOdomBundleAdjustment.BFrame;
import boofcv.alg.sfm.d3.structure.VisOdomBundleAdjustment.BTrack;
import boofcv.struct.calib.CameraPinholeBrown;
import boofcv.testing.BoofStandardJUnit;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static boofcv.alg.sfm.d3.structure.TestMaxGeoKeyFrameManager.connectFrames;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
/**
* @author Peter Abeles
*/
class TestSelectTracksInFrameForBundleAdjustment extends BoofStandardJUnit {
final int width = 100;
final int height = 200;
/**
* Basic test. Each track is visible in every frame at the same location.
*/
@Test
void minimal_all() {
var scene = new VisOdomBundleAdjustment<>(BTrack::new);
var alg = new SelectTracksInFrameForBundleAdjustment(0xBEEF);
alg.configUniform.regionScaleFactor = 1.0; // makes the math easier
alg.maxFeaturesPerFrame = 200;
var selected = new ArrayList<BTrack>();
scene.addCamera(new CameraPinholeBrown(0, 0, 0, 0, 0, width, height));
for (int i = 0; i < 5; i++) {
scene.addFrame(i);
}
for (int i = 0; i < 200; i++) {
scene.tracks.grow().id = i;
}
for (int i = 0; i < scene.frames.size; i++) {
BFrame frame = scene.frames.get(i);
for (int j = 0; j < 200; j++) {
BTrack track = scene.tracks.get(j);
frame.tracks.add(track);
// pixel coordinates
int x = (i*10)%width;
int y = 10*((i*10)/width);
VisOdomBundleAdjustment.BObservation o = track.observations.grow();
o.frame = frame;
o.pixel.setTo(x, y);
}
}
alg.selectTracks(scene, selected);
assertEquals(200, selected.size());
}
@Test
void initializeGrid() {
var scene = new VisOdomBundleAdjustment<>(BTrack::new);
var alg = new SelectTracksInFrameForBundleAdjustment(0xBEEF);
alg.minTrackObservations = 1;
scene.addCamera(new CameraPinholeBrown(0, 0, 0, 0, 0, width, height));
for (int i = 0; i < 3; i++) {
scene.addFrame(i);
}
BFrame targetFrame = scene.frames.get(2);
// create enough tracks for there to be one in each cell
connectFrames(1, 2, 200, scene);
for (int i = 0; i < scene.tracks.size; i++) {
BTrack track = scene.tracks.get(i);
// pixel coordinates
int x = (i*10)%width;
int y = 10*((i*10)/width);
// make sure it's false. should be already
track.selected = false;
track.findObservationBy(targetFrame).pixel.setTo(x, y);
}
// mark this one as active so that it isn't added to a cell. There should only be one empty cell
scene.tracks.get(2).selected = true;
// run it
alg.initializeGrid(targetFrame, width, height, 10);
// There should be one track in all but one cell
for (int i = 0; i < alg.grid.cells.size; i++) {
Info cell = alg.grid.cells.get(i);
if (i != 2) {
assertEquals(0, cell.alreadySelected);
assertEquals(1, cell.unselected.size());
assertSame(scene.tracks.get(i), cell.unselected.get(0));
} else {
assertEquals(1, cell.alreadySelected);
assertEquals(0, cell.unselected.size());
}
}
}
/**
* Simple scenario. One track in each cell and one cell has an already selected track. See if the expected number
* of tracks is returned
*/
@Test
void selectNewTracks() {
var scene = new VisOdomBundleAdjustment<>(BTrack::new);
var alg = new SelectTracksInFrameForBundleAdjustment(0xBEEF);
alg.maxFeaturesPerFrame = 200; // one less than the total number of tracks
alg.grid.initialize(10, width, height);
// populate the grid with one track each
for (int row = 0; row < 20; row++) {
for (int col = 0; col < 10; col++) {
alg.grid.get(row, col).unselected.add(scene.tracks.grow());
}
}
alg.grid.get(1, 1).alreadySelected = 1;
List<BTrack> selected = new ArrayList<>();
alg.selectNewTracks(selected);
assertEquals(199, selected.size());
for (int row = 0; row < 20; row++) {
for (int col = 0; col < 10; col++) {
assertEquals(0, alg.grid.get(row, col).alreadySelected);
if (row == 1 && col == 1)
assertEquals(1, alg.grid.get(row, col).unselected.size());
else
assertEquals(0, alg.grid.get(row, col).unselected.size());
}
}
}
}
| apache-2.0 |
fine1021/Alipay | app/src/main/java/com/yxkang/android/alipay/util/SignaturesUtil.java | 6715 | package com.yxkang.android.alipay.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.DisplayMetrics;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.List;
/**
* Created by fine on 2016/4/28.
*/
public class SignaturesUtil {
private static final String TAG = "SignaturesUtil";
/**
* 获取未安装的APK的签名信息
*
* @param apkPath apk路径
* @return APK的签名信息
*/
@SuppressWarnings("unchecked")
public static String getNotInstalledAPKSignatures(String apkPath) {
String PATH_PackageParser = "android.content.pm.PackageParser";
try {
// apk包的文件路径
// 这是一个Package 解释器, 是隐藏的
// 构造函数的参数只有一个, apk文件的路径
// PackageParser packageParser = new PackageParser(apkPath);
Class pkgParserCls = Class.forName(PATH_PackageParser);
Class[] typeArgs = new Class[1];
typeArgs[0] = String.class;
Constructor pkgParserCt = pkgParserCls.getConstructor(typeArgs);
Object[] valueArgs = new Object[1];
valueArgs[0] = apkPath;
Object pkgParser = pkgParserCt.newInstance(valueArgs);
Log.i(TAG, "showUninstallAPKSignatures: pkgParser = " + pkgParser.toString());
// 这个是与显示有关的, 里面涉及到一些像素显示等等, 我们使用默认的情况
DisplayMetrics metrics = new DisplayMetrics();
metrics.setToDefaults();
// PackageParser.Package mPkgInfo = packageParser.parsePackage(new
// File(apkPath), apkPath,
// metrics, 0);
typeArgs = new Class[4];
typeArgs[0] = File.class;
typeArgs[1] = String.class;
typeArgs[2] = DisplayMetrics.class;
typeArgs[3] = Integer.TYPE;
Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage",
typeArgs);
valueArgs = new Object[4];
valueArgs[0] = new File(apkPath);
valueArgs[1] = apkPath;
valueArgs[2] = metrics;
valueArgs[3] = PackageManager.GET_SIGNATURES;
Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs);
typeArgs = new Class[2];
typeArgs[0] = pkgParserPkg.getClass();
typeArgs[1] = Integer.TYPE;
Method pkgParser_collectCertificatesMtd = pkgParserCls.getDeclaredMethod("collectCertificates",
typeArgs);
valueArgs = new Object[2];
valueArgs[0] = pkgParserPkg;
valueArgs[1] = PackageManager.GET_SIGNATURES;
pkgParser_collectCertificatesMtd.invoke(pkgParser, valueArgs);
// 应用程序信息包, 这个公开的, 不过有些函数, 变量没公开
Field packageInfoFld = pkgParserPkg.getClass().getDeclaredField("mSignatures");
Signature[] info = (Signature[]) packageInfoFld.get(pkgParserPkg);
Log.i(TAG, "showUninstallAPKSignatures: size = " + info.length);
Log.i(TAG, "showUninstallAPKSignatures: " + info[0].toCharsString());
return info[0].toCharsString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取app自身的签名
*
* @param context 上下文
* @return app自身的签名
*/
public static String getSelfSignatures(Context context) {
PackageManager pm = context.getPackageManager();
List<PackageInfo> apps = pm.getInstalledPackages(PackageManager.GET_SIGNATURES);
for (PackageInfo packageinfo : apps) {
String packageName = packageinfo.packageName;
if (packageName.equals(context.getPackageName())) {
Signature[] signatures = packageinfo.signatures;
if (signatures == null || signatures.length == 0) {
return null;
}
Log.i(TAG, "getSelfSignatures: length = " + signatures.length);
StringBuilder buffer = new StringBuilder();
for (Signature signature : signatures) {
buffer.append(MD5.getMessageDigest(signature.toByteArray()));
}
Log.i(TAG, "getSelfSignatures: " + buffer.toString());
parseSignature(signatures[0].toByteArray());
return buffer.toString();
}
}
return null;
}
/**
* 获取已安装的app的签名信息
*
* @param context 上下文
*/
@SuppressLint("PackageManagerGetSignatures")
public static void getInstalledAPKSignatures(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo("com.yxkang.android.alipay",
PackageManager.GET_SIGNATURES);
Signature[] signs = packageInfo.signatures;
if (signs == null || signs.length == 0) {
return;
}
StringBuilder buffer = new StringBuilder();
for (Signature signature : signs) {
buffer.append(MD5.getMessageDigest(signature.toByteArray()));
}
Log.i(TAG, "getInstalledAPKSignatures: " + buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private static void parseSignature(byte[] signature) {
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(signature));
String pubKey = cert.getPublicKey().toString();
String signNumber = cert.getSerialNumber().toString();
Log.i(TAG, "parseSignature: signName = " + cert.getSigAlgName());
Log.i(TAG, "parseSignature: pubKey = " + pubKey);
Log.i(TAG, "parseSignature: signNumber = " + signNumber);
Log.i(TAG, "parseSignature: subjectDN = "+cert.getSubjectDN().toString());
} catch (CertificateException e) {
e.printStackTrace();
}
}
}
| apache-2.0 |
rdblue/incubator-nifi | nifi-api/src/main/java/org/apache/nifi/controller/status/history/StatusSnapshot.java | 1538 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.controller.status.history;
import java.util.Date;
import java.util.Map;
/**
* A StatusSnapshot represents a Component's status report at some point in time
*/
public interface StatusSnapshot {
/**
* Rreturns the point in time for which the status values were obtained
*
* @return
*/
Date getTimestamp();
/**
* Returns a Map of MetricDescriptor to value
*
* @return
*/
Map<MetricDescriptor<?>, Long> getStatusMetrics();
/**
* Returns a {@link ValueReducer} that is capable of merging multiple
* StatusSnapshot objects into a single one
*
* @return
*/
ValueReducer<StatusSnapshot, StatusSnapshot> getValueReducer();
}
| apache-2.0 |
xushaomin/appleframework | apple-commons/src/main/java/com/appleframework/logging/StaticLog.java | 7228 | package com.appleframework.logging;
import com.appleframework.logging.level.Level;
import com.appleframework.tools.lang.caller.CallerUtil;
import com.appleframework.tools.util.StrUtil;
/**
* 静态日志类,用于在不引入日志对象的情况下打印日志
*
* @author cruise.xu
*
*/
public final class StaticLog {
private static final String FQCN = StaticLog.class.getName();
private StaticLog() {
}
// ----------------------------------------------------------- Log method start
// ------------------------ Trace
/**
* Trace等级日志,小于debug<br>
* 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!!
*
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void trace(String format, Object... arguments) {
trace(LogFactory.get(CallerUtil.getCallerCaller()), format, arguments);
}
/**
* Trace等级日志,小于Debug
*
* @param log 日志对象
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void trace(Log log, String format, Object... arguments) {
log.trace(FQCN, null, format, arguments);
}
// ------------------------ debug
/**
* Debug等级日志,小于Info<br>
* 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!!
*
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void debug(String format, Object... arguments) {
debug(LogFactory.get(CallerUtil.getCallerCaller()), format, arguments);
}
/**
* Debug等级日志,小于Info
*
* @param log 日志对象
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void debug(Log log, String format, Object... arguments) {
log.debug(FQCN, null, format, arguments);
}
// ------------------------ info
/**
* Info等级日志,小于Warn<br>
* 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!!
*
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void info(String format, Object... arguments) {
info(LogFactory.get(CallerUtil.getCallerCaller()), format, arguments);
}
/**
* Info等级日志,小于Warn
*
* @param log 日志对象
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void info(Log log, String format, Object... arguments) {
log.info(FQCN, null, format, arguments);
}
// ------------------------ warn
/**
* Warn等级日志,小于Error<br>
* 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!!
*
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void warn(String format, Object... arguments) {
warn(LogFactory.get(CallerUtil.getCallerCaller()), format, arguments);
}
/**
* Warn等级日志,小于Error<br>
* 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!!
*
* @param e 需在日志中堆栈打印的异常
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void warn(Throwable e, String format, Object... arguments) {
warn(LogFactory.get(CallerUtil.getCallerCaller()), e, StrUtil.format(format, arguments));
}
/**
* Warn等级日志,小于Error
*
* @param log 日志对象
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void warn(Log log, String format, Object... arguments) {
warn(log, null, format, arguments);
}
/**
* Warn等级日志,小于Error
*
* @param log 日志对象
* @param e 需在日志中堆栈打印的异常
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void warn(Log log, Throwable e, String format, Object... arguments) {
log.warn(FQCN, e, format, arguments);
}
// ------------------------ error
/**
* Error等级日志<br>
* 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!!
*
* @param e 需在日志中堆栈打印的异常
*/
public static void error(Throwable e) {
error(LogFactory.get(CallerUtil.getCallerCaller()), e);
}
/**
* Error等级日志<br>
* 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!!
*
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void error(String format, Object... arguments) {
error(LogFactory.get(CallerUtil.getCallerCaller()), format, arguments);
}
/**
* Error等级日志<br>
* 由于动态获取Log,效率较低,建议在非频繁调用的情况下使用!!
*
* @param e 需在日志中堆栈打印的异常
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void error(Throwable e, String format, Object... arguments) {
error(LogFactory.get(CallerUtil.getCallerCaller()), e, format, arguments);
}
/**
* Error等级日志<br>
*
* @param log 日志对象
* @param e 需在日志中堆栈打印的异常
*/
public static void error(Log log, Throwable e) {
error(log, e, e.getMessage());
}
/**
* Error等级日志<br>
*
* @param log 日志对象
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void error(Log log, String format, Object... arguments) {
error(log, null, format, arguments);
}
/**
* Error等级日志<br>
*
* @param log 日志对象
* @param e 需在日志中堆栈打印的异常
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void error(Log log, Throwable e, String format, Object... arguments) {
log.error(FQCN, e, format, arguments);
}
// ------------------------ Log
/**
* 打印日志<br>
*
* @param level 日志级别
* @param t 需在日志中堆栈打印的异常
* @param format 格式文本,{} 代表变量
* @param arguments 变量对应的参数
*/
public static void log(Level level, Throwable t, String format, Object... arguments) {
LogFactory.get(CallerUtil.getCallerCaller()).log(FQCN, level, t, format, arguments);
}
// ----------------------------------------------------------- Log method end
/**
* 获得Log
*
* @param clazz 日志发出的类
* @return Log
* @deprecated 请使用 {@link Log#get(Class)}
*/
@Deprecated
public static Log get(Class<?> clazz) {
return LogFactory.get(clazz);
}
/**
* 获得Log
*
* @param name 自定义的日志发出者名称
* @return Log
* @deprecated 请使用 {@link Log#get(String)}
*/
@Deprecated
public static Log get(String name) {
return LogFactory.get(name);
}
/**
* @return 获得日志,自动判定日志发出者
* @deprecated 请使用 {@link Log#get()}
*/
@Deprecated
public static Log get() {
return LogFactory.get(CallerUtil.getCallerCaller());
}
}
| apache-2.0 |
mifos/1.4.x | application/src/test/java/org/mifos/application/accounts/financial/util/helpers/FinancialInitializerIntegrationTest.java | 2458 | /*
* Copyright (c) 2005-2009 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.application.accounts.financial.util.helpers;
import junit.framework.Assert;
import org.mifos.application.accounts.financial.business.COABO;
import org.mifos.application.accounts.financial.business.FinancialActionBO;
import org.mifos.application.accounts.financial.business.GLCategoryType;
import org.mifos.application.accounts.financial.exceptions.FinancialException;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.SystemException;
public class FinancialInitializerIntegrationTest extends MifosIntegrationTestCase {
public FinancialInitializerIntegrationTest() throws SystemException, ApplicationException {
super();
}
public void testAssetsCategoryIsCached() throws Exception {
String assetsGlCode = "10000";
COABO account1 = ChartOfAccountsCache.get(assetsGlCode);
Assert.assertEquals(GLCategoryType.ASSET, account1.getCategoryType());
}
public void testFinancialActionInitializer() throws FinancialException {
FinancialInitializer.initalizeFinancialAction();
FinancialActionBO financialActionPrincipal = FinancialActionCache
.getFinancialAction(FinancialActionConstants.PRINCIPALPOSTING);
Assert.assertEquals(financialActionPrincipal.getId().shortValue(), FinancialActionConstants.PRINCIPALPOSTING.value);
}
public void testCOACacherException() throws Exception {
try {
ChartOfAccountsCache.get("-1");
Assert.fail("Expected FinancialException.");
} catch (FinancialException e) {
// do nothing
}
}
}
| apache-2.0 |
manavista/LessonManager | app/src/main/java/jp/manavista/lessonmanager/model/entity/MemberLesson.java | 1135 | /*
* Copyright (c) 2017 manavista. All rights reserved.
*/
package jp.manavista.lessonmanager.model.entity;
import com.github.gfx.android.orma.annotation.Column;
import com.github.gfx.android.orma.annotation.PrimaryKey;
import com.github.gfx.android.orma.annotation.Table;
import java.sql.Time;
import lombok.ToString;
/**
*
* MemberLesson
*
* <p>
* Overview:<br>
* Define the regular lesson data of member.
* </p>
*/
@Table
@ToString
public class MemberLesson {
@PrimaryKey(autoincrement = true)
public long id;
@Column(indexed = true)
public long memberId;
@Column
public String name;
@Column
public String abbr;
@Column
public String type;
@Column
public String location;
@Column
public String presenter;
@Column
public int textColor;
@Column
public int backgroundColor;
@Column
public Time startTime;
@Column
public Time endTime;
@Column
public String dayOfWeeks;
@Column
public String periodFrom;
@Column(indexed = true)
public String periodTo;
@Column(indexed = true)
public Member member;
}
| apache-2.0 |
MyRobotLab/myrobotlab | src/main/java/org/myrobotlab/service/JFugue.java | 2876 | /**
*
* @author grog (at) myrobotlab.org
*
* This file is part of MyRobotLab (http://myrobotlab.org).
*
* MyRobotLab is free software: you can redistribute it and/or modify
* it under the terms of the Apache License 2.0 as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* MyRobotLab is distributed in the hope that it will be useful or fun,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Apache License 2.0 for more details.
*
* All libraries in thirdParty bundle are subject to their own license
* requirements - please refer to http://myrobotlab.org/libraries for
* details.
*
* Enjoy !
*
* */
package org.myrobotlab.service;
import org.jfugue.player.Player;
import org.jfugue.rhythm.Rhythm;
import org.myrobotlab.framework.Service;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.slf4j.Logger;
/**
* JFugue - This service can generate tones to be played Also it can generate
* some sounds and music based on string patterns that define the beat.
*
*/
public class JFugue extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(JFugue.class);
// transient public ManagedPlayer player = new ManagedPlayer();
transient public Player player = new Player();
// TODO - look at JavaSoundDemo - they have a synth & mixer there
public static void main(String[] args) {
LoggingFactory.init(Level.DEBUG);
JFugue jfugue = (JFugue) Runtime.start("jfugue", "JFugue");
jfugue.play("C");
jfugue.playRythm("O..oO...O..oOO..");
jfugue.play("C");
jfugue.play("C7h");
jfugue.play("C5maj7w");
}
public JFugue(String n, String id) {
super(n, id);
}
public void play(Integer i) { // play tone
// player.play("[A" + i + "]w");
player.play("[" + i + "]");
}
public void play(Rhythm rythm) {
player.play(rythm);
}
public void play(String s) {
player.play(s);
}
public void playRythm(String data) {
Rhythm rhythm = new Rhythm();
rhythm.addLayer(data);
player.play(rhythm.getPattern());
/*
* rhythm.setLayer(1, "O..oO...O..oOO.."); rhythm.setLayer(2,
* "..*...*...*...*."); rhythm.addSubstitution('O', "[BASS_DRUM]i");
* rhythm.addSubstitution('o', "Rs [BASS_DRUM]s");
* rhythm.addSubstitution('*', "[ACOUSTIC_SNARE]i");
* rhythm.addSubstitution('.', "Ri");
*
* play(rhythm);
*/
}
}
| apache-2.0 |
davidmoten/rxjava-parallel | src/main/java/rx/observables/ParallelObservable.java | 60848 | package rx.observables;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import rx.Notification;
import rx.Observable;
import rx.Observer;
import rx.Scheduler;
import rx.Observable.Operator;
import rx.Observable.Transformer;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Action2;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.functions.Functions;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import rx.schedulers.TimeInterval;
import rx.schedulers.Timestamped;
import rx.subjects.Subject;
/**
* The Observable class that implements the Reactive Pattern.
* <p>
* This class provides methods for subscribing to the Observable as well as
* delegate methods to the various Observers.
* <p>
* The documentation for this class makes use of marble diagrams. The following
* legend explains these diagrams:
* <p>
* <img width="640" height="301" src=
* "https://raw.github.com/wiki/Netflix/RxJava/images/rx-operators/legend.png"
* alt="">
* <p>
* For more information see the <a
* href="https://github.com/Netflix/RxJava/wiki/Observable">RxJava wiki</a>
*
* @param <T>
* the type of the items emitted by the Observable
*/
public class ParallelObservable<T> {
private final Observable<Observable<T>> source;
private ParallelObservable(Observable<Observable<T>> source) {
this.source = source;
}
public static <T> ParallelObservable<T> parallel(Observable<T> o,
final Scheduler scheduler) {
return create(o.map(new Func1<T, Observable<T>>() {
@Override
public Observable<T> call(T t) {
return Observable.just(t).subscribeOn(scheduler);
}
}));
}
public static <T> ParallelObservable<T> parallel(Observable<T> o) {
return parallel(o, Schedulers.computation());
}
public static final <T> ParallelObservable<T> create(
Observable<Observable<T>> source) {
return new ParallelObservable<T>(source);
}
private <R> ParallelObservable<R> create(
Func1<Observable<T>, Observable<R>> f) {
return create(source.map(f));
}
public Observable<T> flatten() {
return source.flatMap(new Func1<Observable<T>,Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o;
}});
}
/*****************************************************************
* Generated methods below
****************************************************************/
public final <R> ParallelObservable<R> lift(
final Operator<? extends R, ? super T> lift) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.lift(lift);
}
});
}
public final <R> ParallelObservable<R> compose(
final Transformer<? super T, R> transformer) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.compose(transformer);
}
});
}
public final ParallelObservable<Observable<T>> nest() {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.nest();
}
});
}
public final ParallelObservable<Boolean> all(
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<Boolean>>() {
@Override
public Observable<Boolean> call(Observable<T> o) {
return o.all(predicate);
}
});
}
public final ParallelObservable<T> ambWith(final Observable<? extends T> t1) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.ambWith(t1);
}
});
}
public final ParallelObservable<T> asObservable() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.asObservable();
}
});
}
public final <TClosing> ParallelObservable<List<T>> buffer(
final Func0<? extends Observable<? extends TClosing>> bufferClosingSelector) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(bufferClosingSelector);
}
});
}
public final ParallelObservable<List<T>> buffer(final int count) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(count);
}
});
}
public final ParallelObservable<List<T>> buffer(final int count,
final int skip) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(count, skip);
}
});
}
public final ParallelObservable<List<T>> buffer(final long timespan,
final long timeshift, final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(timespan, timeshift, unit);
}
});
}
public final ParallelObservable<List<T>> buffer(final long timespan,
final long timeshift, final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(timespan, timeshift, unit, scheduler);
}
});
}
public final ParallelObservable<List<T>> buffer(final long timespan,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(timespan, unit);
}
});
}
public final ParallelObservable<List<T>> buffer(final long timespan,
final TimeUnit unit, final int count) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(timespan, unit, count);
}
});
}
public final ParallelObservable<List<T>> buffer(final long timespan,
final TimeUnit unit, final int count, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(timespan, unit, count, scheduler);
}
});
}
public final ParallelObservable<List<T>> buffer(final long timespan,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(timespan, unit, scheduler);
}
});
}
public final <TOpening, TClosing> ParallelObservable<List<T>> buffer(
final Observable<? extends TOpening> bufferOpenings,
final Func1<? super TOpening, ? extends Observable<? extends TClosing>> bufferClosingSelector) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(bufferOpenings, bufferClosingSelector);
}
});
}
public final <B> ParallelObservable<List<T>> buffer(
final Observable<B> boundary) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(boundary);
}
});
}
public final <B> ParallelObservable<List<T>> buffer(
final Observable<B> boundary, final int initialCapacity) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.buffer(boundary, initialCapacity);
}
});
}
public final ParallelObservable<T> cache() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.cache();
}
});
}
public final ParallelObservable<T> cache(final int capacity) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.cache(capacity);
}
});
}
public final <R> ParallelObservable<R> cast(final Class<R> klass) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.cast(klass);
}
});
}
// public final <R> ParallelObservable<R> collect(final R state,
// final Action2<R, ? super T> collector) {
// return create(new Func1<Observable<T>, Observable<R>>() {
// @Override
// public Observable<R> call(Observable<T> o) {
// return o.collect(state, collector);
// }
// });
// }
public final <R> ParallelObservable<R> concatMap(
final Func1<? super T, ? extends Observable<? extends R>> func) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.concatMap(func);
}
});
}
public final ParallelObservable<T> concatWith(
final Observable<? extends T> t1) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.concatWith(t1);
}
});
}
public final ParallelObservable<Boolean> contains(final Object element) {
return create(new Func1<Observable<T>, Observable<Boolean>>() {
@Override
public Observable<Boolean> call(Observable<T> o) {
return o.contains(element);
}
});
}
public final ParallelObservable<Integer> count() {
return create(new Func1<Observable<T>, Observable<Integer>>() {
@Override
public Observable<Integer> call(Observable<T> o) {
return o.count();
}
});
}
public final <U> ParallelObservable<T> debounce(
final Func1<? super T, ? extends Observable<U>> debounceSelector) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.debounce(debounceSelector);
}
});
}
public final ParallelObservable<T> debounce(final long timeout,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.debounce(timeout, unit);
}
});
}
public final ParallelObservable<T> debounce(final long timeout,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.debounce(timeout, unit, scheduler);
}
});
}
public final ParallelObservable<T> defaultIfEmpty(final T defaultValue) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.defaultIfEmpty(defaultValue);
}
});
}
public final <U, V> ParallelObservable<T> delay(
final Func0<? extends Observable<U>> subscriptionDelay,
final Func1<? super T, ? extends Observable<V>> itemDelay) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.delay(subscriptionDelay, itemDelay);
}
});
}
public final <U> ParallelObservable<T> delay(
final Func1<? super T, ? extends Observable<U>> itemDelay) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.delay(itemDelay);
}
});
}
public final ParallelObservable<T> delay(final long delay,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.delay(delay, unit);
}
});
}
public final ParallelObservable<T> delay(final long delay,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.delay(delay, unit, scheduler);
}
});
}
public final ParallelObservable<T> delaySubscription(final long delay,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.delaySubscription(delay, unit);
}
});
}
public final ParallelObservable<T> delaySubscription(final long delay,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.delaySubscription(delay, unit, scheduler);
}
});
}
public final <T2> ParallelObservable<T2> dematerialize() {
return create(new Func1<Observable<T>, Observable<T2>>() {
@Override
public Observable<T2> call(Observable<T> o) {
return o.dematerialize();
}
});
}
public final ParallelObservable<T> distinct() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.distinct();
}
});
}
public final <U> ParallelObservable<T> distinct(
final Func1<? super T, ? extends U> keySelector) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.distinct(keySelector);
}
});
}
public final ParallelObservable<T> distinctUntilChanged() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.distinctUntilChanged();
}
});
}
public final <U> ParallelObservable<T> distinctUntilChanged(
final Func1<? super T, ? extends U> keySelector) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.distinctUntilChanged(keySelector);
}
});
}
public final ParallelObservable<T> doOnCompleted(final Action0 onCompleted) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.doOnCompleted(onCompleted);
}
});
}
public final ParallelObservable<T> doOnEach(
final Action1<Notification<? super T>> onNotification) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.doOnEach(onNotification);
}
});
}
public final ParallelObservable<T> doOnEach(
final Observer<? super T> observer) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.doOnEach(observer);
}
});
}
public final ParallelObservable<T> doOnError(
final Action1<Throwable> onError) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.doOnError(onError);
}
});
}
public final ParallelObservable<T> doOnNext(final Action1<? super T> onNext) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.doOnNext(onNext);
}
});
}
public final ParallelObservable<T> doOnSubscribe(final Action0 subscribe) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.doOnSubscribe(subscribe);
}
});
}
public final ParallelObservable<T> doOnTerminate(final Action0 onTerminate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.doOnTerminate(onTerminate);
}
});
}
public final ParallelObservable<T> doOnUnsubscribe(final Action0 unsubscribe) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.doOnUnsubscribe(unsubscribe);
}
});
}
public final ParallelObservable<T> elementAt(final int index) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.elementAt(index);
}
});
}
public final ParallelObservable<T> elementAtOrDefault(final int index,
final T defaultValue) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.elementAtOrDefault(index, defaultValue);
}
});
}
public final ParallelObservable<Boolean> exists(
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<Boolean>>() {
@Override
public Observable<Boolean> call(Observable<T> o) {
return o.exists(predicate);
}
});
}
public final ParallelObservable<T> filter(
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.filter(predicate);
}
});
}
public final ParallelObservable<T> finallyDo(final Action0 action) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.finallyDo(action);
}
});
}
public final ParallelObservable<T> first() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.first();
}
});
}
public final ParallelObservable<T> first(
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.first(predicate);
}
});
}
public final ParallelObservable<T> firstOrDefault(final T defaultValue) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.firstOrDefault(defaultValue);
}
});
}
public final ParallelObservable<T> firstOrDefault(final T defaultValue,
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.firstOrDefault(defaultValue, predicate);
}
});
}
public final <R> ParallelObservable<R> flatMap(
final Func1<? super T, ? extends Observable<? extends R>> func) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.flatMap(func);
}
});
}
public final <R> ParallelObservable<R> flatMap(
final Func1<? super T, ? extends Observable<? extends R>> onNext,
final Func1<? super Throwable, ? extends Observable<? extends R>> onError,
final Func0<? extends Observable<? extends R>> onCompleted) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.flatMap(onNext, onError, onCompleted);
}
});
}
public final <U, R> ParallelObservable<R> flatMap(
final Func1<? super T, ? extends Observable<? extends U>> collectionSelector,
final Func2<? super T, ? super U, ? extends R> resultSelector) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.flatMap(collectionSelector, resultSelector);
}
});
}
public final <R> ParallelObservable<R> flatMapIterable(
final Func1<? super T, ? extends Iterable<? extends R>> collectionSelector) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.flatMapIterable(collectionSelector);
}
});
}
public final <U, R> ParallelObservable<R> flatMapIterable(
final Func1<? super T, ? extends Iterable<? extends U>> collectionSelector,
final Func2<? super T, ? super U, ? extends R> resultSelector) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.flatMapIterable(collectionSelector, resultSelector);
}
});
}
public final <K, R> ParallelObservable<GroupedObservable<K, R>> groupBy(
final Func1<? super T, ? extends K> keySelector,
final Func1<? super T, ? extends R> elementSelector) {
return create(new Func1<Observable<T>, Observable<GroupedObservable<K, R>>>() {
@Override
public Observable<GroupedObservable<K, R>> call(Observable<T> o) {
return o.groupBy(keySelector, elementSelector);
}
});
}
public final <K> ParallelObservable<GroupedObservable<K, T>> groupBy(
final Func1<? super T, ? extends K> keySelector) {
return create(new Func1<Observable<T>, Observable<GroupedObservable<K, T>>>() {
@Override
public Observable<GroupedObservable<K, T>> call(Observable<T> o) {
return o.groupBy(keySelector);
}
});
}
public final <T2, D1, D2, R> ParallelObservable<R> groupJoin(
final Observable<T2> right,
final Func1<? super T, ? extends Observable<D1>> leftDuration,
final Func1<? super T2, ? extends Observable<D2>> rightDuration,
final Func2<? super T, ? super Observable<T2>, ? extends R> resultSelector) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.groupJoin(right, leftDuration, rightDuration,
resultSelector);
}
});
}
public final ParallelObservable<T> ignoreElements() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.ignoreElements();
}
});
}
public final ParallelObservable<Boolean> isEmpty() {
return create(new Func1<Observable<T>, Observable<Boolean>>() {
@Override
public Observable<Boolean> call(Observable<T> o) {
return o.isEmpty();
}
});
}
public final <TRight, TLeftDuration, TRightDuration, R> ParallelObservable<R> join(
final Observable<TRight> right,
final Func1<T, Observable<TLeftDuration>> leftDurationSelector,
final Func1<TRight, Observable<TRightDuration>> rightDurationSelector,
final Func2<T, TRight, R> resultSelector) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.join(right, leftDurationSelector,
rightDurationSelector, resultSelector);
}
});
}
public final ParallelObservable<T> last() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.last();
}
});
}
public final ParallelObservable<T> last(
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.last(predicate);
}
});
}
public final ParallelObservable<T> lastOrDefault(final T defaultValue) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.lastOrDefault(defaultValue);
}
});
}
public final ParallelObservable<T> lastOrDefault(final T defaultValue,
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.lastOrDefault(defaultValue, predicate);
}
});
}
public final ParallelObservable<T> limit(final int num) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.limit(num);
}
});
}
public final ParallelObservable<Long> countLong() {
return create(new Func1<Observable<T>, Observable<Long>>() {
@Override
public Observable<Long> call(Observable<T> o) {
return o.countLong();
}
});
}
public final <R> ParallelObservable<R> map(
final Func1<? super T, ? extends R> func) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.map(func);
}
});
}
public final ParallelObservable<Notification<T>> materialize() {
return create(new Func1<Observable<T>, Observable<Notification<T>>>() {
@Override
public Observable<Notification<T>> call(Observable<T> o) {
return o.materialize();
}
});
}
public final ParallelObservable<T> mergeWith(
final Observable<? extends T> t1) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.mergeWith(t1);
}
});
}
public final ParallelObservable<T> observeOn(final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.observeOn(scheduler);
}
});
}
public final <R> ParallelObservable<R> ofType(final Class<R> klass) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.ofType(klass);
}
});
}
public final ParallelObservable<T> onBackpressureBuffer() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.onBackpressureBuffer();
}
});
}
public final ParallelObservable<T> onBackpressureDrop() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.onBackpressureDrop();
}
});
}
public final ParallelObservable<T> onErrorResumeNext(
final Func1<Throwable, ? extends Observable<? extends T>> resumeFunction) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.onErrorResumeNext(resumeFunction);
}
});
}
public final ParallelObservable<T> onErrorResumeNext(
final Observable<? extends T> resumeSequence) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.onErrorResumeNext(resumeSequence);
}
});
}
public final ParallelObservable<T> onErrorReturn(
final Func1<Throwable, ? extends T> resumeFunction) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.onErrorReturn(resumeFunction);
}
});
}
public final ParallelObservable<T> onExceptionResumeNext(
final Observable<? extends T> resumeSequence) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.onExceptionResumeNext(resumeSequence);
}
});
}
public final <R> ParallelObservable<R> publish(
final Func1<? super Observable<T>, ? extends Observable<R>> selector) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.publish(selector);
}
});
}
public final ParallelObservable<T> reduce(final Func2<T, T, T> accumulator) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.reduce(accumulator);
}
});
}
public final <R> ParallelObservable<R> reduce(final R initialValue,
final Func2<R, ? super T, R> accumulator) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.reduce(initialValue, accumulator);
}
});
}
public final ParallelObservable<T> repeat() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.repeat();
}
});
}
public final ParallelObservable<T> repeat(final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.repeat(scheduler);
}
});
}
public final ParallelObservable<T> repeat(final long count) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.repeat(count);
}
});
}
public final ParallelObservable<T> repeat(final long count,
final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.repeat(count, scheduler);
}
});
}
// public final ParallelObservable<T> repeatWhen(
// final Func1<? super Observable<? extends Notification<?>>, ? extends Observable<?>> notificationHandler,
// final Scheduler scheduler) {
// return create(new Func1<Observable<T>, Observable<T>>() {
// @Override
// public Observable<T> call(Observable<T> o) {
// return o.repeatWhen(notificationHandler, scheduler);
// }
// });
// }
// public final ParallelObservable<T> repeatWhen(
// final Func1<? super Observable<? extends Notification<?>>, ? extends Observable<?>> notificationHandler) {
// return create(new Func1<Observable<T>, Observable<T>>() {
// @Override
// public Observable<T> call(Observable<T> o) {
// return o.repeatWhen(notificationHandler);
// }
// });
// }
public final <R> ParallelObservable<R> replay(
final Func1<? super Observable<T>, ? extends Observable<R>> selector) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.replay(selector);
}
});
}
public final <R> ParallelObservable<R> replay(
final Func1<? super Observable<T>, ? extends Observable<R>> selector,
final int bufferSize) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.replay(selector, bufferSize);
}
});
}
public final <R> ParallelObservable<R> replay(
final Func1<? super Observable<T>, ? extends Observable<R>> selector,
final int bufferSize, final long time, final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.replay(selector, bufferSize, time, unit);
}
});
}
public final <R> ParallelObservable<R> replay(
final Func1<? super Observable<T>, ? extends Observable<R>> selector,
final int bufferSize, final long time, final TimeUnit unit,
final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.replay(selector, bufferSize, time, unit, scheduler);
}
});
}
public final <R> ParallelObservable<R> replay(
final Func1<? super Observable<T>, ? extends Observable<R>> selector,
final int bufferSize, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.replay(selector, bufferSize, scheduler);
}
});
}
public final <R> ParallelObservable<R> replay(
final Func1<? super Observable<T>, ? extends Observable<R>> selector,
final long time, final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.replay(selector, time, unit);
}
});
}
public final <R> ParallelObservable<R> replay(
final Func1<? super Observable<T>, ? extends Observable<R>> selector,
final long time, final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.replay(selector, time, unit, scheduler);
}
});
}
public final <R> ParallelObservable<R> replay(
final Func1<? super Observable<T>, ? extends Observable<R>> selector,
final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.replay(selector, scheduler);
}
});
}
public final ParallelObservable<T> retry() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.retry();
}
});
}
public final ParallelObservable<T> retry(final long count) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.retry(count);
}
});
}
public final ParallelObservable<T> retry(
final Func2<Integer, Throwable, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.retry(predicate);
}
});
}
// public final ParallelObservable<T> retryWhen(
// final Func1<? super Observable<? extends Notification<?>>, ? extends Observable<?>> notificationHandler) {
// return create(new Func1<Observable<T>, Observable<T>>() {
// @Override
// public Observable<T> call(Observable<T> o) {
// return o.retryWhen(notificationHandler);
// }
// });
// }
// public final ParallelObservable<T> retryWhen(
// final Func1<? super Observable<? extends Notification<?>>, ? extends Observable<?>> notificationHandler,
// final Scheduler scheduler) {
// return create(new Func1<Observable<T>, Observable<T>>() {
// @Override
// public Observable<T> call(Observable<T> o) {
// return o.retryWhen(notificationHandler, scheduler);
// }
// });
// }
public final ParallelObservable<T> sample(final long period,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.sample(period, unit);
}
});
}
public final ParallelObservable<T> sample(final long period,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.sample(period, unit, scheduler);
}
});
}
public final <U> ParallelObservable<T> sample(final Observable<U> sampler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.sample(sampler);
}
});
}
public final ParallelObservable<T> scan(final Func2<T, T, T> accumulator) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.scan(accumulator);
}
});
}
public final <R> ParallelObservable<R> scan(final R initialValue,
final Func2<R, ? super T, R> accumulator) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.scan(initialValue, accumulator);
}
});
}
public final ParallelObservable<T> serialize() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.serialize();
}
});
}
public final ParallelObservable<T> share() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.share();
}
});
}
public final ParallelObservable<T> single() {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.single();
}
});
}
public final ParallelObservable<T> single(
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.single(predicate);
}
});
}
public final ParallelObservable<T> singleOrDefault(final T defaultValue) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.singleOrDefault(defaultValue);
}
});
}
public final ParallelObservable<T> singleOrDefault(final T defaultValue,
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.singleOrDefault(defaultValue, predicate);
}
});
}
public final ParallelObservable<T> skip(final int num) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.skip(num);
}
});
}
public final ParallelObservable<T> skip(final long time, final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.skip(time, unit);
}
});
}
public final ParallelObservable<T> skip(final long time,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.skip(time, unit, scheduler);
}
});
}
public final ParallelObservable<T> skipLast(final int count) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.skipLast(count);
}
});
}
public final ParallelObservable<T> skipLast(final long time,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.skipLast(time, unit);
}
});
}
public final ParallelObservable<T> skipLast(final long time,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.skipLast(time, unit, scheduler);
}
});
}
public final <U> ParallelObservable<T> skipUntil(final Observable<U> other) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.skipUntil(other);
}
});
}
public final ParallelObservable<T> skipWhile(
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.skipWhile(predicate);
}
});
}
public final ParallelObservable<T> startWith(final Observable<T> values) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(values);
}
});
}
public final ParallelObservable<T> startWith(final Iterable<T> values) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(values);
}
});
}
public final ParallelObservable<T> startWith(final T t1) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(t1);
}
});
}
public final ParallelObservable<T> startWith(final T t1, final T t2) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(t1, t2);
}
});
}
public final ParallelObservable<T> startWith(final T t1, final T t2,
final T t3) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(t1, t2, t3);
}
});
}
public final ParallelObservable<T> startWith(final T t1, final T t2,
final T t3, final T t4) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(t1, t2, t3, t4);
}
});
}
public final ParallelObservable<T> startWith(final T t1, final T t2,
final T t3, final T t4, final T t5) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(t1, t2, t3, t4, t5);
}
});
}
public final ParallelObservable<T> startWith(final T t1, final T t2,
final T t3, final T t4, final T t5, final T t6) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(t1, t2, t3, t4, t5, t6);
}
});
}
public final ParallelObservable<T> startWith(final T t1, final T t2,
final T t3, final T t4, final T t5, final T t6, final T t7) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(t1, t2, t3, t4, t5, t6, t7);
}
});
}
public final ParallelObservable<T> startWith(final T t1, final T t2,
final T t3, final T t4, final T t5, final T t6, final T t7,
final T t8) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(t1, t2, t3, t4, t5, t6, t7, t8);
}
});
}
public final ParallelObservable<T> startWith(final T t1, final T t2,
final T t3, final T t4, final T t5, final T t6, final T t7,
final T t8, final T t9) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.startWith(t1, t2, t3, t4, t5, t6, t7, t8, t9);
}
});
}
public final ParallelObservable<T> subscribeOn(final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.subscribeOn(scheduler);
}
});
}
public final <R> ParallelObservable<R> switchMap(
final Func1<? super T, ? extends Observable<? extends R>> func) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.switchMap(func);
}
});
}
public final ParallelObservable<T> take(final int num) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.take(num);
}
});
}
public final ParallelObservable<T> take(final long time, final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.take(time, unit);
}
});
}
public final ParallelObservable<T> take(final long time,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.take(time, unit, scheduler);
}
});
}
public final ParallelObservable<T> takeFirst(
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.takeFirst(predicate);
}
});
}
public final ParallelObservable<T> takeLast(final int count) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.takeLast(count);
}
});
}
public final ParallelObservable<T> takeLast(final int count,
final long time, final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.takeLast(count, time, unit);
}
});
}
public final ParallelObservable<T> takeLast(final int count,
final long time, final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.takeLast(count, time, unit, scheduler);
}
});
}
public final ParallelObservable<T> takeLast(final long time,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.takeLast(time, unit);
}
});
}
public final ParallelObservable<T> takeLast(final long time,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.takeLast(time, unit, scheduler);
}
});
}
public final ParallelObservable<List<T>> takeLastBuffer(final int count) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.takeLastBuffer(count);
}
});
}
public final ParallelObservable<List<T>> takeLastBuffer(final int count,
final long time, final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.takeLastBuffer(count, time, unit);
}
});
}
public final ParallelObservable<List<T>> takeLastBuffer(final int count,
final long time, final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.takeLastBuffer(count, time, unit, scheduler);
}
});
}
public final ParallelObservable<List<T>> takeLastBuffer(final long time,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.takeLastBuffer(time, unit);
}
});
}
public final ParallelObservable<List<T>> takeLastBuffer(final long time,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.takeLastBuffer(time, unit, scheduler);
}
});
}
public final <E> ParallelObservable<T> takeUntil(
final Observable<? extends E> other) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.takeUntil(other);
}
});
}
public final ParallelObservable<T> takeWhile(
final Func1<? super T, Boolean> predicate) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.takeWhile(predicate);
}
});
}
public final ParallelObservable<T> throttleFirst(final long windowDuration,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.throttleFirst(windowDuration, unit);
}
});
}
public final ParallelObservable<T> throttleFirst(final long skipDuration,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.throttleFirst(skipDuration, unit, scheduler);
}
});
}
public final ParallelObservable<T> throttleLast(
final long intervalDuration, final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.throttleLast(intervalDuration, unit);
}
});
}
public final ParallelObservable<T> throttleLast(
final long intervalDuration, final TimeUnit unit,
final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.throttleLast(intervalDuration, unit, scheduler);
}
});
}
public final ParallelObservable<T> throttleWithTimeout(final long timeout,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.throttleWithTimeout(timeout, unit);
}
});
}
public final ParallelObservable<T> throttleWithTimeout(final long timeout,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.throttleWithTimeout(timeout, unit, scheduler);
}
});
}
public final ParallelObservable<TimeInterval<T>> timeInterval() {
return create(new Func1<Observable<T>, Observable<TimeInterval<T>>>() {
@Override
public Observable<TimeInterval<T>> call(Observable<T> o) {
return o.timeInterval();
}
});
}
public final ParallelObservable<TimeInterval<T>> timeInterval(
final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<TimeInterval<T>>>() {
@Override
public Observable<TimeInterval<T>> call(Observable<T> o) {
return o.timeInterval(scheduler);
}
});
}
public final <U, V> ParallelObservable<T> timeout(
final Func0<? extends Observable<U>> firstTimeoutSelector,
final Func1<? super T, ? extends Observable<V>> timeoutSelector) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.timeout(firstTimeoutSelector, timeoutSelector);
}
});
}
public final <U, V> ParallelObservable<T> timeout(
final Func0<? extends Observable<U>> firstTimeoutSelector,
final Func1<? super T, ? extends Observable<V>> timeoutSelector,
final Observable<? extends T> other) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.timeout(firstTimeoutSelector, timeoutSelector, other);
}
});
}
public final <V> ParallelObservable<T> timeout(
final Func1<? super T, ? extends Observable<V>> timeoutSelector) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.timeout(timeoutSelector);
}
});
}
public final <V> ParallelObservable<T> timeout(
final Func1<? super T, ? extends Observable<V>> timeoutSelector,
final Observable<? extends T> other) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.timeout(timeoutSelector, other);
}
});
}
public final ParallelObservable<T> timeout(final long timeout,
final TimeUnit timeUnit) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.timeout(timeout, timeUnit);
}
});
}
public final ParallelObservable<T> timeout(final long timeout,
final TimeUnit timeUnit, final Observable<? extends T> other) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.timeout(timeout, timeUnit, other);
}
});
}
public final ParallelObservable<T> timeout(final long timeout,
final TimeUnit timeUnit, final Observable<? extends T> other,
final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.timeout(timeout, timeUnit, other, scheduler);
}
});
}
public final ParallelObservable<T> timeout(final long timeout,
final TimeUnit timeUnit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.timeout(timeout, timeUnit, scheduler);
}
});
}
public final ParallelObservable<Timestamped<T>> timestamp() {
return create(new Func1<Observable<T>, Observable<Timestamped<T>>>() {
@Override
public Observable<Timestamped<T>> call(Observable<T> o) {
return o.timestamp();
}
});
}
public final ParallelObservable<Timestamped<T>> timestamp(
final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<Timestamped<T>>>() {
@Override
public Observable<Timestamped<T>> call(Observable<T> o) {
return o.timestamp(scheduler);
}
});
}
public final ParallelObservable<List<T>> toList() {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.toList();
}
});
}
public final <K> ParallelObservable<Map<K, T>> toMap(
final Func1<? super T, ? extends K> keySelector) {
return create(new Func1<Observable<T>, Observable<Map<K, T>>>() {
@Override
public Observable<Map<K, T>> call(Observable<T> o) {
return o.toMap(keySelector);
}
});
}
public final <K, V> ParallelObservable<Map<K, V>> toMap(
final Func1<? super T, ? extends K> keySelector,
final Func1<? super T, ? extends V> valueSelector) {
return create(new Func1<Observable<T>, Observable<Map<K, V>>>() {
@Override
public Observable<Map<K, V>> call(Observable<T> o) {
return o.toMap(keySelector, valueSelector);
}
});
}
public final <K, V> ParallelObservable<Map<K, V>> toMap(
final Func1<? super T, ? extends K> keySelector,
final Func1<? super T, ? extends V> valueSelector,
final Func0<? extends Map<K, V>> mapFactory) {
return create(new Func1<Observable<T>, Observable<Map<K, V>>>() {
@Override
public Observable<Map<K, V>> call(Observable<T> o) {
return o.toMap(keySelector, valueSelector, mapFactory);
}
});
}
public final <K> ParallelObservable<Map<K, Collection<T>>> toMultimap(
final Func1<? super T, ? extends K> keySelector) {
return create(new Func1<Observable<T>, Observable<Map<K, Collection<T>>>>() {
@Override
public Observable<Map<K, Collection<T>>> call(Observable<T> o) {
return o.toMultimap(keySelector);
}
});
}
public final <K, V> ParallelObservable<Map<K, Collection<V>>> toMultimap(
final Func1<? super T, ? extends K> keySelector,
final Func1<? super T, ? extends V> valueSelector) {
return create(new Func1<Observable<T>, Observable<Map<K, Collection<V>>>>() {
@Override
public Observable<Map<K, Collection<V>>> call(Observable<T> o) {
return o.toMultimap(keySelector, valueSelector);
}
});
}
public final <K, V> ParallelObservable<Map<K, Collection<V>>> toMultimap(
final Func1<? super T, ? extends K> keySelector,
final Func1<? super T, ? extends V> valueSelector,
final Func0<? extends Map<K, Collection<V>>> mapFactory) {
return create(new Func1<Observable<T>, Observable<Map<K, Collection<V>>>>() {
@Override
public Observable<Map<K, Collection<V>>> call(Observable<T> o) {
return o.toMultimap(keySelector, valueSelector, mapFactory);
}
});
}
public final <K, V> ParallelObservable<Map<K, Collection<V>>> toMultimap(
final Func1<? super T, ? extends K> keySelector,
final Func1<? super T, ? extends V> valueSelector,
final Func0<? extends Map<K, Collection<V>>> mapFactory,
final Func1<? super K, ? extends Collection<V>> collectionFactory) {
return create(new Func1<Observable<T>, Observable<Map<K, Collection<V>>>>() {
@Override
public Observable<Map<K, Collection<V>>> call(Observable<T> o) {
return o.toMultimap(keySelector, valueSelector, mapFactory,
collectionFactory);
}
});
}
public final ParallelObservable<List<T>> toSortedList() {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.toSortedList();
}
});
}
public final ParallelObservable<List<T>> toSortedList(
final Func2<? super T, ? super T, Integer> sortFunction) {
return create(new Func1<Observable<T>, Observable<List<T>>>() {
@Override
public Observable<List<T>> call(Observable<T> o) {
return o.toSortedList(sortFunction);
}
});
}
public final ParallelObservable<T> unsubscribeOn(final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<T>>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.unsubscribeOn(scheduler);
}
});
}
public final <TClosing> ParallelObservable<Observable<T>> window(
final Func0<? extends Observable<? extends TClosing>> closingSelector) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(closingSelector);
}
});
}
public final ParallelObservable<Observable<T>> window(final int count) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(count);
}
});
}
public final ParallelObservable<Observable<T>> window(final int count,
final int skip) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(count, skip);
}
});
}
public final ParallelObservable<Observable<T>> window(final long timespan,
final long timeshift, final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(timespan, timeshift, unit);
}
});
}
public final ParallelObservable<Observable<T>> window(final long timespan,
final long timeshift, final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(timespan, timeshift, unit, scheduler);
}
});
}
public final ParallelObservable<Observable<T>> window(final long timespan,
final long timeshift, final TimeUnit unit, final int count,
final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(timespan, timeshift, unit, count, scheduler);
}
});
}
public final ParallelObservable<Observable<T>> window(final long timespan,
final TimeUnit unit) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(timespan, unit);
}
});
}
public final ParallelObservable<Observable<T>> window(final long timespan,
final TimeUnit unit, final int count) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(timespan, unit, count);
}
});
}
public final ParallelObservable<Observable<T>> window(final long timespan,
final TimeUnit unit, final int count, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(timespan, unit, count, scheduler);
}
});
}
public final ParallelObservable<Observable<T>> window(final long timespan,
final TimeUnit unit, final Scheduler scheduler) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(timespan, unit, scheduler);
}
});
}
public final <TOpening, TClosing> ParallelObservable<Observable<T>> window(
final Observable<? extends TOpening> windowOpenings,
final Func1<? super TOpening, ? extends Observable<? extends TClosing>> closingSelector) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(windowOpenings, closingSelector);
}
});
}
public final <U> ParallelObservable<Observable<T>> window(
final Observable<U> boundary) {
return create(new Func1<Observable<T>, Observable<Observable<T>>>() {
@Override
public Observable<Observable<T>> call(Observable<T> o) {
return o.window(boundary);
}
});
}
public final <T2, R> ParallelObservable<R> zipWith(
final Iterable<? extends T2> other,
final Func2<? super T, ? super T2, ? extends R> zipFunction) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.zipWith(other, zipFunction);
}
});
}
public final <T2, R> ParallelObservable<R> zipWith(
final Observable<? extends T2> other,
final Func2<? super T, ? super T2, ? extends R> zipFunction) {
return create(new Func1<Observable<T>, Observable<R>>() {
@Override
public Observable<R> call(Observable<T> o) {
return o.zipWith(other, zipFunction);
}
});
}
}
| apache-2.0 |
javanarior/valueobject-library | src/main/java/de/javanarior/vo/types/CharWrapper.java | 1899 | /*
* Copyright (C) 2014 Sven von Pluto - javanarior (a) gmail dot 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 de.javanarior.vo.types;
/**
* Wrapper for Character values.
*
* @param <V>
* the value type
*/
public abstract class CharWrapper<V extends Value<V, Character>> extends AbstractValue<V, Character> {
private final char value;
/**
* Create Character Type with char value.
*
* @param value
* - value for the object
*/
public CharWrapper(char value) {
super();
this.value = value;
}
@Override
public Character getValue() {
return asCharacter();
}
@Override
public int hashCode() {
return 31 * super.hashCode() + value;
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
CharWrapper<?> other = (CharWrapper<?>)obj;
if (value != other.value) {
return false;
}
return true;
}
/**
* Returns the value as primitive char.
*
* @return primitive char
*/
public char asChar() {
return value;
}
/**
* Return the value as Character object.
*
* @return Character object
*/
public Character asCharacter() {
return Character.valueOf(value);
}
}
| apache-2.0 |
ruspl-afed/dbeaver | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/data/aggregate/FunctionMedian.java | 2002 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.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.jkiss.dbeaver.model.data.aggregate;
import org.jkiss.dbeaver.Log;
import java.util.*;
/**
* Median
*/
public class FunctionMedian implements IAggregateFunction {
private static final Log log = Log.getLog(FunctionMedian.class);
private List<Comparable> cache = new ArrayList<>();
@Override
public boolean accumulate(Object value) {
if (value instanceof Comparable) {
cache.add((Comparable) value);
return true;
}
return false;
}
@Override
public Object getResult(int valueCount) {
try {
Collections.sort(cache);
} catch (Exception e) {
log.debug("Can't sort value collection", e);
return null;
}
int size = cache.size();
int middle = size / 2;
if (size % 2 == 1) {
return cache.get(middle);
} else {
Comparable val1 = cache.get(middle - 1);
Comparable val2 = cache.get(middle);
if (val1 instanceof Number && val2 instanceof Number) {
return (((Number) val1).doubleValue() + ((Number) val2).doubleValue()) / 2.0;
}
// Not true median - but we can't evaluate it for non-numeric values
// So just get first one
return val1;
}
}
}
| apache-2.0 |
Esri/performance-test-harness-for-geoevent | performance-test-harness-orchestrator/src/main/java/com/esri/geoevent/test/performance/OrchestratorRunner.java | 7843 | /*
Copyright 1995-2015 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, contact:
Environmental Systems Research Institute, Inc.
Attn: Contracts Dept
380 New York Street
Redlands, California, USA 92373
email: contracts@esri.com
*/
package com.esri.geoevent.test.performance;
import com.esri.geoevent.test.performance.jaxb.Fixture;
import com.esri.geoevent.test.performance.jaxb.Fixtures;
import com.esri.geoevent.test.performance.jaxb.ProvisionerConfig;
import com.esri.geoevent.test.performance.provision.DefaultProvisionerFactory;
import com.esri.geoevent.test.performance.provision.ProvisionException;
import com.esri.geoevent.test.performance.provision.Provisioner;
import com.esri.geoevent.test.performance.provision.ProvisionerFactory;
import com.esri.geoevent.test.performance.report.CSVReportWriter;
import com.esri.geoevent.test.performance.report.ReportType;
import com.esri.geoevent.test.performance.report.ReportWriter;
import com.esri.geoevent.test.performance.report.XLSXReportWriter;
import com.esri.geoevent.test.performance.statistics.FixturesStatistics;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
/**
*
* @author davi5017
*/
public class OrchestratorRunner implements RunnableComponent {
private List<String> testNames;
private boolean reportComplete;
private long startTime;
private Fixtures fixtures;
// Runnable
private RunningStateListener listener;
protected AtomicBoolean running = new AtomicBoolean(false);
public OrchestratorRunner(Fixtures fixtures) {
this.fixtures = fixtures;
}
@Override
public void start() throws RunningException {
running = new AtomicBoolean(true);
run();
if (listener != null) {
listener.onStateChange(new RunningState(RunningStateType.STARTED));
}
}
@Override
public void stop() {
running.set(false);
if (listener != null) {
listener.onStateChange(new RunningState(RunningStateType.STOPPED));
}
}
@Override
public boolean isRunning() {
return running.get();
}
@Override
public RunningStateType getRunningState() {
return running.get() ? RunningStateType.STARTED : RunningStateType.STOPPED;
}
@Override
public void setRunningStateListener(RunningStateListener listener) {
this.listener = listener;
}
/**
* Main Test Harness Orchestrator Method
*/
public void run() {
// parse the xml file
testNames = new ArrayList<String>();
// add this runtime hook to write out whatever results we have to a report in case of exit or failures
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
long totalTime = System.currentTimeMillis() - startTime;
writeReport(fixtures, testNames, totalTime);
}));
// Check the master fixtures configuration to see if we need to provision all of the test
ProvisionerFactory provisionerFactory = new DefaultProvisionerFactory();
try {
ProvisionerConfig masterProvisionerConfig = fixtures.getProvisionerConfig();
if (masterProvisionerConfig != null) {
Provisioner provisioner = provisionerFactory.createProvisioner(masterProvisionerConfig);
if (provisioner != null) {
provisioner.provision();
}
}
} catch (ProvisionException error) {
System.err.println(ImplMessages.getMessage("TEST_HARNESS_EXECUTOR_PROVISIONING_ERROR"));
error.printStackTrace();
return;
}
// start
startTime = System.currentTimeMillis();
// process all fixtures in sequence/series
final Fixture defaultFixture = fixtures.getDefaultFixture();
Queue<Fixture> processingQueue = new ConcurrentLinkedQueue<Fixture>(fixtures.getFixtures());
while (!processingQueue.isEmpty() && isRunning()) {
Fixture fixture = processingQueue.remove();
fixture.apply(defaultFixture);
try {
ProvisionerConfig fixtureProvisionerConfig = fixture.getProvisionerConfig();
if (fixtureProvisionerConfig != null) {
Provisioner provisioner = provisionerFactory.createProvisioner(fixtureProvisionerConfig);
if (provisioner != null) {
provisioner.provision();
}
}
} catch (Exception error) {
System.err.println(ImplMessages.getMessage("TEST_HARNESS_EXECUTOR_FIXTURE_PROVISIONING_ERROR", fixture.getName()));
error.printStackTrace();
continue;
}
testNames.add(fixture.getName());
Orchestrator orchestrator = new PerformanceTestHarness(fixture);
try {
orchestrator.init();
orchestrator.runTest();
} catch (Exception error) {
error.printStackTrace();
orchestrator.destroy();
orchestrator = null;
continue;
}
// check if we are running and sleep accordingly
while (orchestrator.isRunning() && isRunning()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
orchestrator = null;
// pause for 1/2 second before continuing with the next test
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long totalTime = System.currentTimeMillis() - startTime;
// write out the report
writeReport(fixtures, testNames, totalTime);
//notify
stop();
}
private void writeReport(final Fixtures fixtures, final List<String> testNames, long totalTestingTime) {
if (fixtures == null || testNames.size() == 0 || reportComplete) {
return;
}
// write out the report
ReportWriter reportWriter = null;
ReportType type = fixtures.getReport().getType();
switch (type) {
case XLSX:
reportWriter = new XLSXReportWriter();
break;
case CSV:
default:
reportWriter = new CSVReportWriter();
break;
}
//write the report
try {
List<String> columnNames = reportWriter.getReportColumnNames(fixtures.getReport().getReportColumns(), fixtures.getReport().getAdditionalReportColumns());
reportWriter.setMaxNumberOfReportFiles(fixtures.getReport().getMaxNumberOfReportFiles());
reportWriter.setTotalTestingTime(totalTestingTime);
reportWriter.writeReport(fixtures.getReport().getReportFile(), testNames, columnNames, FixturesStatistics.getInstance().getStats());
} catch (Exception error) {
error.printStackTrace();
} finally {
reportComplete = true;
}
}
}
| apache-2.0 |
droolsjbpm/kie-benchmarks | drools-benchmarks/src/main/java/org/drools/benchmarks/turtle/buildtime/GeneratorUtil.java | 3310 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.benchmarks.turtle.buildtime;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.openjdk.jmh.util.FileUtils;
public class GeneratorUtil {
public static void main(String[] args) throws IOException {
final StringBuilder sb = new StringBuilder();
sb.append("package org.drools.benchmarks.bre;\n");
sb.append("\n");
sb.append("import org.drools.benchmarks.model.Account;\n");
sb.append("import org.drools.benchmarks.model.Address;\n");
sb.append("import org.drools.benchmarks.model.Customer;\n");
sb.append("\n");
for (int i = 1; i <= 20; i++) {
sb.append("rule \"accountBalance" + i + "\"\n"
+ "when \n"
+ " $account : Account(balance == " + i + ")\n"
+ "then\n"
+ " modify ($account) { setBalance(" + (-i) + ") };\n"
+ "end\n");
sb.append("\n");
sb.append("rule \"postalCode" + i + "\"\n"
+ "when \n"
+ " $address : Address(postCode != \"" + i + "\")\n"
+ "then\n"
+ " modify ($address) { setPostCode(\"" + i + "\") };\n"
+ "end\n");
sb.append("\n");
sb.append("rule \"accountOwner" + i + "\"\n"
+ "when \n"
+ " $account : Account(balance == " + i + ")\n"
+ " $customer : Customer (this == $account.owner)\n"
+ "then\n"
+ " modify ($account) { setBalance(" + (-i) + ") };\n"
+ "end\n");
sb.append("\n");
sb.append("rule \"BrnoPrahaOstrava" + i + "\"\n"
+ "when \n"
+ " $address : Address(city in (\"Brno\", \"Praha\", \"Ostrava\", \"" + i + "\"))\n"
+ "then\n"
+ " modify ($address) { setCity(\"" + i + "\") };\n"
+ "end\n");
sb.append("\n");
sb.append("rule \"exists" + i + "\"\n"
+ "when \n"
+ " $customer: Customer(firstName == \"Jake" + i + "\")\n"
+ "then\n"
+ " modify ($customer) {setFirstName(\"Jackie" + i + "\")} \n"
+ "end\n");
sb.append("\n");
}
final List<String> lines = Arrays.asList(sb.toString().split("\n"));
FileUtils.writeLines(new File("drools-benchmarks/src/main/resources/kbase-creation/rules.drl"), lines);
}
}
| apache-2.0 |
cwpenhale/red5-mobileconsole | red5_server/src/test/java/org/red5/server/service/RemoteClass.java | 860 | /*
* RED5 Open Source Flash Server - http://code.google.com/p/red5/
*
* Copyright 2006-2012 by respective authors (see below). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.red5.server.service;
public class RemoteClass {
public String attribute1;
public int attribute2;
}
| apache-2.0 |
Ardulink/Ardulink-2 | ardulink-core-base/src/main/java/org/ardulink/core/linkmanager/LinkFactory.java | 1239 | /**
Copyright 2013 project Ardulink http://www.ardulink.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.ardulink.core.linkmanager;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import org.ardulink.core.Link;
/**
* [ardulinktitle] [ardulinkversion]
*
* project Ardulink http://www.ardulink.org/
*
* [adsense]
*
*/
public interface LinkFactory<T extends LinkConfig> {
/**
* LinkFactories can have beside their primary name additionally alias names.
*/
@Retention(RUNTIME)
public static @interface Alias {
String[] value();
}
String getName();
Link newLink(T config) throws Exception;
T newLinkConfig();
}
| apache-2.0 |
cloudscode/jibu | jibu-core/src/main/java/org/gaixie/jibu/security/dao/impl/SettingDAOPgSQL.java | 6811 | /*
* 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.gaixie.jibu.security.dao.impl;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.gaixie.jibu.utils.SQLBuilder;
import org.gaixie.jibu.security.dao.SettingDAO;
import org.gaixie.jibu.security.model.Setting;
import org.gaixie.jibu.security.model.User;
import org.gaixie.jibu.JibuException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Setting 数据访问接口的 PostgreSQL 实现。
* <p>
*/
public class SettingDAOPgSQL implements SettingDAO {
private static final Logger logger = LoggerFactory.getLogger(SettingDAOPgSQL.class);
private QueryRunner run = null;
public SettingDAOPgSQL() {
this.run = new QueryRunner();
}
public Setting get(Connection conn, int id) throws SQLException {
ResultSetHandler<Setting> h = new BeanHandler(Setting.class);
return run.query(conn
, "SELECT id,name,value,sortindex,enabled FROM settings WHERE id=? "
, h
, id);
}
public Setting get(Connection conn, String name, String value) throws SQLException {
ResultSetHandler<Setting> h = new BeanHandler(Setting.class);
return run.query(conn
, "SELECT id,name,value,sortindex,enabled FROM settings WHERE name=? AND value=? "
, h
, name
, value);
}
public Setting getDefault(Connection conn, String name) throws SQLException {
ResultSetHandler<Setting> h = new BeanHandler(Setting.class);
return run.query(conn
, "SELECT id,name,value,sortindex,enabled FROM settings WHERE sortindex = 0 and name=? "
, h
, name);
}
public Setting getByUsername(Connection conn, String name, String username) throws SQLException {
ResultSetHandler<Setting> h = new BeanHandler(Setting.class);
String sql =
" SELECT s.id,s.name,s.value,s.sortindex,s.enabled \n"+
" FROM settings s, userbase u, user_setting_map usm \n"+
" WHERE u.username=? \n"+
" AND u.id = usm.user_id \n"+
" AND usm.setting_id = s.id \n"+
" AND s.name = ?";
return run.query(conn,sql
, h
, username, name);
}
public void save(Connection conn, Setting setting) throws SQLException {
run.update(conn
, "INSERT INTO settings (name,value,sortindex,enabled) VALUES (?,?,?,?)"
, setting.getName()
, setting.getValue()
, setting.getSortindex()
, setting.getEnabled());
}
/**
* {@inheritDoc}
* <p>
* 除 id 属性以外,所有非空的属性将会被更新至数据库中。
*/
public void update(Connection conn, Setting setting) throws SQLException {
String sql = "UPDATE settings \n";
Integer id = setting.getId();
setting.setId(null);
try {
String s = SQLBuilder.beanToSQLClause(setting,",");
sql = sql + SQLBuilder.getSetClause(s) +"\n"+
"WHERE id=? ";
} catch (JibuException e) {
throw new SQLException(e.getMessage());
}
run.update(conn
, sql
, id);
}
/**
* {@inheritDoc}
* <p>
* setting.getId() 不能为 null。
*/
public void delete(Connection conn, Setting setting) throws SQLException {
run.update(conn
, "DELETE FROM settings WHERE id=?"
, setting.getId());
}
public List<Setting> findByName(Connection conn, String name) throws SQLException {
ResultSetHandler<List<Setting>> h = new BeanListHandler(Setting.class);
return run.query(conn
,"SELECT id,name,value,sortindex,enabled FROM settings WHERE name =? ORDER BY sortindex"
,h,name);
}
public List<Setting> getAllDefault(Connection conn) throws SQLException {
ResultSetHandler<List<Setting>> h = new BeanListHandler(Setting.class);
return run.query(conn
,"SELECT id,name,value,sortindex,enabled FROM settings WHERE sortindex =0"
,h);
}
public List<Setting> findByUsername(Connection conn, String username) throws SQLException {
ResultSetHandler<List<Setting>> h = new BeanListHandler(Setting.class);
String sql =
" SELECT s.id,s.name,s.value,s.sortindex,s.enabled \n"+
" FROM settings s, userbase u, user_setting_map usm \n"+
" WHERE u.username=? \n"+
" AND u.id = usm.user_id \n"+
" AND usm.setting_id = s.id \n";
return run.query(conn,sql
, h
, username);
}
public void bind(Connection conn, int sid, int uid) throws SQLException {
run.update(conn
, "INSERT INTO user_setting_map (setting_id,user_id) values (?,?)"
, sid
, uid);
}
public void unbind(Connection conn, int sid, int uid) throws SQLException {
run.update(conn
, "DELETE FROM user_setting_map WHERE setting_id = ? AND user_id = ?"
, sid
, uid);
}
public void unbindAll(Connection conn, int uid) throws SQLException {
run.update(conn
, "DELETE FROM user_setting_map WHERE user_id = ?"
, uid);
}
}
| apache-2.0 |
nickbabcock/dropwizard | dropwizard-jdbi3/src/test/java/io/dropwizard/jdbi3/bundles/JdbiExceptionsBundleTest.java | 1003 | package io.dropwizard.jdbi3.bundles;
import io.dropwizard.Configuration;
import io.dropwizard.jdbi3.jersey.LoggingJdbiExceptionMapper;
import io.dropwizard.jdbi3.jersey.LoggingSQLExceptionMapper;
import io.dropwizard.jersey.setup.JerseyEnvironment;
import io.dropwizard.setup.Environment;
import org.junit.Test;
import static org.mockito.Mockito.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class JdbiExceptionsBundleTest {
@Test
public void test() {
Environment environment = mock(Environment.class);
JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class);
when(environment.jersey()).thenReturn(jerseyEnvironment);
new JdbiExceptionsBundle().run(new Configuration(), environment);
verify(jerseyEnvironment).register(isA(LoggingSQLExceptionMapper.class));
verify(jerseyEnvironment).register(isA(LoggingJdbiExceptionMapper.class));
}
}
| apache-2.0 |
snorochevskiy/JTranslate | rest/src/main/java/org/jtranslate/web/rest/TranslationProjectssEndpoint.java | 2324 | package org.jtranslate.web.rest;
import org.jtranslate.TranslationsDao;
import org.jtranslate.entity.TranslationProjectEntity;
import org.jtranslate.entity.TranslationSubprojectEntity;
import org.jtranslate.web.rest.dto.TranslationProjectDto;
import org.jtranslate.web.rest.dto.TranslationSubprojectDto;
import org.jtranslate.web.rest.mappers.TranslationProjectMapper;
import org.jtranslate.web.rest.mappers.TranslationSubprojectMapper;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;
@RestController
@RequestMapping("/rest/v_1/project")
public class TranslationProjectssEndpoint {
@Resource
private TranslationsDao translationsDao;
@RequestMapping(value = "/all", method = RequestMethod.GET)
public Set<TranslationProjectDto> listProjects() {
Set<TranslationProjectDto> projects = new HashSet<>();
for (TranslationProjectEntity p : translationsDao.getAllTranslationProjects()) {
projects.add(TranslationProjectMapper.map(p));
}
return projects;
}
@RequestMapping(value = "/{id}/subprojects", method = RequestMethod.GET)
public Set<TranslationSubprojectDto> listSubprojects(@PathVariable("id") Long projectId) {
Set<TranslationSubprojectDto> subprojects = new HashSet<>();
for (TranslationSubprojectEntity p : translationsDao.getAllSubprojects(projectId)) {
subprojects.add(TranslationSubprojectMapper.map(p));
}
return subprojects;
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public void createProject(@RequestBody TranslationProjectDto projectDto) {
translationsDao.createProject(TranslationProjectMapper.map(projectDto));
}
@RequestMapping(value = "/{projectId}/create-subproject", method = RequestMethod.POST)
public void createSubroject(@RequestBody TranslationSubprojectDto subprojectDto) {
translationsDao.createSubproject(TranslationSubprojectMapper.map(subprojectDto));
}
}
| apache-2.0 |
lvsijian8/MrFlower_for_Web | MrFlower/src/pot/dao/android/getManageAllDaoAndroid.java | 2615 | package pot.dao.android;
import net.sf.json.JSONArray;
import pot.util.DBConnection;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by lvsijian8 on 2017/5/12.
*/
public class getManageAllDaoAndroid {
public Map findAllPot(int user_id) {
Connection con = null;
PreparedStatement prepstmt = null;
ResultSet rs = null;
boolean nullMark = false;
Map wai = new HashMap();
JSONArray array = new JSONArray();
ArrayList<Integer> pot_ids = new ArrayList<Integer>();
Timestamp date = new Timestamp(new java.util.Date().getTime() - 10000);
Timestamp now = new Timestamp(new java.util.Date().getTime());
String sqlFindPots = "SELECT pot_id FROM user_pot WHERE user_id=?;";
String sqlFindPotName = "SELECT flower_name,heartBeat_time,now_water,now_bottle FROM pot WHERE pot_id=?;";
try {
con = DBConnection.getDBConnection();
prepstmt = con.prepareStatement(sqlFindPots);
prepstmt.setInt(1, user_id);
rs = prepstmt.executeQuery();
while (rs.next()) {
nullMark = true;
pot_ids.add(rs.getInt("pot_id"));
}
prepstmt = con.prepareStatement(sqlFindPotName);
for (int i = 0; i < pot_ids.size(); i++) {
prepstmt.setInt(1, pot_ids.get(i));
rs = prepstmt.executeQuery();
while (rs.next()) {
Map params = new HashMap();
params.put("pot_id", pot_ids.get(i));
params.put("pot_names", rs.getString("flower_name"));
params.put("pot_waters", rs.getInt("now_water"));
params.put("pot_bottles", rs.getInt("now_bottle"));
params.put("pot_online", 0);
date = rs.getTimestamp("heartBeat_time");
if (date == null)
date = new Timestamp(new java.util.Date().getTime() - 10000);
if (((now.getTime() - date.getTime()) / 1000) > 5)
params.put("pot_online", 0);
else
params.put("pot_online", 1);
array.add(params);
}
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBConnection.closeDB(con, prepstmt, rs);
}
wai.put("data", array);
if (nullMark)
return wai;
else
return null;
}
} | apache-2.0 |
sunny256/crate | sql/src/main/java/io/crate/executor/transport/task/SymbolBasedUpsertByIdTask.java | 13327 | /*
* Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.executor.transport.task;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.crate.Constants;
import io.crate.executor.JobTask;
import io.crate.executor.RowCountResult;
import io.crate.executor.TaskResult;
import io.crate.executor.transport.ShardUpsertResponse;
import io.crate.executor.transport.SymbolBasedShardUpsertRequest;
import io.crate.jobs.*;
import io.crate.metadata.settings.CrateSettings;
import io.crate.planner.node.dml.SymbolBasedUpsertByIdNode;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.create.TransportBulkCreateIndicesAction;
import org.elasticsearch.action.admin.indices.create.TransportCreateIndexAction;
import org.elasticsearch.action.bulk.BulkRetryCoordinatorPool;
import org.elasticsearch.action.bulk.SymbolBasedBulkShardProcessor;
import org.elasticsearch.action.bulk.SymbolBasedTransportShardUpsertActionDelegate;
import org.elasticsearch.action.support.AutoCreateIndex;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.IndexAlreadyExistsException;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CancellationException;
public class SymbolBasedUpsertByIdTask extends JobTask {
private final SymbolBasedTransportShardUpsertActionDelegate transportShardUpsertActionDelegate;
private final TransportCreateIndexAction transportCreateIndexAction;
private final TransportBulkCreateIndicesAction transportBulkCreateIndicesAction;
private final ClusterService clusterService;
private final SymbolBasedUpsertByIdNode node;
private final List<ListenableFuture<TaskResult>> resultList;
private final AutoCreateIndex autoCreateIndex;
private final BulkRetryCoordinatorPool bulkRetryCoordinatorPool;
private final JobContextService jobContextService;
private final static ESLogger logger = Loggers.getLogger(SymbolBasedUpsertByIdTask.class);
@Nullable
private SymbolBasedBulkShardProcessorContext bulkShardProcessorContext;
public SymbolBasedUpsertByIdTask(UUID jobId,
ClusterService clusterService,
Settings settings,
SymbolBasedTransportShardUpsertActionDelegate transportShardUpsertActionDelegate,
TransportCreateIndexAction transportCreateIndexAction,
TransportBulkCreateIndicesAction transportBulkCreateIndicesAction,
BulkRetryCoordinatorPool bulkRetryCoordinatorPool,
SymbolBasedUpsertByIdNode node,
JobContextService jobContextService) {
super(jobId);
this.transportShardUpsertActionDelegate = transportShardUpsertActionDelegate;
this.transportCreateIndexAction = transportCreateIndexAction;
this.transportBulkCreateIndicesAction = transportBulkCreateIndicesAction;
this.clusterService = clusterService;
this.node = node;
this.bulkRetryCoordinatorPool = bulkRetryCoordinatorPool;
this.jobContextService = jobContextService;
autoCreateIndex = new AutoCreateIndex(settings);
if (node.items().size() == 1) {
// skip useless usage of bulk processor if only 1 item in statement
// and instead create upsert request directly on start()
resultList = new ArrayList<>(1);
resultList.add(SettableFuture.<TaskResult>create());
} else {
resultList = initializeBulkShardProcessor(settings);
}
}
@Override
public void start() {
if (node.items().size() == 1) {
// directly execute upsert request without usage of bulk processor
@SuppressWarnings("unchecked")
SettableFuture<TaskResult> futureResult = (SettableFuture)resultList.get(0);
SymbolBasedUpsertByIdNode.Item item = node.items().get(0);
if (node.isPartitionedTable()
&& autoCreateIndex.shouldAutoCreate(item.index(), clusterService.state())) {
createIndexAndExecuteUpsertRequest(item, futureResult);
} else {
executeUpsertRequest(item, futureResult);
}
} else if (bulkShardProcessorContext != null) {
for (SymbolBasedUpsertByIdNode.Item item : node.items()) {
bulkShardProcessorContext.add(
item.index(),
item.id(),
item.updateAssignments(),
item.insertValues(),
item.routing(),
item.version());
}
bulkShardProcessorContext.start();
}
}
private void executeUpsertRequest(final SymbolBasedUpsertByIdNode.Item item, final SettableFuture futureResult) {
ShardId shardId = clusterService.operationRouting().indexShards(
clusterService.state(),
item.index(),
Constants.DEFAULT_MAPPING_TYPE,
item.id(),
item.routing()
).shardId();
SymbolBasedShardUpsertRequest upsertRequest = new SymbolBasedShardUpsertRequest(shardId, node.updateColumns(), node.insertColumns());
upsertRequest.continueOnError(false);
upsertRequest.add(0, item.id(), item.updateAssignments(), item.insertValues(), item.version(), item.routing());
UpsertByIdContext upsertByIdContext = new UpsertByIdContext(upsertRequest, item, futureResult, transportShardUpsertActionDelegate);
registerContext(upsertByIdContext);
upsertByIdContext.start();
}
private void registerContext(ExecutionSubContext context) {
JobExecutionContext.Builder contextBuilder = jobContextService.newBuilder(jobId());
contextBuilder.addSubContext(node.executionNodeId(), context);
jobContextService.createContext(contextBuilder);
}
private List<ListenableFuture<TaskResult>> initializeBulkShardProcessor(Settings settings) {
assert node.updateColumns() != null | node.insertColumns() != null;
SymbolBasedShardUpsertRequest.Builder builder = new SymbolBasedShardUpsertRequest.Builder(
CrateSettings.BULK_REQUEST_TIMEOUT.extractTimeValue(settings),
false, // do not overwrite duplicates
node.isBulkRequest() || node.updateColumns() != null, // continue on error on bulk and/or update
node.updateColumns(),
node.insertColumns()
);
SymbolBasedBulkShardProcessor<SymbolBasedShardUpsertRequest, ShardUpsertResponse> bulkShardProcessor = new SymbolBasedBulkShardProcessor<>(
clusterService,
transportBulkCreateIndicesAction,
settings,
bulkRetryCoordinatorPool,
node.isPartitionedTable(),
node.items().size(),
builder,
transportShardUpsertActionDelegate);
bulkShardProcessorContext = new SymbolBasedBulkShardProcessorContext(bulkShardProcessor);
registerContext(bulkShardProcessorContext);
if (!node.isBulkRequest()) {
final SettableFuture<TaskResult> futureResult = SettableFuture.create();
List<ListenableFuture<TaskResult>> resultList = new ArrayList<>(1);
resultList.add(futureResult);
Futures.addCallback(bulkShardProcessor.result(), new FutureCallback<BitSet>() {
@Override
public void onSuccess(@Nullable BitSet result) {
if (result == null) {
futureResult.set(TaskResult.ROW_COUNT_UNKNOWN);
} else {
futureResult.set(new RowCountResult(result.cardinality()));
}
bulkShardProcessorContext.close();
}
@Override
public void onFailure(@Nonnull Throwable t) {
futureResult.setException(t);
bulkShardProcessorContext.close();
}
});
return resultList;
} else {
final int numResults = node.items().size();
final List<ListenableFuture<TaskResult>> resultList = new ArrayList<>(numResults);
for (int i = 0; i < numResults; i++) {
resultList.add(SettableFuture.<TaskResult>create());
}
Futures.addCallback(bulkShardProcessor.result(), new FutureCallback<BitSet>() {
@Override
public void onSuccess(@Nullable BitSet result) {
if (result == null) {
setAllToFailed(null);
return;
}
for (int i = 0; i < numResults; i++) {
SettableFuture<TaskResult> future = (SettableFuture<TaskResult>) resultList.get(i);
future.set(result.get(i) ? TaskResult.ONE_ROW : TaskResult.FAILURE);
}
bulkShardProcessorContext.close();
}
private void setAllToFailed(@Nullable Throwable throwable) {
if (throwable instanceof CancellationException) {
for (ListenableFuture<TaskResult> future : resultList) {
((SettableFuture<TaskResult>) future).setException(throwable);
}
} else if (throwable == null) {
for (ListenableFuture<TaskResult> future : resultList) {
((SettableFuture<TaskResult>) future).set(TaskResult.FAILURE);
}
} else {
for (ListenableFuture<TaskResult> future : resultList) {
((SettableFuture<TaskResult>) future).set(RowCountResult.error(throwable));
}
}
}
@Override
public void onFailure(@Nonnull Throwable t) {
setAllToFailed(t);
bulkShardProcessorContext.close();
}
});
return resultList;
}
}
private void createIndexAndExecuteUpsertRequest(final SymbolBasedUpsertByIdNode.Item item,
final SettableFuture futureResult) {
transportCreateIndexAction.execute(
new CreateIndexRequest(item.index()).cause("upsert single item"),
new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(CreateIndexResponse createIndexResponse) {
executeUpsertRequest(item, futureResult);
}
@Override
public void onFailure(Throwable e) {
e = ExceptionsHelper.unwrapCause(e);
if (e instanceof IndexAlreadyExistsException) {
executeUpsertRequest(item, futureResult);
} else {
futureResult.setException(e);
}
}
});
}
@Override
public List<? extends ListenableFuture<TaskResult>> result() {
return resultList;
}
@Override
public void upstreamResult(List<? extends ListenableFuture<TaskResult>> result) {
throw new UnsupportedOperationException("UpsertByIdTask can't have an upstream result");
}
}
| apache-2.0 |
Pranavan135/AndesMaster | modules/andes-core/broker/src/main/java/org/wso2/andes/server/queue/DLCQueueUtils.java | 5308 | /*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.andes.server.queue;
import org.apache.log4j.Logger;
import org.wso2.andes.exchange.ExchangeDefaults;
import org.wso2.andes.framing.AMQShortString;
import org.wso2.andes.kernel.*;
import org.wso2.andes.server.ClusterResourceHolder;
import org.wso2.andes.server.cluster.coordination.ClusterCoordinationHandler;
import org.wso2.andes.server.cluster.coordination.hazelcast.HazelcastAgent;
import org.wso2.andes.server.util.AndesConstants;
import org.wso2.andes.server.virtualhost.VirtualHost;
import org.wso2.andes.subscription.AMQPLocalSubscription;
/**
* This class centralises the management of Dead Letter Queues by creating Dead Letter Queues when
* requested and deciding on whether a queue is a Dead Letter Queue or not and generating the 'Dead
* Letter Queue' queue name for the tenant.
*/
public class DLCQueueUtils {
private static final Logger log = Logger.getLogger(DLCQueueUtils.class);
/**
* Derive the Dead Letter Queue name of the tenant with respect to a given queue of the same
* tenant.
*
* @param queueName
* A queue name in the same tenant.
* @param dlcString
* The Dead Letter Queue suffix.
* @return The Dead Letter Queue name for the tenant.
*/
public static String identifyTenantInformationAndGenerateDLCString(String queueName,
String dlcString) {
String destinationString;
if ("/".contains(queueName)) {
//The Queue is in the tenant realm
destinationString = queueName.split("/", 2)[0] + "/" + dlcString;
} else {
destinationString = dlcString;
}
return destinationString;
}
/**
* Decides on whether a given queue name is a Dead Letter Queue or not.
*
* @param queueName
* The Queue name to test.
* @return True if a Dead Letter Queue, False if not a Dead Letter Queue.
*/
public static boolean isDeadLetterQueue(String queueName) {
boolean isDeadLetterQueue = false;
if (queueName.contains("/")) {
//The Queue is in the tenant realm
if (queueName.split("/", 2)[1].contains(AndesConstants.DEAD_LETTER_QUEUE_NAME)) {
isDeadLetterQueue = true;
}
} else {
if (queueName.equals(AndesConstants.DEAD_LETTER_QUEUE_NAME)) {
isDeadLetterQueue = true;
}
}
return isDeadLetterQueue;
}
/**
* Creates a Dead Letter Queue for the tenant in a given queue name.
*
* @param queueName
* A queue name in the same tenant.
* @param host
* The Virtual Host.
* @param owner
* The tenant owner.
* @throws AndesException
*/
public static synchronized void createDLCQueue(String queueName, VirtualHost host,
String owner) throws AndesException {
String dlcQueueName = identifyTenantInformationAndGenerateDLCString(queueName,
AndesConstants.DEAD_LETTER_QUEUE_NAME);
QueueRegistry queueRegistry = host.getQueueRegistry();
AMQQueue queue = queueRegistry.getQueue(new AMQShortString(dlcQueueName));
if (queue == null && !isDeadLetterQueue(queueName)) {
AndesQueue andesQueue = new AndesQueue(dlcQueueName, owner, false, true);
AndesContext.getInstance().getAMQPConstructStore().addQueue(andesQueue, true);
ClusterResourceHolder.getInstance().getVirtualHostConfigSynchronizer().queue(dlcQueueName, owner, false,
null);
QueueListener queueListener = new ClusterCoordinationHandler(HazelcastAgent
.getInstance());
queueListener.handleLocalQueuesChanged(andesQueue, QueueListener.QueueEvent.ADDED);
LocalSubscription mockSubscription =
new AMQPLocalSubscription(queueRegistry.getQueue(new AMQShortString(dlcQueueName)),
null, "0", dlcQueueName, false, false, true, null,
System.currentTimeMillis(), dlcQueueName, owner,
ExchangeDefaults.DIRECT_EXCHANGE_NAME.toString(), "DIRECT", null, false);
AndesContext.getInstance().getSubscriptionStore().createDisconnectOrRemoveClusterSubscription
(mockSubscription, SubscriptionListener.SubscriptionChange.ADDED);
log.info(dlcQueueName + " Queue Created as Dead Letter Channel");
}
}
}
| apache-2.0 |
xtremelabs/xl-image_utils_lib-android | xl-image_utils-test_suite/src/com/xtremelabs/imageutils/SampleSizeTests.java | 12286 | /*
* Copyright 2013 Xtreme Labs
*
* 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.xtremelabs.imageutils;
import android.test.ActivityInstrumentationTestCase2;
import com.xtremelabs.imageutils.ImageLoader.Options;
import com.xtremelabs.imageutils.ImageLoader.Options.ScalingPreference;
import com.xtremelabs.testactivity.MainActivity;
public class SampleSizeTests extends ActivityInstrumentationTestCase2<MainActivity> {
private CacheRequest mCacheRequest;
private ScalingInfo mScalingInfo;
private Options mOptions;
private Dimensions mDimensions;
public SampleSizeTests() {
super(MainActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mDimensions = new Dimensions(512, 512);
mScalingInfo = new ScalingInfo();
mOptions = new Options();
mCacheRequest = new CacheRequest("some uri", mScalingInfo, mOptions);
mOptions.scalingPreference = ScalingPreference.LARGER_THAN_VIEW_OR_FULL_SIZE;
}
public void testSampleSizesWithLargerThanView() {
mOptions.scalingPreference = ScalingPreference.LARGER_THAN_VIEW_OR_FULL_SIZE;
mScalingInfo.width = 600;
mScalingInfo.height = 600;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 500;
mScalingInfo.height = 500;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 257;
mScalingInfo.height = 257;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 256;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 100;
mScalingInfo.height = 600;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 600;
mScalingInfo.height = 100;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 170;
mScalingInfo.height = 170;
assertEquals(3, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = null;
mScalingInfo.height = 100;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 100;
mScalingInfo.height = null;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = null;
mScalingInfo.height = null;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 128;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
}
public void testSampleSizesMatchToLargerDimension() {
mOptions.scalingPreference = ScalingPreference.MATCH_TO_LARGER_DIMENSION;
mScalingInfo.width = 600;
mScalingInfo.height = 600;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 500;
mScalingInfo.height = 500;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 257;
mScalingInfo.height = 257;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 256;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 100;
mScalingInfo.height = 600;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 600;
mScalingInfo.height = 100;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 170;
mScalingInfo.height = 170;
assertEquals(3, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = null;
mScalingInfo.height = 100;
assertEquals(5, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 100;
mScalingInfo.height = null;
assertEquals(5, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = null;
mScalingInfo.height = null;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 128;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
}
public void testSampleSizesMatchToSmallerDimension() {
mOptions.scalingPreference = ScalingPreference.MATCH_TO_SMALLER_DIMENSION;
mScalingInfo.width = 600;
mScalingInfo.height = 600;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 500;
mScalingInfo.height = 500;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 257;
mScalingInfo.height = 257;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 256;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 100;
mScalingInfo.height = 600;
assertEquals(5, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 600;
mScalingInfo.height = 100;
assertEquals(5, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 170;
mScalingInfo.height = 170;
assertEquals(3, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = null;
mScalingInfo.height = 100;
assertEquals(5, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 100;
mScalingInfo.height = null;
assertEquals(5, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = null;
mScalingInfo.height = null;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 128;
assertEquals(4, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
}
public void testSampleSizesSmallerThanView() {
mOptions.scalingPreference = ScalingPreference.SMALLER_THAN_VIEW;
mScalingInfo.width = 600;
mScalingInfo.height = 600;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 500;
mScalingInfo.height = 500;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 257;
mScalingInfo.height = 257;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 256;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 100;
mScalingInfo.height = 600;
assertEquals(6, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 600;
mScalingInfo.height = 100;
assertEquals(6, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 170;
mScalingInfo.height = 170;
assertEquals(4, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = null;
mScalingInfo.height = 100;
assertEquals(6, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 100;
mScalingInfo.height = null;
assertEquals(6, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = null;
mScalingInfo.height = null;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 128;
assertEquals(4, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
}
public void testSampleSizesRoundToClosestMatch() {
mOptions.scalingPreference = ScalingPreference.ROUND_TO_CLOSEST_MATCH;
mScalingInfo.width = 600;
mScalingInfo.height = 600;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 500;
mScalingInfo.height = 500;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 257;
mScalingInfo.height = 257;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 256;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 100;
mScalingInfo.height = 600;
assertEquals(5, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 600;
mScalingInfo.height = 100;
assertEquals(5, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 170;
mScalingInfo.height = 170;
assertEquals(3, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = null;
mScalingInfo.height = 100;
assertEquals(5, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 100;
mScalingInfo.height = null;
assertEquals(5, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = null;
mScalingInfo.height = null;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 128;
assertEquals(4, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
}
public void testBasicSampleSizeCalculations() {
mScalingInfo.width = 512;
mScalingInfo.height = 512;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 2000;
mScalingInfo.height = 2000;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 257;
mScalingInfo.height = 257;
assertEquals(1, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 256;
mScalingInfo.height = 256;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 250;
mScalingInfo.height = 250;
assertEquals(2, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 129;
mScalingInfo.height = 129;
assertEquals(3, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 128;
mScalingInfo.height = 128;
assertEquals(4, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 64;
mScalingInfo.height = 64;
assertEquals(8, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 32;
mScalingInfo.height = 32;
assertEquals(16, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
mScalingInfo.width = 16;
mScalingInfo.height = 16;
assertEquals(32, SampleSizeCalculationUtility.calculateSampleSize(mCacheRequest, mDimensions));
}
}
| apache-2.0 |
battleground/storm-mobile | app/src/main/java/com/baofeng/mobile/activity/CategoryActivity.java | 924 | package com.baofeng.mobile.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import com.baofeng.mobile.R;
/**
* Created by author:李瑞宇
* email:allnet@live.cn
* on 15-7-28.
*/
public class CategoryActivity extends AppCompatActivity {
public static void launch(Context context) {
Intent intent = new Intent(context, CategoryActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_category);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
finish();
return super.onOptionsItemSelected(item);
}
}
| apache-2.0 |
mjanicek/rembulan | rembulan-luajava-compat/src/main/java/net/sandius/rembulan/lib/luajava/LuaJavaLib.java | 9432 | /*
* Copyright 2016 Miroslav Janíček
*
* 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.sandius.rembulan.lib.luajava;
import net.sandius.rembulan.ByteString;
import net.sandius.rembulan.LuaRuntimeException;
import net.sandius.rembulan.StateContext;
import net.sandius.rembulan.Table;
import net.sandius.rembulan.impl.UnimplementedFunction;
import net.sandius.rembulan.lib.AbstractLibFunction;
import net.sandius.rembulan.lib.ArgumentIterator;
import net.sandius.rembulan.lib.SimpleLoaderFunction;
import net.sandius.rembulan.runtime.ExecutionContext;
import net.sandius.rembulan.runtime.LuaFunction;
import net.sandius.rembulan.runtime.ResolvedControlThrowable;
import java.lang.reflect.InvocationTargetException;
public final class LuaJavaLib {
private LuaJavaLib() {
// not to be instantiated
}
public static LuaFunction loader(Table env) {
return new LoaderFunction(env);
}
static class LoaderFunction extends SimpleLoaderFunction {
public LoaderFunction(Table env) {
super(env);
}
@Override
public Object install(StateContext context, Table env, ByteString modName, ByteString origin) {
Table t = context.newTable();
t.rawset("newInstance", LuaJavaLib.NewInstance.INSTANCE);
t.rawset("bindClass", LuaJavaLib.BindClass.INSTANCE);
t.rawset("new", LuaJavaLib.New.INSTANCE);
t.rawset("createProxy", new UnimplementedFunction(modName + ".createProxy"));
t.rawset("loadLib", new UnimplementedFunction(modName + ".loadLib"));
env.rawset(modName, t);
return t;
}
}
/**
* {@code newInstance(className, ...)}
*
* <p>This function creates a new Java object, and returns a Lua object that is a reference
* to the actual Java object. You can access this object with the regular syntax used
* to access object oriented functions in Lua objects.</p>
*
* <p>The first parameter is the name of the class to be instantiated. The other parameters
* are passed to the Java Class constructor.</p>
*
* <p>Example:</p>
*
* <pre>
* obj = luajava.newInstance("java.lang.Object")
* -- obj is now a reference to the new object
* -- created and any of its methods can be accessed.
*
* -- this creates a string tokenizer to the "a,b,c,d"
* -- string using "," as the token separator.
* strTk = luajava.newInstance("java.util.StringTokenizer",
* "a,b,c,d", ",")
* while strTk:hasMoreTokens() do
* print(strTk:nextToken())
* end
* </pre>
*
* <p>The code above should print the following on the screen:</p>
*
* <pre>
* a
* b
* c
* d
* </pre>
*/
static class NewInstance extends AbstractLibFunction {
static final NewInstance INSTANCE = new NewInstance();
@Override
protected String name() {
return "newInstance";
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args)
throws ResolvedControlThrowable {
String className = args.nextString().toString();
Object[] ctorArgs = args.copyRemaining();
final ObjectWrapper instance;
try {
instance = ObjectWrapper.newInstance(className, ctorArgs);
}
catch (ClassNotFoundException | MethodSelectionException | IllegalAccessException
| InstantiationException | InvocationTargetException ex) {
throw new LuaRuntimeException(ex);
}
context.getReturnBuffer().setTo(instance);
}
}
/**
* {@code bindClass(className)}
*
* <p>This function retrieves a Java class corresponding to {@code className}.
* The returned object can be used to access static fields and methods of the corresponding
* class.</p>
*
* <p>Example:</p>
*
* <pre>
* sys = luajava.bindClass("java.lang.System")
* print ( sys:currentTimeMillis() )
*
* -- this prints the time returned by the function.
* </pre>
*/
static class BindClass extends AbstractLibFunction {
static final BindClass INSTANCE = new BindClass();
@Override
protected String name() {
return "bindClass";
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
String className = args.nextString().toString();
final ClassWrapper wrapper;
try {
wrapper = ClassWrapper.of(className);
}
catch (ClassNotFoundException ex) {
throw new LuaRuntimeException(ex);
}
context.getReturnBuffer().setTo(wrapper);
}
}
/**
* {@code new(javaClass)}
*
* <p>This function receives a java.lang.Class and returns a new instance of this class.</p>
*
* <p>{@code new} works just like {@code newInstance}, but the first argument is an instance of the
* class.</p>
*
* <p>Example:</p>
*
* <pre>
* str = luajava.bindClass("java.lang.String")
* strInstance = luajava.new(str)
* </pre>
*/
static class New extends AbstractLibFunction {
static final New INSTANCE = new New();
@Override
protected String name() {
return "new";
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
ClassWrapper classWrapper = args.nextUserdata(ClassWrapper.staticTypeName(), ClassWrapper.class);
final ObjectWrapper instance;
try {
instance = ObjectWrapper.newInstance(classWrapper.get(), new Object[] { });
}
catch (MethodSelectionException | IllegalAccessException | InstantiationException
| InvocationTargetException ex) {
throw new LuaRuntimeException(ex);
}
context.getReturnBuffer().setTo(instance);
}
}
/**
* {@code createProxy(interfaceNames, luaObject)}
*
* <p>We can also, instead of creating a Java object to be manipulated by Lua, create a Lua
* object that will be manipulated by Java. We can do that in LuaJava by creating a proxy to
* that object. This is done by the {@code createProxy} function.</p>
*
* <p>The function {@code createProxy} returns a java Object reference that can be used as
* an implementation of the given interface.</p>
*
* <p>{@code createProxy} receives a string that contains the names of the interfaces to
* be implemented, separated by a comma ({@code ,}), and a Lua object that is the interface
* implementation.</p>
*
* <p>Example:</p>
*
* <pre>
* button = luajava.newInstance("java.awt.Button", "execute")
* button_cb = {}
* function button_cb.actionPerformed(ev)
* -- ...
* end
*
* buttonProxy = luajava.createProxy("java.awt.ActionListener",
* button_cb)
*
* button:addActionListener(buttonProxy)
* </pre>
*
* <p>We can use Lua scripts to write implementations only for Java interfaces.</p>
*/
static class CreateProxy extends AbstractLibFunction {
static final CreateProxy INSTANCE = new CreateProxy();
@Override
protected String name() {
return "createProxy";
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
throw new UnsupportedOperationException("not implemented: " + name()); // TODO
}
}
/**
* {@code loadLib(className, methodName)}
*
* <p>loadLib is a function that has a use similar to Lua's {@code loadlib} function.
* The purpose of this function is to allow users to write libraries in Java and then load
* them into Lua.</p>
*
* <p>What {@code loadLib} does is call a static function in a given class and execute
* a given method, which should receive {@code LuaState} as parameter. If this function
* returns a integer, LuaJava takes it as the number of parameters returned by the the
* function, otherwise nothing is returned.</p>
*
* <p>The following Lua example can access the global {@code eg} created by the Java class
* {@code test.LoadLibExample}:
*
* <pre>
* luajava.loadLib("test.LoadLibExample", "open")
* eg.example(3)
* </pre>
*
* <p>And this Java example implements the method {@code example}:</p>
*
* <pre>
* public static int open(LuaState L) throws LuaException {
* L.newTable();
* L.pushValue(-1);
* L.setGlobal("eg");
*
* L.pushString("example");
*
* L.pushJavaFunction(new JavaFunction(L) {
* //
* // Example for loadLib.
* // Prints the time and the first parameter, if any.
* //
* public int execute() throws LuaException {
* System.out.println(new Date().toString());
*
* if (L.getTop() > 1) {
* System.out.println(getParam(2));
* }
*
* return 0;
* }
* });
*
* L.setTable(-3);
*
* return 1;
* }
* </pre>
*/
static class LoadLib extends AbstractLibFunction {
static final LoadLib INSTANCE = new LoadLib();
@Override
protected String name() {
return "loadLib";
}
@Override
protected void invoke(ExecutionContext context, ArgumentIterator args) throws ResolvedControlThrowable {
throw new UnsupportedOperationException("not implemented: " + name()); // TODO
}
}
}
| apache-2.0 |
cr0wbar/Bananarama | bananarama-core/src/main/java/org/bananarama/crud/UpdateOperation.java | 958 | /*
* Copyright 2016 BananaRama.
*
* 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.bananarama.crud;
import com.googlecode.cqengine.query.option.QueryOptions;
import java.util.stream.Stream;
/**
*
* @author Guglielmo De Concini
*/
public interface UpdateOperation<T> extends BasicOperation{
public UpdateOperation<T> from(Stream<T> data);
public UpdateOperation<T> from(Stream<T> data,QueryOptions options);
}
| apache-2.0 |
lecousin/java-framework-core | net.lecousin.core/src/test/java/net/lecousin/framework/core/tests/io/provider/TestByteArrayIOProvider.java | 1031 | package net.lecousin.framework.core.tests.io.provider;
import net.lecousin.framework.concurrent.threads.Task;
import net.lecousin.framework.core.test.LCCoreAbstractTest;
import net.lecousin.framework.io.provider.ByteArrayIOProvider;
import org.junit.Assert;
import org.junit.Test;
public class TestByteArrayIOProvider extends LCCoreAbstractTest {
@Test
public void test() throws Exception {
ByteArrayIOProvider provider = new ByteArrayIOProvider(new byte[100], "test");
provider.provideIOReadable(Task.Priority.NORMAL).close();
provider.provideIOReadableSeekable(Task.Priority.NORMAL).close();
provider.provideIOReadableSeekableKnownSize(Task.Priority.NORMAL).close();
provider.provideIOReadWrite(Task.Priority.NORMAL).close();
provider.provideIOReadWriteSeekable(Task.Priority.NORMAL).close();
provider.provideIOWritable(Task.Priority.NORMAL).close();
provider.provideIOWritableSeekable(Task.Priority.NORMAL).close();
Assert.assertEquals("test", provider.getDescription());
}
}
| apache-2.0 |
4data/hibernate-memcached | src/main/java/br/com/dlbca/hibernate/memcached/generator/exception/MacAddressException.java | 300 | package br.com.dlbca.hibernate.memcached.generator.exception;
/**
* Exception for MacAddress.
*
* @author bruno
*
*/
@SuppressWarnings("serial")
public class MacAddressException extends RuntimeException {
public MacAddressException(String message, Exception e) {
super(message, e);
}
}
| apache-2.0 |
Tarnumx/Jtest | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactCreationTests.java | 2936 | package ru.stqa.pft.addressbook.tests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.*;
import ru.stqa.pft.addressbook.model.ContactData;
public class ContactCreationTests {
FirefoxDriver wd;
@BeforeMethod
public void setUp() throws Exception {
wd = new FirefoxDriver();
wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
wd.get("http://localhost/addressbook/");
login("admin", "secret");
}
private void login(String userName, String password) {
wd.findElement(By.name("user")).click();
wd.findElement(By.name("user")).clear();
wd.findElement(By.name("user")).sendKeys(userName);
wd.findElement(By.name("pass")).click();
wd.findElement(By.name("pass")).clear();
wd.findElement(By.name("pass")).sendKeys(password);
wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click();
}
@Test
public void testContact() {
groupCreation();
groupForms(new ContactData("Alexey", "Sitnikov", "Moscow", "988", "alexey.sitnikov@ya.ru"));
enterInfo();
returnToHomepage();
}
private void returnToHomepage() {
wd.findElement(By.linkText("home page")).click();
}
private void enterInfo() {
wd.findElement(By.xpath("//div[@id='content']/form/input[21]")).click();
}
private void groupForms(ContactData formGroups) {
wd.findElement(By.name("firstname")).click();
wd.findElement(By.name("firstname")).clear();
wd.findElement(By.name("firstname")).sendKeys(formGroups.getFirstName());
wd.findElement(By.name("lastname")).click();
wd.findElement(By.name("lastname")).clear();
wd.findElement(By.name("lastname")).sendKeys(formGroups.getLastName());
wd.findElement(By.name("address")).click();
wd.findElement(By.name("address")).clear();
wd.findElement(By.name("address")).sendKeys(formGroups.getAddress());
wd.findElement(By.name("mobile")).click();
wd.findElement(By.name("mobile")).clear();
wd.findElement(By.name("mobile")).sendKeys(formGroups.getPhoneNumMob());
wd.findElement(By.name("email")).click();
wd.findElement(By.name("email")).clear();
wd.findElement(By.name("email")).sendKeys(formGroups.getEmail());
}
private void groupCreation() {
wd.findElement(By.linkText("add new")).click();
}
@AfterMethod
public void tearDown() {
wd.quit();
}
public static boolean isAlertPresent(FirefoxDriver wd) {
try {
wd.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
}
| apache-2.0 |
EsupPortail/esup-publisher | src/test/java/org/esupportail/publisher/web/PublishControllerTest.java | 28193 | /**
* Copyright (C) 2014 Esup Portail http://www.esup-portail.org
* @Author (C) 2012 Julien Gribonvald <julien.gribonvald@recia.fr>
*
* 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.esupportail.publisher.web;
import static org.hamcrest.Matchers.blankOrNullString;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.xpath;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.esupportail.publisher.Application;
import org.esupportail.publisher.config.Constants;
import org.esupportail.publisher.domain.AbstractItem;
import org.esupportail.publisher.domain.Attachment;
import org.esupportail.publisher.domain.Category;
import org.esupportail.publisher.domain.Flash;
import org.esupportail.publisher.domain.ItemClassificationOrder;
import org.esupportail.publisher.domain.LinkedFileItem;
import org.esupportail.publisher.domain.News;
import org.esupportail.publisher.domain.Organization;
import org.esupportail.publisher.domain.Publisher;
import org.esupportail.publisher.domain.Reader;
import org.esupportail.publisher.domain.Redactor;
import org.esupportail.publisher.domain.Subscriber;
import org.esupportail.publisher.domain.enums.DisplayOrderType;
import org.esupportail.publisher.domain.enums.ItemStatus;
import org.esupportail.publisher.domain.enums.ItemType;
import org.esupportail.publisher.domain.enums.PermissionClass;
import org.esupportail.publisher.domain.enums.SubscribeType;
import org.esupportail.publisher.domain.enums.WritingMode;
import org.esupportail.publisher.repository.CategoryRepository;
import org.esupportail.publisher.repository.ItemClassificationOrderRepository;
import org.esupportail.publisher.repository.ItemRepository;
import org.esupportail.publisher.repository.LinkedFileItemRepository;
import org.esupportail.publisher.repository.ObjTest;
import org.esupportail.publisher.repository.OrganizationRepository;
import org.esupportail.publisher.repository.PublisherRepository;
import org.esupportail.publisher.repository.ReaderRepository;
import org.esupportail.publisher.repository.RedactorRepository;
import org.esupportail.publisher.repository.SubscriberRepository;
import org.esupportail.publisher.service.HighlightedClassificationService;
import org.esupportail.publisher.service.SubscriberService;
import org.esupportail.publisher.service.bean.ServiceUrlHelper;
import org.esupportail.publisher.service.factories.CategoryFactory;
import org.esupportail.publisher.service.factories.CategoryProfileFactory;
import org.esupportail.publisher.service.factories.FlashInfoVOFactory;
import org.esupportail.publisher.service.factories.ItemVOFactory;
import org.esupportail.publisher.service.factories.RubriqueVOFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by jgribonvald on 08/06/16.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
@Slf4j
@Transactional
public class PublishControllerTest {
private MockMvc restPublishControllerMockMvc;
@Autowired
private OrganizationRepository organizationRepository;
@Autowired
private PublisherRepository publisherRepository;
// @Autowired
// private ClassificationRepository<AbstractClassification> classificationRepository;
@Autowired
private CategoryRepository categoryRepository;
//
// @Inject
// private FeedRepository<AbstractFeed> feedRepository;
@Autowired
private ReaderRepository readerRepository;
@Autowired
private RedactorRepository redactorRepository;
@Autowired
private ItemRepository<AbstractItem> itemRepository;
// @Inject
// private FlashRepository flashRepository;
@Autowired
private ItemClassificationOrderRepository itemClassificationOrderRepository;
@Autowired
private FlashInfoVOFactory flashInfoVOFactory;
@Autowired
private RubriqueVOFactory rubriqueVOFactory;
@Autowired
private ItemVOFactory itemVOFactory;
@Autowired
private CategoryProfileFactory categoryProfileFactory;
@Autowired
private CategoryFactory categoryFactory;
@Autowired
private SubscriberService subscriberService;
@Autowired
private SubscriberRepository subscriberRepository;
@Autowired
private ServiceUrlHelper urlHelper;
@Autowired
private HighlightedClassificationService highlightedClassificationService;
@Autowired
private LinkedFileItemRepository linkedFileItemRepository;
private static final Map<String, String> namespaces =
Collections.singletonMap("dc", "http://purl.org/dc/elements/1.1/");
@PostConstruct
public void setup() {
MockitoAnnotations.initMocks(this);
PublishController publishController = new PublishController();
ReflectionTestUtils.setField(publishController, "organizationRepository", organizationRepository);
ReflectionTestUtils.setField(publishController, "publisherRepository", publisherRepository);
//ReflectionTestUtils.setField(publishController, "flashRepository", flashRepository);
ReflectionTestUtils.setField(publishController, "categoryRepository", categoryRepository);
//ReflectionTestUtils.setField(publishController, "classificationRepository", classificationRepository);
ReflectionTestUtils.setField(publishController, "itemClassificationOrderRepository", itemClassificationOrderRepository);
ReflectionTestUtils.setField(publishController, "rubriqueVOFactory", rubriqueVOFactory);
ReflectionTestUtils.setField(publishController, "itemVOFactory", itemVOFactory);
ReflectionTestUtils.setField(publishController, "categoryProfileFactory", categoryProfileFactory);
ReflectionTestUtils.setField(publishController, "categoryFactory", categoryFactory);
ReflectionTestUtils.setField(publishController, "flashInfoVOFactory", flashInfoVOFactory);
ReflectionTestUtils.setField(publishController, "subscriberService", subscriberService);
ReflectionTestUtils.setField(publishController, "urlHelper", urlHelper);
ReflectionTestUtils.setField(publishController, "highlightedClassificationService", highlightedClassificationService);
ReflectionTestUtils.setField(publishController, "linkedFileItemRepository", linkedFileItemRepository);
this.restPublishControllerMockMvc = MockMvcBuilders.standaloneSetup(publishController).build();
}
private Publisher newWay;
private Publisher filesPub;
private Publisher flashInfo;
private Publisher esupLectureWay;
private Organization organization;
private List<LinkedFileItem> files = new ArrayList<>();
private List<Category> catsOfEsupLectureWay = new ArrayList<>();
private News savedNews;
@Before
public void initTest() throws InterruptedException {
organization = new Organization();
organization.setDescription("A Desc");
organization.setDisplayOrder(200);
organization.setName("A TESTER" );
organization.setDisplayName("À tester");
organization.setIdentifiers(Sets.newHashSet("0450822X", "0370028X"));
organization = organizationRepository.saveAndFlush(organization);
Reader reader1 = ObjTest.newReader("1");
reader1 = readerRepository.saveAndFlush(reader1);
Reader reader2 = ObjTest.newReader("2");
reader2 = readerRepository.saveAndFlush(reader2);
Reader reader3 = ObjTest.newReader("3");
reader3.getAuthorizedTypes().clear();
reader3.getAuthorizedTypes().add(ItemType.ATTACHMENT);
reader3 = readerRepository.saveAndFlush(reader3);
Redactor redactor1 = ObjTest.newRedactor("1");
redactor1 = redactorRepository.saveAndFlush(redactor1);
Redactor redactor2 = ObjTest.newRedactor("2");
redactor2 = redactorRepository.saveAndFlush(redactor2);
Redactor redactor3 = ObjTest.newRedactor("3");
redactor3.setOptionalPublishTime(true);
redactor3 = redactorRepository.saveAndFlush(redactor3);
Redactor redactor4 = ObjTest.newRedactor("4");
redactor4.setWritingMode(WritingMode.STATIC);
redactor4 = redactorRepository.saveAndFlush(redactor4);
newWay = new Publisher(organization, reader1, redactor1, "PUB 1", PermissionClass.CONTEXT, true,true, true);
newWay.setDefaultDisplayOrder(DisplayOrderType.NAME);
newWay = publisherRepository.saveAndFlush(newWay);
flashInfo = new Publisher(organization, reader2, redactor2, "PUB 2", PermissionClass.CONTEXT, true,false, false);
flashInfo = publisherRepository.saveAndFlush(flashInfo);
filesPub = new Publisher(organization, reader3, redactor3, "PUB 3", PermissionClass.CONTEXT, true,true, false);
filesPub = publisherRepository.saveAndFlush(filesPub);
esupLectureWay = new Publisher(organization, reader1, redactor4, "PUB 4 ", PermissionClass.CONTEXT, true, true, false);
esupLectureWay = publisherRepository.saveAndFlush(esupLectureWay);
// number of cats in publisher newWay is needed in getItemsFromPublisherTest
// NB important, à la une isn't persisted, it's hardcoded and should be considered
Category cat1 = ObjTest.newCategory("Cat A", newWay);
cat1.setDefaultDisplayOrder(DisplayOrderType.CUSTOM);
cat1 = categoryRepository.saveAndFlush(cat1);
Category cat2 = ObjTest.newCategory("cat B", newWay);
cat2 = categoryRepository.saveAndFlush(cat2);
Category cat3 = ObjTest.newCategory("cat C", flashInfo);
cat3 = categoryRepository.saveAndFlush(cat3);
Category cat4 = ObjTest.newCategory("cat D", filesPub);
cat4 = categoryRepository.saveAndFlush(cat4);
Category cat5 = ObjTest.newCategory("Cat E", esupLectureWay);
cat5 = categoryRepository.saveAndFlush(cat5);
catsOfEsupLectureWay.add(cat5);
Category cat6 = ObjTest.newCategory("cat F", esupLectureWay);
cat6 = categoryRepository.saveAndFlush(cat6);
catsOfEsupLectureWay.add(cat6);
News news1 = ObjTest.newNews("news 1", organization, newWay.getContext().getRedactor());
// Don't update date, a test on SCHEDULED => PUBLISHED is made
news1.setStartDate(LocalDate.now());
news1.setEndDate(LocalDate.now().plusMonths(1));
news1.setStatus(ItemStatus.SCHEDULED);
news1 = itemRepository.saveAndFlush(news1);
final Instant news1DateModify = news1.getLastModifiedDate().minusSeconds(1);
News news2 = ObjTest.newNews("news 2", organization, newWay.getContext().getRedactor());
news2.setStartDate(LocalDate.now().minusDays(1));
news2.setEndDate(LocalDate.now().plusMonths(1));
news2.setStatus(ItemStatus.PUBLISHED);
news2 = itemRepository.saveAndFlush(news2);
News news3 = ObjTest.newNews("news 3", organization, newWay.getContext().getRedactor());
news3.setStatus(ItemStatus.PUBLISHED);
news3.setStartDate(LocalDate.now().minusDays(2));
news3.setEndDate(LocalDate.now().plusMonths(1));
news3 = itemRepository.saveAndFlush(news3);
News news4 = ObjTest.newNews("news 4", organization, newWay.getContext().getRedactor());
news4.setStatus(ItemStatus.ARCHIVED);
news4.setStartDate(LocalDate.now().minusMonths(1));
news4.setEndDate(LocalDate.now().minusDays(1));
news4 = itemRepository.saveAndFlush(news4);
Flash flash = ObjTest.newFlash("flash 1", organization, flashInfo.getContext().getRedactor());
flash.setStatus(ItemStatus.PUBLISHED);
flash.setStartDate(LocalDate.now());
flash.setEndDate(LocalDate.now().plusMonths(1));
flash = itemRepository.saveAndFlush(flash);
Attachment attachment = ObjTest.newAttachment("file 1", organization, filesPub.getContext().getRedactor());
attachment.setStartDate(LocalDate.now());
attachment.setEndDate(null);
attachment.setStatus(ItemStatus.PUBLISHED);
attachment = itemRepository.saveAndFlush(attachment);
log.debug("==============+> Saved attachment {}", attachment);
News news5 = ObjTest.newNews("news 5", organization, esupLectureWay.getContext().getRedactor());
news5.setStartDate(LocalDate.now());
news5.setEndDate(LocalDate.now().plusMonths(1));
news5.setStatus(ItemStatus.PUBLISHED);
news5 = itemRepository.saveAndFlush(news5);
News news6 = ObjTest.newNews("news 6", organization, esupLectureWay.getContext().getRedactor());
news6.setStartDate(LocalDate.now().minusDays(1));
news6.setEndDate(LocalDate.now().plusMonths(1));
news6.setStatus(ItemStatus.PUBLISHED);
news6 = itemRepository.saveAndFlush(news6);
Thread.sleep(1000);
int nbModif = itemRepository.publishScheduled();
// test news1 SCHEDULED => PUBLISHED + update datemodification and move it to First news in order
Assert.assertEquals(1, nbModif);
news1 = (News)itemRepository.findById(news1.getId()).orElse(null);
Assert.assertNotNull(news1);
Assert.assertEquals(news1.getStatus(), ItemStatus.PUBLISHED);
// This part check if the
log.debug("Modified time before {} and after running publishScheduled {}", news1DateModify, news1.getLastModifiedDate());
Assert.assertTrue("The PublishScheduled task run an update on a wrong timezone ! Check DB time_zone and your java server timezone",
news1.getLastModifiedDate().isAfter(news1DateModify));
files.add(new LinkedFileItem("20052/201608259432.jpg", "truc-image.jpg", attachment, false, "image/jpg"));
files.add(new LinkedFileItem("20052/BBBAADFDSDSD.jpg", "truc2.pdf", attachment, false, "application/pdf"));
linkedFileItemRepository.saveAll(files);
itemClassificationOrderRepository.saveAndFlush(new ItemClassificationOrder(news1, cat1, 0));
itemClassificationOrderRepository.saveAndFlush(new ItemClassificationOrder(news2, cat1, 1));
itemClassificationOrderRepository.saveAndFlush(new ItemClassificationOrder(news3, cat2, 2));
itemClassificationOrderRepository.saveAndFlush(new ItemClassificationOrder(news4, cat2, 3));
itemClassificationOrderRepository.saveAndFlush(new ItemClassificationOrder(flash, cat3, 0));
itemClassificationOrderRepository.saveAndFlush(new ItemClassificationOrder(attachment, cat4, 0));
itemClassificationOrderRepository.saveAndFlush(new ItemClassificationOrder(news5, cat5, 0));
itemClassificationOrderRepository.saveAndFlush(new ItemClassificationOrder(news6, cat6, 0));
Subscriber sub = ObjTest.newSubscriberPerson(organization.getContextKey());
sub.setSubscribeType(SubscribeType.FORCED);
Subscriber sub2 = ObjTest.newSubscriberGroup(news1.getContextKey());
Subscriber sub3 = ObjTest.newSubscriberGroup(news2.getContextKey());
sub3.setSubscribeType(SubscribeType.FORCED);
Subscriber sub4 = ObjTest.newSubscriberPerson(news3.getContextKey());
Subscriber sub5 = ObjTest.newSubscriberPerson(news4.getContextKey());
Subscriber sub6 = ObjTest.newSubscriberPerson(attachment.getContextKey());
Subscriber sub7 = ObjTest.newSubscriberGroup(cat5.getContextKey());
sub = subscriberRepository.saveAndFlush(sub);
sub2 = subscriberRepository.saveAndFlush(sub2);
sub3 = subscriberRepository.saveAndFlush(sub3);
sub4 = subscriberRepository.saveAndFlush(sub4);
sub5 = subscriberRepository.saveAndFlush(sub5);
sub6 = subscriberRepository.saveAndFlush(sub6);
sub7 = subscriberRepository.saveAndFlush(sub7);
// should be order as first news
savedNews = (News) itemRepository.getOne(news1.getId());
log.debug("News1 {}, {}", news1.getCreatedDate(), news1.getLastModifiedDate());
log.debug("News2 {}, {}", news2.getCreatedDate(), news2.getLastModifiedDate());
log.debug("News3 {}, {}", news3.getCreatedDate(), news3.getLastModifiedDate());
}
@Test
public void getAllPlublisherContextTest() throws Exception {
restPublishControllerMockMvc.perform(get("/published/contexts/{reader_id}/{redactor_id}", newWay.getContext().getReader().getId(), newWay.getContext().getRedactor().getId())
.accept(MediaType.APPLICATION_XML)).andDo(MockMvcResultHandlers.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/categoryProfilesUrl/categoryProfile/visibility/obliged").exists())
.andExpect(xpath("/categoryProfilesUrl/categoryProfile/visibility/allowed").exists())
.andExpect(xpath("/categoryProfilesUrl/categoryProfile/visibility/autoSubscribed").exists())
.andExpect(xpath("/categoryProfilesUrl/categoryProfile/visibility/*[self::obliged or self::allowed or self::autoSubscribed]/*[self::regular or self::group or self::regex]").exists());
//.andExpect(xpath("/categoryProfilesUrl//categoryProfile/visibility//").exists());
}
@Test
public void getEsupLectureCategoriesContextTest() throws Exception {
restPublishControllerMockMvc.perform(get("/published/categories/{publisher_id}", esupLectureWay.getId())
.accept(MediaType.APPLICATION_XML)).andDo(MockMvcResultHandlers.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/category").exists())
.andExpect(xpath("/category[@name]").exists())
.andExpect(xpath("/category[@edit]").exists())
.andExpect(xpath("/category[@ttl]").exists())
.andExpect(xpath("/category/visibility").exists())
.andExpect(xpath("/category/visibility/obliged").exists())
.andExpect(xpath("/category/visibility/allowed").exists())
.andExpect(xpath("/category/visibility/autoSubscribed").exists())
.andExpect(xpath("/category/visibility/*[self::obliged or self::allowed or self::autoSubscribed]/*[self::regular or self::group or self::regex]").exists())
.andExpect(xpath("/category/sourceProfiles").exists())
.andExpect(xpath("/category/sourceProfiles/*").nodeCount(catsOfEsupLectureWay.size()))
.andExpect(xpath("/category/sourceProfiles/sourceProfile").exists())
.andExpect(xpath("/category/sourceProfiles/*[@name]").exists())
.andExpect(xpath("/category/sourceProfiles/*[@id]").exists())
.andExpect(xpath("/category/sourceProfiles/*[@url]").exists())
.andExpect(xpath("/category/sourceProfiles/*[@specificUserContent]").exists())
.andExpect(xpath("/category/sourceProfiles/*[@access]").exists())
.andExpect(xpath("/category/sourceProfiles/*[@ttl]").exists())
.andExpect(xpath("/category/sourceProfiles/sourceProfile/visibility/*[self::obliged or self::allowed or self::autoSubscribed]").exists());
}
@Test
public void getItemsFromPublisherTest() throws Exception {
log.info("try to compare to {}", savedNews);
restPublishControllerMockMvc.perform(get("/published/items/{publisher_id}", newWay.getId())
.accept(MediaType.APPLICATION_XML)).andDo(MockMvcResultHandlers.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
// FOR XPATH help watch examples on https://howtodoinjava.com/xml/xpath-attribute-evaluate/
.andExpect(xpath("/actualites/rubriques/*").nodeCount(3))
.andExpect(xpath("/actualites/rubriques/rubrique/uuid").exists())
.andExpect(xpath("/actualites/rubriques/rubrique/uuid").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/rubriques/rubrique/name").exists())
.andExpect(xpath("/actualites/rubriques/rubrique/name").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/rubriques/rubrique/color").exists())
.andExpect(xpath("/actualites/rubriques/rubrique/color").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/rubriques/rubrique/highlight").exists())
.andExpect(xpath("/actualites/rubriques/rubrique/highlight").booleanValue(true))
.andExpect(xpath("/actualites/items/*").nodeCount(3))
.andExpect(xpath("/actualites/items/item/article/title").exists())
.andExpect(xpath("/actualites/items/item/article/title").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/article/link").exists())
.andExpect(xpath("/actualites/items/item/article/link").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/article/enclosure").exists())
.andExpect(xpath("/actualites/items/item/article/enclosure").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/article/description").exists())
.andExpect(xpath("/actualites/items/item/article/description").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/article/pubDate").exists())
.andExpect(xpath("/actualites/items/item/article/pubDate").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/article/guid").exists())
.andExpect(xpath("/actualites/items/item/article/guid").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/article/category").exists())
.andExpect(xpath("/actualites/items/item/article/category").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/article/dc:date", namespaces).exists())
.andExpect(xpath("/actualites/items/item/article/dc:date", namespaces).string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/article/files").exists())
.andExpect(xpath("/actualites/items/item/type").exists())
.andExpect(xpath("/actualites/items/item/type").string(News.class.getSimpleName()))
.andExpect(xpath("/actualites/items/item/creator").exists())
.andExpect(xpath("/actualites/items/item/creator").string(Constants.SYSTEM_ACCOUNT))
.andExpect(xpath("/actualites/items/item/pubDate").exists())
.andExpect(xpath("/actualites/items/item/pubDate").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/createdDate").exists())
.andExpect(xpath("/actualites/items/item/createdDate").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/modifiedDate").exists())
.andExpect(xpath("/actualites/items/item/modifiedDate").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/uuid").exists())
.andExpect(xpath("/actualites/items/item/uuid").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item[1]/article/title").string(savedNews.getTitle()))
.andExpect(xpath("/actualites/items/item[1]/article/description").string(savedNews.getSummary()))
.andExpect(xpath("/actualites/items/item[1]/article/pubDate").string(
DateTimeFormatter.RFC_1123_DATE_TIME.withZone(ZoneId.systemDefault()).format(savedNews.getStartDate().atStartOfDay(ZoneId.systemDefault()))))
.andExpect(xpath("/actualites/items/item/visibility").exists())
.andExpect(xpath("/actualites/items/item/visibility/obliged").exists())
.andExpect(xpath("/actualites/items/item/visibility/*[self::obliged or self::allowed or self::autoSubscribed]/*[self::regular or self::group or self::regex]").exists())
.andExpect(xpath("/actualites/items/item/visibility/obliged/regular/@attribute").exists())
.andExpect(xpath("/actualites/items/item/visibility/obliged/regular/@attribute").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/visibility/obliged/regular/@value").exists())
.andExpect(xpath("/actualites/items/item/visibility/obliged/regular/@value").string(not(blankOrNullString())))
.andExpect(xpath("/actualites/items/item/visibility/allowed").exists())
.andExpect(xpath("/actualites/items/item/visibility/autoSubscribed").exists());
}
@Test
public void getItemsAttachmentFromPublisherTest() throws Exception {
restPublishControllerMockMvc.perform(get("/published/items/{publisher_id}", filesPub.getId())
.accept(MediaType.APPLICATION_XML)).andDo(MockMvcResultHandlers.print()).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_XML))
.andExpect(xpath("/actualites/rubriques/*").nodeCount(1))
.andExpect(xpath("/actualites/items/*").nodeCount(1))
.andExpect(xpath("/actualites/items/item/article/pubDate").exists())
.andExpect(xpath("/actualites/items/item/type").exists())
.andExpect(xpath("/actualites/items/item/type").string(Attachment.class.getSimpleName()))
.andExpect(xpath("/actualites/items/item/rubriques/uuid").exists())
.andExpect(xpath("/actualites/items/item/article/files").exists())
.andExpect(xpath("/actualites/items/item/article/files/*").nodeCount(files.size()))
.andExpect(xpath("/actualites/items/item/article/files/file").exists())
.andExpect(xpath("/actualites/items/item/article/files/file/uri").exists())
.andExpect(xpath("/actualites/items/item/article/files/file/fileName").exists())
.andExpect(xpath("/actualites/items/item/article/files/file/contentType").exists())
.andExpect(xpath("/actualites/items/item/visibility").exists())
.andExpect(xpath("/actualites/items/item/visibility/obliged").exists())
.andExpect(xpath("/actualites/items/item/visibility/*[self::obliged or self::allowed or self::autoSubscribed]/*[self::regular or self::group or self::regex]").exists())
.andExpect(xpath("/actualites/items/item/visibility/allowed").exists())
.andExpect(xpath("/actualites/items/item/visibility/autoSubscribed").exists());
}
} | apache-2.0 |
BasisTI/rancher-java-sdk | src/main/java/io/rancher/service/SnapshotService.java | 1187 | package io.rancher.service;
import io.rancher.base.Filters;
import io.rancher.base.TypeCollection;
import io.rancher.type.Snapshot;
import io.rancher.type.SnapshotBackupInput;
import io.rancher.type.Backup;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;
public interface SnapshotService {
@GET("snapshot")
Call<TypeCollection<Snapshot>> list();
@GET("snapshot")
Call<TypeCollection<Snapshot>> list(@QueryMap Filters filters);
@GET("snapshot/{id}")
Call<Snapshot> get(@Path("id") String id);
@POST("snapshot")
Call<Snapshot> create(@Body Snapshot snapshot);
@PUT("snapshot/{id}")
Call<Snapshot> update(@Path("id") String id, @Body Snapshot snapshot);
@DELETE("snapshot/{id}")
Call<Response> delete(@Path("id") String id);
@POST("snapshot/{id}?action=backup")
Call<Backup> backup(@Path("id") String id, @Body SnapshotBackupInput snapshotBackupInput);
@POST("snapshot/{id}?action=remove")
Call<Snapshot> remove(@Path("id") String id);
}
| apache-2.0 |
ydxlt/amm | src/cn/jxust/base/service/DepartmentService.java | 12102 | package cn.jxust.base.service;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.jxust.base.dao.DepartmentDao;
import cn.jxust.base.model.Department;
import cn.jxust.orm.PageData;
import cn.jxust.orm.hibernate.BaseDao;
import cn.jxust.orm.hibernate.BaseService;
import cn.jxust.utils.JsonUtils;
@Service
@Transactional
public class DepartmentService extends BaseService<Department>
{
@Override
@Resource(name="departmentDao")
public void setBaseDao(BaseDao<Department> baseDao)
{
this.baseDao = baseDao;
}
public DepartmentDao getDepartmentDao()
{
return (DepartmentDao)baseDao;
}
public List<Department> getAll()
{
return getDepartmentDao().findList("from Department order by departmentType,ordNum");
}
public PageData<Department> getAllByPage(int pageNum, Department entity)
{
return getDepartmentDao().findAllByPage(pageNum, entity);
}
public List<Department> getByType(String type)
{
return getDepartmentDao().findByType(type);
}
public Department getById(String id)
{
return getDepartmentDao().find(id);
}
public List<Department> getByFixedQuota()
{
return getDepartmentDao().findByFixedQuota();
}
/**
* 获取单位累计排名
* @param deptType
* @return
*/
public Integer getTotalScoreByDept(Department dept)
{
if(null == dept.getTotalScore() || dept.getTotalScore() == 0)
{
return 1;
}
List<Department> depts = getDepartmentDao().findTotalScore(dept.getDepartmentType());
int index = 0;
double score = 0d;
for(Department d : depts)
{
if(d.getTotalScore() != score)
{
score = d.getTotalScore();
index++;
}
if(d.getDepartmentId().equals(dept.getDepartmentId()))
{
break;
}
}
return index;
}
/**
* 获取单位累计排名指数
* @param dept
* @return
*/
public Double getTotalScoreRankByDept(Department dept)
{
if(null == dept.getTotalScore() || dept.getTotalScore() == 0)
{
return 1d;
}
List<Department> depts = getDepartmentDao().findTotalScore(dept.getDepartmentType());
int size = depts.size();
int index = 0;
double score = 0d;
for(Department d : depts)
{
if(d.getTotalScore() != score)
{
score = d.getTotalScore();
index++;
}
if(d.getDepartmentId().equals(dept.getDepartmentId()))
{
break;
}
}
double rank = new Double(size - index + 1) / size;
return rank;
}
public List<Department> getTotalScore(String deptType)
{
return getDepartmentDao().findTotalScore(deptType);
}
public List<Department> getTotalScore(String deptType, int num)
{
List<Department> depts = getDepartmentDao().findTotalScore(deptType);
if(depts.size() > num)
{
return depts.subList(0, num);
}
else
{
return depts;
}
}
/**
* 将deptDesc拆分成Map对象
* @param deptDesc
* @return
*/
public Map<String, Object> convenDescToMap(String deptDesc)
{
if(null != deptDesc && !"".equals(deptDesc.trim()))
{
return JsonUtils.string2map(deptDesc);
}
return null;
}
public void updateDetails(String deptId, Map<String, Object> value)
{
StringBuilder sb = new StringBuilder();
sb.append("{");
if(null==value.get("3") || "".equals(value.get("3")))
{
sb.append("辖区总人口数:");
sb.append("'");
if(null != value.get("1") && !"".equals(value.get("1")))
{
sb.append(value.get("1"));
}
sb.append("'");
sb.append(",");
sb.append("村数:");
sb.append("'");
if(null != value.get("2") && !"".equals(value.get("2")))
{
sb.append(value.get("2"));
}
sb.append("'");
sb.append(",");
}
else
{
sb.append("单位职工数:");
sb.append("'");
if(null != value.get("3") && !"".equals(value.get("3")))
{
sb.append(value.get("3"));
}
sb.append("'");
sb.append(",");
}
sb.append("主要领导:");
sb.append("'");
if(null != value.get("4") && !"".equals(value.get("4")))
{
sb.append(value.get("4"));
}
sb.append("'");
sb.append(",");
sb.append("分管领导:");
sb.append("'");
if(null != value.get("5") && !"".equals(value.get("5")))
{
sb.append(value.get("5"));
}
sb.append("'");
sb.append(",");
sb.append("综治工作人员1:");
sb.append("'");
if(null != value.get("6") && !"".equals(value.get("6")))
{
sb.append(value.get("6"));
}
sb.append("'");
sb.append(",");
sb.append("职务1:");
sb.append("'");
if(null != value.get("7") && !"".equals(value.get("7")))
{
sb.append(value.get("7"));
}
sb.append("'");
sb.append(",");
sb.append("办公地址:");
sb.append("'");
if(null != value.get("8") && !"".equals(value.get("8")))
{
sb.append(value.get("8"));
}
sb.append("'");
sb.append(",");
sb.append("主要领导职务:");
sb.append("'");
if(null != value.get("9") && !"".equals(value.get("9")))
{
sb.append(value.get("9"));
}
sb.append("'");
sb.append(",");
sb.append("主要领导联系电话:");
sb.append("'");
if(null != value.get("10") && !"".equals(value.get("10")))
{
sb.append(value.get("10"));
}
sb.append("'");
sb.append(",");
sb.append("分管领导职务:");
sb.append("'");
if(null != value.get("11") && !"".equals(value.get("11")))
{
sb.append(value.get("11"));
}
sb.append("'");
sb.append(",");
sb.append("分管领导联系电话:");
sb.append("'");
if(null != value.get("12") && !"".equals(value.get("12")))
{
sb.append(value.get("12"));
}
sb.append("'");
sb.append(",");
sb.append("联系电话1:");
sb.append("'");
if(null != value.get("13") && !"".equals(value.get("13")))
{
sb.append(value.get("13"));
}
sb.append("'");
sb.append(",");
sb.append("综治工作人员2:");
sb.append("'");
if(null != value.get("14") && !"".equals(value.get("14")))
{
sb.append(value.get("14"));
}
sb.append("'");
sb.append(",");
sb.append("综治工作人员3:");
sb.append("'");
if(null != value.get("15") && !"".equals(value.get("15")))
{
sb.append(value.get("15"));
}
sb.append("'");
sb.append(",");
sb.append("综治工作人员4:");
sb.append("'");
if(null != value.get("16") && !"".equals(value.get("16")))
{
sb.append(value.get("16"));
}
sb.append("'");
sb.append(",");
sb.append("综治工作人员5:");
sb.append("'");
if(null != value.get("17") && !"".equals(value.get("17")))
{
sb.append(value.get("17"));
}
sb.append("'");
sb.append(",");
sb.append("职务2:");
sb.append("'");
if(null != value.get("18") && !"".equals(value.get("18")))
{
sb.append(value.get("18"));
}
sb.append("'");
sb.append(",");
sb.append("职务3:");
sb.append("'");
if(null != value.get("19") && !"".equals(value.get("19")))
{
sb.append(value.get("19"));
}
sb.append("'");
sb.append(",");
sb.append("职务4:");
sb.append("'");
if(null != value.get("20") && !"".equals(value.get("20")))
{
sb.append(value.get("20"));
}
sb.append("'");
sb.append(",");
sb.append("职务5:");
sb.append("'");
if(null != value.get("21") && !"".equals(value.get("21")))
{
sb.append(value.get("21"));
}
sb.append("'");
sb.append(",");
sb.append("联系电话2:");
sb.append("'");
if(null != value.get("22") && !"".equals(value.get("22")))
{
sb.append(value.get("22"));
}
sb.append("'");
sb.append(",");
sb.append("联系电话3:");
sb.append("'");
if(null != value.get("23") && !"".equals(value.get("23")))
{
sb.append(value.get("23"));
}
sb.append("'");
sb.append(",");
sb.append("联系电话4:");
sb.append("'");
if(null != value.get("24") && !"".equals(value.get("24")))
{
sb.append(value.get("24"));
}
sb.append("'");
sb.append(",");
sb.append("联系电话5:");
sb.append("'");
if(null != value.get("25") && !"".equals(value.get("25")))
{
sb.append(value.get("25"));
}
sb.append("'");
sb.append("}");
Department dept = find(deptId);
dept.setDepartmentDesc(sb.toString());
update(dept);
}
/**
* 显示dept details
* @param deptId
* @return
*/
public String viewDetails(String deptId)
{
StringBuilder sb = new StringBuilder();
Department dept = find(deptId);
Map<String, Object> desc = JsonUtils.string2map(dept.getDepartmentDesc());
// Iterator<String> it = desc.keySet().iterator();
// while(it.hasNext())
// {
// String key = it.next();
// sb.append("<strong>");
// sb.append(key);
// sb.append("</strong>");
// sb.append(":");
// sb.append(desc.get(key));
// sb.append("<br/>");
// }
if(!desc.isEmpty())
{
if(desc.containsKey("辖区总人口数"))
{
sb.append("<div class=\"row-fluid\">");
sb.append("辖区总人口数");
sb.append(desc.get("辖区总人口数"));
sb.append(" 村(居)数");
sb.append(desc.get("村数"));
sb.append("</div>");
}
else
{
sb.append("<div class=\"row-fluid\">单位职工数");
sb.append(desc.get("单位职工数"));
sb.append("</div>");
}
sb.append("<br/>");
sb.append("<div>");
sb.append("<strong>主要领导:</strong>");
sb.append(desc.get("主要领导"));
sb.append(" [");
sb.append(desc.get("主要领导职务"));
sb.append("]<br/><strong>联系电话:</strong>");
sb.append(desc.get("主要领导联系电话"));
sb.append("</div>");
sb.append("<div>");
sb.append("<strong>分管领导:</strong>");
sb.append(desc.get("分管领导"));
sb.append(" [");
sb.append(desc.get("分管领导职务"));
sb.append("]<br/><strong>联系电话:</strong>");
sb.append(desc.get("分管领导联系电话"));
sb.append("</div>");
sb.append("<div>");
sb.append("<strong>综治工作人员:</strong>");
sb.append("<br/>");
if(!"".equals(desc.get("综治工作人员1")))
{
sb.append((null == desc.get("综治工作人员1"))?"":desc.get("综治工作人员1"));
sb.append(" [");
sb.append((null == desc.get("职务1"))?"":desc.get("职务1"));
sb.append("] ");
sb.append((null == desc.get("联系电话1"))?"":desc.get("联系电话1"));
sb.append("<br/>");
}
if(!"".equals(desc.get("综治工作人员2")))
{
sb.append((null == desc.get("综治工作人员2"))?"":desc.get("综治工作人员2"));
sb.append(" [");
sb.append((null == desc.get("职务2"))?"":desc.get("职务2"));
sb.append("] ");
sb.append((null == desc.get("联系电话2"))?"":desc.get("联系电话2"));
sb.append("<br/>");
}
if(!"".equals(desc.get("综治工作人员3")))
{
sb.append((null == desc.get("综治工作人员3"))?"":desc.get("综治工作人员3"));
sb.append(" [");
sb.append((null == desc.get("职务3"))?"":desc.get("职务3"));
sb.append("] ");
sb.append((null == desc.get("联系电话3"))?"":desc.get("联系电话3"));
sb.append("<br/>");
}
if(!"".equals(desc.get("综治工作人员4")))
{
sb.append((null == desc.get("综治工作人员4"))?"":desc.get("综治工作人员4"));
sb.append(" [");
sb.append((null == desc.get("职务4"))?"":desc.get("职务4"));
sb.append("] ");
sb.append((null == desc.get("联系电话4"))?"":desc.get("联系电话4"));
sb.append("<br/>");
}
if(!"".equals(desc.get("综治工作人员5")))
{
sb.append((null == desc.get("综治工作人员5"))?"":desc.get("综治工作人员5"));
sb.append(" [");
sb.append((null == desc.get("职务5"))?"":desc.get("职务5"));
sb.append("] ");
sb.append((null == desc.get("联系电话5"))?"":desc.get("联系电话5"));
sb.append("<br/>");
}
sb.append("</div>");
sb.append("<div>");
sb.append("<strong>办公地址:</strong>");
sb.append(desc.get("办公地址"));
sb.append("</div>");
}
return sb.toString();
}
}
| apache-2.0 |
marcusthebrown/spatialconnect-android-sdk | spatialconnect/src/main/java/com/boundlessgeo/spatialconnect/services/SCBackendService.java | 27299 | /**
* Copyright 2016 Boundless, http://boundlessgeo.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.boundlessgeo.spatialconnect.services;
import android.content.Context;
import android.os.Build;
import android.util.Log;
import com.boundlessgeo.schema.Actions;
import com.boundlessgeo.schema.MessagePbf;
import com.boundlessgeo.spatialconnect.SpatialConnect;
import com.boundlessgeo.spatialconnect.config.SCConfig;
import com.boundlessgeo.spatialconnect.config.SCFormConfig;
import com.boundlessgeo.spatialconnect.config.SCRemoteConfig;
import com.boundlessgeo.spatialconnect.config.SCStoreConfig;
import com.boundlessgeo.spatialconnect.geometries.SCSpatialFeature;
import com.boundlessgeo.spatialconnect.mqtt.MqttHandler;
import com.boundlessgeo.spatialconnect.mqtt.QoS;
import com.boundlessgeo.spatialconnect.mqtt.SCNotification;
import com.boundlessgeo.spatialconnect.scutilities.Json.JsonUtilities;
import com.boundlessgeo.spatialconnect.scutilities.SCTuple;
import com.boundlessgeo.spatialconnect.services.authService.SCAuthService;
import com.boundlessgeo.spatialconnect.stores.ISyncableStore;
import com.boundlessgeo.spatialconnect.stores.SCDataStore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.protobuf.Timestamp;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subjects.BehaviorSubject;
import static com.boundlessgeo.spatialconnect.scutilities.Json.SCObjectMapper.getMapper;
import static java.util.Arrays.asList;
/**
* SCBackendService handles any communication with backend SpatialConnect services.
*/
public class SCBackendService extends SCService implements SCServiceLifecycle {
private static final String LOG_TAG = SCBackendService.class.getSimpleName();
private static final String SERVICE_NAME = "SC_BACKEND_SERVICE";
private Context context;
private MqttHandler mqttHandler;
private Observable<SCNotification> notifications;
private Observable<Boolean> syncStores;
private SCAuthService authService;
private SCConfigService configService;
private SCSensorService sensorService;
private SCDataService dataService;
private String deviceToken;
/**
* Behavior Observable emitting True when the SpatialConnect SCConfig has been received
*/
public BehaviorSubject<Boolean> configReceived = BehaviorSubject.create(false);
/**
* Behavior Observable emitting True when Connected, False when the Connection is down
*/
public BehaviorSubject<Boolean> connectedToBroker = BehaviorSubject.create(false);
/**
* Endpoint running SpatialConnect Server
*/
public String backendUri = null;
public SCBackendService(final Context context) {
this.context = context;
this.mqttHandler = MqttHandler.getInstance(context);
}
/**
* Initialize the backend service with a {@code SCRemoteConfig} to setup connections to the
* SpatialConnect backend including the REST API and the MQTT broker.
*
* @param config
*/
public void initialize(SCRemoteConfig config) {
if (backendUri == null) {
backendUri = String.format(
"%s://%s:%s",
config.getHttpProtocol() == null ? "http" : config.getHttpProtocol(),
config.getHttpHost() == null ? "localhost" : config.getHttpHost(),
config.getHttpPort() == null ? "8085" : config.getHttpPort().toString()
);
}
mqttHandler.initialize(config);
setupMqttConnectionListener();
}
/**
* Observable emiting SCNotifications
* @return Observable<{@link SCRemoteConfig}>
*/
public Observable<SCNotification> getNotifications() {
return notifications;
}
/**
* Publishes an SCMessage to the SpatialConnect Server
* @param topic topic MQTT destination topic
* @param message msg {@link MessagePbf.Msg} to be sent
*/
public void publish(String topic, MessagePbf.Msg message) {
MessagePbf.Msg.Builder msgBuilder = MessagePbf.Msg.newBuilder();
msgBuilder.setAction(message.getAction())
.setPayload(message.getPayload())
.setTo(message.getTo())
.setJwt(getJwt());
mqttHandler.publish(topic, msgBuilder.build(), QoS.EXACTLY_ONCE.value());
}
/**
* Publishes an SCMessage to the SpatialConnect Server with At Most Once Delivery QoS 0
* @param topic topic MQTT destination topic
* @param message msg {@link MessagePbf.Msg} to be sent
*/
public void publishAtMostOnce(String topic, MessagePbf.Msg message) {
MessagePbf.Msg.Builder msgBuilder = MessagePbf.Msg.newBuilder();
msgBuilder.setAction(message.getAction())
.setPayload(message.getPayload())
.setTo(message.getTo())
.setJwt(getJwt());
mqttHandler.publish(topic, msgBuilder.build(), QoS.AT_MOST_ONCE.value());
}
/**
* Publishes an SCMessage to the SpatialConnect Server with At Least Once Delivery QoS 1
* @param topic topic MQTT destination topic
* @param message msg {@link MessagePbf.Msg} to be sent
*/
public void publishAtLeastOnce(String topic, MessagePbf.Msg message) {
MessagePbf.Msg.Builder msgBuilder = MessagePbf.Msg.newBuilder();
msgBuilder.setAction(message.getAction())
.setPayload(message.getPayload())
.setTo(message.getTo())
.setJwt(getJwt());
mqttHandler.publish(topic, msgBuilder.build(), QoS.AT_LEAST_ONCE.value());
}
/**
* Publishes an SCMessage to the SpatialConnect Server with Exactly Once Delivery QoS 2
* @param topic topic MQTT destination topic
* @param message msg {@link MessagePbf.Msg} to be sent
*/
public void publishExactlyOnce(String topic, MessagePbf.Msg message) {
MessagePbf.Msg.Builder msgBuilder = MessagePbf.Msg.newBuilder();
msgBuilder.setAction(message.getAction())
.setPayload(message.getPayload())
.setTo(message.getTo())
.setJwt(getJwt());
mqttHandler.publish(topic, msgBuilder.build(), QoS.EXACTLY_ONCE.value());
}
/**
* Publishes a message with a reply-to observable returned for creating a request
* reply with the server.
*
* @param topic topic MQTT destination topic
* @param message msg {@link MessagePbf.Msg} to be sent
* @return Observable of the {@link MessagePbf.Msg} filtered by the correlation id
*/
public Observable<MessagePbf.Msg> publishReplyTo(
String topic,
final MessagePbf.Msg message) {
// set the correlation id and replyTo topic
long correlationId = System.currentTimeMillis();
final MessagePbf.Msg newMessage = MessagePbf.Msg.newBuilder()
.setAction(message.getAction())
.setPayload(message.getPayload())
.setTo(MqttHandler.REPLY_TO_TOPIC)
.setCorrelationId(correlationId)
.setJwt(getJwt())
.build();
mqttHandler.publish(topic, newMessage, QoS.EXACTLY_ONCE.value());
// filter message from reply to topic on the correlation id
return listenOnTopic(MqttHandler.REPLY_TO_TOPIC)
.filter(new Func1<MessagePbf.Msg, Boolean>() {
@Override
public Boolean call(MessagePbf.Msg incomingMessage) {
return incomingMessage.getCorrelationId() == newMessage.getCorrelationId();
}
})
.flatMap(new Func1<MessagePbf.Msg, Observable<MessagePbf.Msg>>() {
@Override
public Observable<MessagePbf.Msg> call(MessagePbf.Msg message) {
return Observable.just(message);
}
});
}
/**
* Subscribes to an MQTT Topic
*
* @param topic topic to listen on
* @return Observable of {@link MessagePbf.Msg}
* filtered to only receive messages from the stated topic
*/
public Observable<MessagePbf.Msg> listenOnTopic(final String topic) {
mqttHandler.subscribe(topic, QoS.EXACTLY_ONCE.value());
// filter messages for this topic
return mqttHandler.getMulticast()
.filter(new Func1<SCTuple, Boolean>() {
@Override
public Boolean call(SCTuple tuple) {
return tuple.first().toString().equalsIgnoreCase(topic);
}
})
.map(new Func1<SCTuple, MessagePbf.Msg>() {
@Override
public MessagePbf.Msg call(SCTuple scTuple) {
return (MessagePbf.Msg) scTuple.second();
}
});
}
public String getJwt() {
SCAuthService authService = SpatialConnect.getInstance().getAuthService();
String jwt = authService.getAccessToken();
return (jwt != null) ? authService.getAccessToken() : "";
}
public void reconnect() {
//re subscribe to mqtt topics
registerForLocalNotifications();
setupSubscriptions();
}
public void updateDeviceToken(final String token) {
Observable<Integer> authed = authService.getLoginStatus()
.filter(new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer integer) {
SCAuthService.SCAuthStatus status =
SCAuthService.SCAuthStatus.fromValue(integer);
return status == SCAuthService.SCAuthStatus.AUTHENTICATED;
}
}).take(1);
authed.subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
//wait on config received to ensure the initial device registration is done
configReceived
.filter(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean received) {
return received;
}
})
.take(1)
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
SpatialConnect sc = SpatialConnect.getInstance();
MessagePbf.Msg registerConfigMsg = MessagePbf.Msg.newBuilder()
.setAction(Actions.DEVICE_INFO.value())
.setPayload(
String.format("{\"identifier\": \"%s\", \"device_info\": %s, \"name\": \"mobile:%s\"}",
sc.getDeviceIdentifier(),
buildDeviceInfo(token),
authService.getUsername())
)
.build();
publishExactlyOnce("/device/info", registerConfigMsg);
}
});
}
});
}
@Override
public boolean start(Map<String, SCService> deps) {
authService = (SCAuthService)deps.get(SCAuthService.serviceId());
configService = (SCConfigService) deps.get(SCConfigService.serviceId());
sensorService = (SCSensorService) deps.get(SCSensorService.serviceId());
dataService = (SCDataService) deps.get(SCDataService.serviceId());
listenForNetworkConnection();
return super.start(deps);
}
@Override
public String getId() {
return SERVICE_NAME;
}
@Override
public List<String> getRequires() {
return asList(SCAuthService.serviceId(), SCConfigService.serviceId(),
SCSensorService.serviceId(), SCDataService.serviceId());
}
private void connectToMqttBroker() {
mqttHandler.connect();
connectedToBroker
.filter(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean connected) {
return connected;
}
})
.take(1)
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
setupSubscriptions();
registerAndFetchConfig();
listenForSyncEvents();
}
});
}
private void loadCachedConfig () {
SCConfig config = configService.getCachedConfig();
if (config != null) {
configService.loadConfig(config);
configReceived.onNext(true);
}
}
private void authListener() {
Log.d(LOG_TAG, "waiting for authentication before connecting to mqtt broker");
authService.getLoginStatus().subscribe(new Action1<Integer>() {
@Override
public void call(Integer status) {
if (status == SCAuthService.SCAuthStatus.AUTHENTICATED.value()) {
connectToMqttBroker();
}
if (status == SCAuthService.SCAuthStatus.AUTHENTICATION_FAILED.value()) {
loadCachedConfig();
}
}
});
}
private void listenForNetworkConnection() {
Log.d(LOG_TAG, "Subscribing to network connectivity updates.");
SCSensorService sensorService = SpatialConnect.getInstance().getSensorService();
sensorService.isConnected().subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean connected) {
if (connected) {
authListener();
} else {
//load config from cache
Log.d(LOG_TAG, "No internet get cached remote config");
connectedToBroker.onNext(false);
loadCachedConfig();
}
}
});
}
private void loadConfig(MessagePbf.Msg message) {
try {
SCConfig config = getMapper().readValue(
message.getPayload(),
SCConfig.class
);
Log.d(LOG_TAG, "Loading config received from mqtt broker");
configReceived.onNext(true);
SpatialConnect.getInstance().getConfigService().setCachedConfig(config);
SpatialConnect.getInstance().getConfigService().loadConfig(config);
}
catch (IOException e) {
e.printStackTrace();
}
}
private void registerAndFetchConfig() {
registerDevice();
fetchConfig();
}
private void fetchConfig() {
Log.d(LOG_TAG, "fetching config from mqtt config topic");
MessagePbf.Msg getConfigMsg = MessagePbf.Msg.newBuilder()
.setAction(Actions.CONFIG_FULL.value()).build();
publishReplyTo("/config", getConfigMsg)
.subscribe(new Action1<MessagePbf.Msg>() {
@Override
public void call(MessagePbf.Msg message) {
loadConfig(message);
}
});
}
private void registerDevice() {
SpatialConnect sc = SpatialConnect.getInstance();
MessagePbf.Msg registerConfigMsg = MessagePbf.Msg.newBuilder()
.setAction(Actions.CONFIG_REGISTER_DEVICE.value())
.setPayload(
String.format("{\"identifier\": \"%s\", \"device_info\": %s, \"name\": \"mobile:%s\"}",
sc.getDeviceIdentifier(),
buildDeviceInfo(),
authService.getUsername())
)
.build();
publishExactlyOnce("/config/register", registerConfigMsg);
}
private void setupSubscriptions() {
notifications = listenOnTopic("/notify")
.mergeWith(listenOnTopic(String.format("/notify/%s", SpatialConnect.getInstance().getDeviceIdentifier())))
.map(new Func1<MessagePbf.Msg, SCNotification>() {
@Override
public SCNotification call(MessagePbf.Msg msg) {
return new SCNotification(msg);
}
});
listenOnTopic("/config/update").subscribe(new Action1<MessagePbf.Msg>() {
@Override
public void call(MessagePbf.Msg msg) {
Log.d("FormStore","action: " + msg.getAction());
SCConfig cachedConfig = configService.getCachedConfig();
JsonUtilities utilities = new JsonUtilities();
switch (Actions.fromAction(msg.getAction())) {
case CONFIG_ADD_STORE:
try {
SCStoreConfig config = getMapper()
.readValue(msg.getPayload(), SCStoreConfig.class);
cachedConfig.addStore(config);
dataService.registerAndStartStoreByConfig(config);
} catch (IOException e) {
e.printStackTrace();
}
break;
case CONFIG_UPDATE_STORE:
try {
SCStoreConfig config = getMapper()
.readValue(msg.getPayload(), SCStoreConfig.class);
cachedConfig.updateStore(config);
dataService.updateStoresByConfig(config);
} catch (IOException e) {
e.printStackTrace();
}
break;
case CONFIG_REMOVE_STORE:
String storeId = utilities.getMapFromJson(msg.getPayload())
.get("id").toString();
SCDataStore store = dataService.getStoreByIdentifier(storeId);
cachedConfig.removeStore(storeId);
dataService.unregisterStore(store);
break;
case CONFIG_ADD_FORM:
try {
SCFormConfig config = getMapper()
.readValue(msg.getPayload(), SCFormConfig.class);
cachedConfig.addForm(config);
dataService.getFormStore().registerFormByConfig(config);
} catch (IOException e) {
e.printStackTrace();
}
break;
case CONFIG_UPDATE_FORM:
try {
SCFormConfig config = getMapper()
.readValue(msg.getPayload(), SCFormConfig.class);
cachedConfig.updateForm(config);
dataService.getFormStore().updateFormByConfig(config);
} catch (IOException e) {
e.printStackTrace();
}
break;
case CONFIG_REMOVE_FORM:
String formKey = utilities.getMapFromJson(msg.getPayload())
.get("form_key").toString();
cachedConfig.removeForm(formKey);
dataService.getFormStore().unregisterFormByKey(formKey);
break;
}
configService.setCachedConfig(cachedConfig);
}
});
}
private void registerForLocalNotifications() {
notifications = listenOnTopic("/notify")
.mergeWith(listenOnTopic(String.format("/notify/%s", SpatialConnect.getInstance().getDeviceIdentifier())))
.map(new Func1<MessagePbf.Msg, SCNotification>() {
@Override
public SCNotification call(MessagePbf.Msg msg) {
return new SCNotification(msg);
}
});
}
private void setupMqttConnectionListener() {
Log.d(LOG_TAG, "setting up mqtt connection listener");
MqttHandler.clientConnected.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean clientConnected) {
connectedToBroker.onNext(clientConnected);
}
});
}
private Timestamp getTimestamp() {
long millis = System.currentTimeMillis();
return Timestamp.newBuilder()
.setSeconds(millis / 1000)
.setNanos((int) ((millis % 1000) * 1000000))
.build();
}
private String buildDeviceInfo() {
return buildDeviceInfo("");
}
private String buildDeviceInfo(String token) {
String release = Build.VERSION.RELEASE;
int sdkVersion = Build.VERSION.SDK_INT;
String os = String.format("Android SDK: %s (%s)", sdkVersion, release);
return String.format("{\"os\": \"%s\", \"token\": \"%s\"}", os, token);
}
private void listenForSyncEvents() {
Observable<SCDataStore> syncableStores = dataService.getISyncableStores();
Observable<Boolean> storeEditSync = syncableStores
.flatMap(new Func1<SCDataStore, Observable<SCSpatialFeature>>() {
@Override
public Observable<SCSpatialFeature> call(SCDataStore scDataStore) {
return scDataStore.storeEdited;
}
}).map(new Func1<SCSpatialFeature, Boolean>() {
@Override
public Boolean call(SCSpatialFeature feature) {
final ISyncableStore store = (ISyncableStore) dataService.getStoreByIdentifier(feature.getStoreId());
syncStore(store);
return null;
}
});
//sync all stores when connection to broker is true
Observable<Boolean> onlineSync = connectedToBroker
.filter(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean sync) {
return sync;
}
}).map(new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean sync) {
syncStores();
return sync;
}
});
Observable<Boolean> sync = onlineSync.mergeWith(storeEditSync);
sync.subscribeOn(Schedulers.newThread()).subscribe();
}
private void syncStores() {
dataService.getISyncableStores()
.subscribe(new Action1<SCDataStore>() {
@Override
public void call(SCDataStore scDataStore) {
syncStore((ISyncableStore) scDataStore);
}
});
}
private void syncStore(final ISyncableStore store) {
Log.d(LOG_TAG, "Syncing store channel " + store.syncChannel());
store.unSent().subscribe(new Action1<SCSpatialFeature>() {
@Override
public void call(final SCSpatialFeature scSpatialFeature) {
send(scSpatialFeature);
}
});
}
private void send(final SCSpatialFeature feature) {
connectedToBroker
.filter(new Func1<Boolean, Boolean>() {
@Override public Boolean call(Boolean connected) {
return connected;
}
})
.subscribe(new Action1<Boolean>() {
@Override public void call(Boolean connected) {
Log.d(LOG_TAG, "Sending feature to mqtt broker " + feature.toJson());
final ISyncableStore store =
(ISyncableStore) dataService.getStoreByIdentifier(feature.getStoreId());
Map<String, Object> featurePayload = store.generateSendPayload(feature);
String payload;
try {
payload = getMapper().writeValueAsString(featurePayload);
MessagePbf.Msg message = MessagePbf.Msg.newBuilder()
.setAction(Actions.DATASERVICE_CREATEFEATURE.value())
.setPayload(payload)
.build();
publishReplyTo(store.syncChannel(), message)
.subscribe(new Action1<MessagePbf.Msg>() {
@Override public void call(MessagePbf.Msg message) {
try {
final JSONObject payload = new JSONObject(message.getPayload());
if (payload.getBoolean("result")) {
Log.d(LOG_TAG, "update audit table to remove sent feature");
store.updateAuditTable(feature);
} else {
Log.e(LOG_TAG,
"Something went wrong sending to server: " + payload
.getString("error"));
}
} catch (JSONException je) {
Log.e(LOG_TAG, "json parse error: " + je.getMessage());
}
}
});
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
});
}
public static String serviceId() {
return SERVICE_NAME;
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-compute/alpha/1.31.0/com/google/api/services/compute/model/BackendService.java | 57061 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.compute.model;
/**
* Represents a Backend Service resource. A backend service defines how Google Cloud load balancers
* distribute traffic. The backend service configuration contains a set of values, such as the
* protocol used to connect to backends, various distribution and session settings, health checks,
* and timeouts. These settings provide fine-grained control over how your load balancer behaves.
* Most of the settings have default values that allow for easy configuration if you need to get
* started quickly. Backend services in Google Compute Engine can be either regionally or globally
* scoped. * [Global](https://cloud.google.com/compute/docs/reference/rest/alpha/backendServices) *
* [Regional](https://cloud.google.com/compute/docs/reference/rest/alpha/regionBackendServices) For
* more information, see Backend Services.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class BackendService extends com.google.api.client.json.GenericJson {
/**
* Lifetime of cookies in seconds. This setting is applicable to external and internal HTTP(S)
* load balancers and Traffic Director and requires GENERATED_COOKIE or HTTP_COOKIE session
* affinity. If set to 0, the cookie is non-persistent and lasts only until the end of the browser
* session (or equivalent). The maximum allowed value is one day (86,400). Not supported when the
* backend service is referenced by a URL map that is bound to target gRPC proxy that has
* validateForProxyless field set to true.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer affinityCookieTtlSec;
/**
* The list of backends that serve this BackendService.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Backend> backends;
static {
// hack to force ProGuard to consider Backend used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(Backend.class);
}
/**
* Cloud CDN configuration for this BackendService. Only available for specified load balancer
* types.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BackendServiceCdnPolicy cdnPolicy;
/**
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CircuitBreakers circuitBreakers;
/**
* Compress text responses using Brotli or gzip compression, based on the client's Accept-Encoding
* header.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String compressionMode;
/**
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ConnectionDraining connectionDraining;
/**
* Connection Tracking configuration for this BackendService. Connection tracking policy settings
* are only available for Network Load Balancing and Internal TCP/UDP Load Balancing.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BackendServiceConnectionTrackingPolicy connectionTrackingPolicy;
/**
* Consistent Hash-based load balancing can be used to provide soft session affinity based on HTTP
* headers, cookies or other properties. This load balancing policy is applicable only for HTTP
* connections. The affinity to a particular destination host will be lost when one or more hosts
* are added/removed from the destination service. This field specifies parameters that control
* consistent hashing. This field is only applicable when localityLbPolicy is set to MAGLEV or
* RING_HASH. This field is applicable to either: - A regional backend service with the
* service_protocol set to HTTP, HTTPS, or HTTP2, and load_balancing_scheme set to
* INTERNAL_MANAGED. - A global backend service with the load_balancing_scheme set to
* INTERNAL_SELF_MANAGED.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private ConsistentHashLoadBalancerSettings consistentHash;
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String creationTimestamp;
/**
* Headers that the load balancer adds to proxied requests. See [Creating custom
* headers](https://cloud.google.com/load-balancing/docs/custom-headers).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> customRequestHeaders;
/**
* Headers that the load balancer adds to proxied responses. See [Creating custom
* headers](https://cloud.google.com/load-balancing/docs/custom-headers).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> customResponseHeaders;
/**
* An optional description of this resource. Provide this property when you create the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* [Output Only] The resource URL for the edge security policy associated with this backend
* service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String edgeSecurityPolicy;
/**
* If true, enables Cloud CDN for the backend service of an external HTTP(S) load balancer.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Boolean enableCDN;
/**
* Requires at least one backend instance group to be defined as a backup (failover) backend. For
* load balancers that have configurable failover: [Internal TCP/UDP Load
* Balancing](https://cloud.google.com/load-balancing/docs/internal/failover-overview) and
* [external TCP/UDP Load Balancing](https://cloud.google.com/load-balancing/docs/network
* /networklb-failover-overview).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BackendServiceFailoverPolicy failoverPolicy;
/**
* Fingerprint of this resource. A hash of the contents stored in this object. This field is used
* in optimistic locking. This field will be ignored when inserting a BackendService. An up-to-
* date fingerprint must be provided in order to update the BackendService, otherwise the request
* will fail with error 412 conditionNotMet. To see the latest fingerprint, make a get() request
* to retrieve a BackendService.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String fingerprint;
/**
* The list of URLs to the healthChecks, httpHealthChecks (legacy), or httpsHealthChecks (legacy)
* resource for health checking this backend service. Not all backend services support legacy
* health checks. See Load balancer guide. Currently, at most one health check can be specified
* for each backend service. Backend services with instance group or zonal NEG backends must have
* a health check. Backend services with internet or serverless NEG backends must not have a
* health check.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> healthChecks;
/**
* The configurations for Identity-Aware Proxy on this resource. Not available for Internal
* TCP/UDP Load Balancing and Network Load Balancing.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BackendServiceIAP iap;
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.math.BigInteger id;
/**
* [Output Only] Type of resource. Always compute#backendService for backend services.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String kind;
/**
* Specifies the load balancer type. A backend service created for one type of load balancer
* cannot be used with another. For more information, refer to Choosing a load balancer.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String loadBalancingScheme;
/**
* The load balancing algorithm used within the scope of the locality. The possible values are: -
* ROUND_ROBIN: This is a simple policy in which each healthy backend is selected in round robin
* order. This is the default. - LEAST_REQUEST: An O(1) algorithm which selects two random healthy
* hosts and picks the host which has fewer active requests. - RING_HASH: The ring/modulo hash
* load balancer implements consistent hashing to backends. The algorithm has the property that
* the addition/removal of a host from a set of N hosts only affects 1/N of the requests. -
* RANDOM: The load balancer selects a random healthy host. - ORIGINAL_DESTINATION: Backend host
* is selected based on the client connection metadata, i.e., connections are opened to the same
* address as the destination address of the incoming connection before the connection was
* redirected to the load balancer. - MAGLEV: used as a drop in replacement for the ring hash load
* balancer. Maglev is not as stable as ring hash but has faster table lookup build times and host
* selection times. For more information about Maglev, see
* https://ai.google/research/pubs/pub44824 This field is applicable to either: - A regional
* backend service with the service_protocol set to HTTP, HTTPS, or HTTP2, and
* load_balancing_scheme set to INTERNAL_MANAGED. - A global backend service with the
* load_balancing_scheme set to INTERNAL_SELF_MANAGED. If sessionAffinity is not NONE, and this
* field is not set to MAGLEV or RING_HASH, session affinity settings will not take effect. Only
* ROUND_ROBIN and RING_HASH are supported when the backend service is referenced by a URL map
* that is bound to target gRPC proxy that has validateForProxyless field set to true.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String localityLbPolicy;
/**
* This field denotes the logging options for the load balancer traffic served by this backend
* service. If logging is enabled, logs will be exported to Stackdriver.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private BackendServiceLogConfig logConfig;
/**
* Specifies the default maximum duration (timeout) for streams to this service. Duration is
* computed from the beginning of the stream until the response has been completely processed,
* including all retries. A stream that does not complete in this duration is closed. If not
* specified, there will be no timeout limit, i.e. the maximum duration is infinite. This value
* can be overridden in the PathMatcher configuration of the UrlMap that references this backend
* service. This field is only allowed when the loadBalancingScheme of the backend service is
* INTERNAL_SELF_MANAGED.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Duration maxStreamDuration;
/**
* Name of the resource. Provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The URL of the network to which this backend service belongs. This field can only be specified
* when the load balancing scheme is set to INTERNAL.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String network;
/**
* Settings controlling the eviction of unhealthy hosts from the load balancing pool for the
* backend service. If not set, this feature is considered disabled. This field is applicable to
* either: - A regional backend service with the service_protocol set to HTTP, HTTPS, or HTTP2,
* and load_balancing_scheme set to INTERNAL_MANAGED. - A global backend service with the
* load_balancing_scheme set to INTERNAL_SELF_MANAGED. Not supported when the backend service is
* referenced by a URL map that is bound to target gRPC proxy that has validateForProxyless field
* set to true.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private OutlierDetection outlierDetection;
/**
* Deprecated in favor of portName. The TCP port to connect on the backend. The default value is
* 80. For Internal TCP/UDP Load Balancing and Network Load Balancing, omit port.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer port;
/**
* A named port on a backend instance group representing the port for communication to the backend
* VMs in that group. The named port must be [defined on each backend instance
* group](https://cloud.google.com/load-balancing/docs/backend-service#named_ports). This
* parameter has no meaning if the backends are NEGs. For Internal TCP/UDP Load Balancing and
* Network Load Balancing, omit port_name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String portName;
/**
* The protocol this BackendService uses to communicate with backends. Possible values are HTTP,
* HTTPS, HTTP2, TCP, SSL, UDP or GRPC. depending on the chosen load balancer or Traffic Director
* configuration. Refer to the documentation for the load balancers or for Traffic Director for
* more information. Must be set to GRPC when the backend service is referenced by a URL map that
* is bound to target gRPC proxy.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String protocol;
/**
* [Output Only] URL of the region where the regional backend service resides. This field is not
* applicable to global backend services. You must specify this field as part of the HTTP request
* URL. It is not settable as a field in the request body.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String region;
/**
* [Output Only] The resource URL for the security policy associated with this backend service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String securityPolicy;
/**
* This field specifies the security settings that apply to this backend service. This field is
* applicable to a global backend service with the load_balancing_scheme set to
* INTERNAL_SELF_MANAGED.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private SecuritySettings securitySettings;
/**
* [Output Only] Server-defined URL for the resource.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String selfLink;
/**
* [Output Only] Server-defined URL for this resource with the resource id.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String selfLinkWithId;
/**
* URLs of networkservices.ServiceBinding resources. Can only be set if load balancing scheme is
* INTERNAL_SELF_MANAGED. If set, lists of backends and health checks must be both empty.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> serviceBindings;
/**
* URL to networkservices.ServiceLbPolicy resource. Can only be set if load balancing scheme is
* EXTERNAL, INTERNAL_MANAGED or INTERNAL_SELF_MANAGED. If used with a backend service, must
* reference a global policy. If used with a regional backend service, must reference a regional
* policy.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String serviceLbPolicy;
/**
* Type of session affinity to use. The default is NONE. Only NONE and HEADER_FIELD are supported
* when the backend service is referenced by a URL map that is bound to target gRPC proxy that has
* validateForProxyless field set to true. For more details, see: [Session
* Affinity](https://cloud.google.com/load-balancing/docs/backend-service#session_affinity).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String sessionAffinity;
/**
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Subsetting subsetting;
/**
* The backend service timeout has a different meaning depending on the type of load balancer. For
* more information see, Backend service settings The default is 30 seconds. The full range of
* timeout values allowed is 1 - 2,147,483,647 seconds. This value can be overridden in the
* PathMatcher configuration of the UrlMap that references this backend service. Not supported
* when the backend service is referenced by a URL map that is bound to target gRPC proxy that has
* validateForProxyless field set to true. Instead, use maxStreamDuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer timeoutSec;
/**
* Lifetime of cookies in seconds. This setting is applicable to external and internal HTTP(S)
* load balancers and Traffic Director and requires GENERATED_COOKIE or HTTP_COOKIE session
* affinity. If set to 0, the cookie is non-persistent and lasts only until the end of the browser
* session (or equivalent). The maximum allowed value is one day (86,400). Not supported when the
* backend service is referenced by a URL map that is bound to target gRPC proxy that has
* validateForProxyless field set to true.
* @return value or {@code null} for none
*/
public java.lang.Integer getAffinityCookieTtlSec() {
return affinityCookieTtlSec;
}
/**
* Lifetime of cookies in seconds. This setting is applicable to external and internal HTTP(S)
* load balancers and Traffic Director and requires GENERATED_COOKIE or HTTP_COOKIE session
* affinity. If set to 0, the cookie is non-persistent and lasts only until the end of the browser
* session (or equivalent). The maximum allowed value is one day (86,400). Not supported when the
* backend service is referenced by a URL map that is bound to target gRPC proxy that has
* validateForProxyless field set to true.
* @param affinityCookieTtlSec affinityCookieTtlSec or {@code null} for none
*/
public BackendService setAffinityCookieTtlSec(java.lang.Integer affinityCookieTtlSec) {
this.affinityCookieTtlSec = affinityCookieTtlSec;
return this;
}
/**
* The list of backends that serve this BackendService.
* @return value or {@code null} for none
*/
public java.util.List<Backend> getBackends() {
return backends;
}
/**
* The list of backends that serve this BackendService.
* @param backends backends or {@code null} for none
*/
public BackendService setBackends(java.util.List<Backend> backends) {
this.backends = backends;
return this;
}
/**
* Cloud CDN configuration for this BackendService. Only available for specified load balancer
* types.
* @return value or {@code null} for none
*/
public BackendServiceCdnPolicy getCdnPolicy() {
return cdnPolicy;
}
/**
* Cloud CDN configuration for this BackendService. Only available for specified load balancer
* types.
* @param cdnPolicy cdnPolicy or {@code null} for none
*/
public BackendService setCdnPolicy(BackendServiceCdnPolicy cdnPolicy) {
this.cdnPolicy = cdnPolicy;
return this;
}
/**
* @return value or {@code null} for none
*/
public CircuitBreakers getCircuitBreakers() {
return circuitBreakers;
}
/**
* @param circuitBreakers circuitBreakers or {@code null} for none
*/
public BackendService setCircuitBreakers(CircuitBreakers circuitBreakers) {
this.circuitBreakers = circuitBreakers;
return this;
}
/**
* Compress text responses using Brotli or gzip compression, based on the client's Accept-Encoding
* header.
* @return value or {@code null} for none
*/
public java.lang.String getCompressionMode() {
return compressionMode;
}
/**
* Compress text responses using Brotli or gzip compression, based on the client's Accept-Encoding
* header.
* @param compressionMode compressionMode or {@code null} for none
*/
public BackendService setCompressionMode(java.lang.String compressionMode) {
this.compressionMode = compressionMode;
return this;
}
/**
* @return value or {@code null} for none
*/
public ConnectionDraining getConnectionDraining() {
return connectionDraining;
}
/**
* @param connectionDraining connectionDraining or {@code null} for none
*/
public BackendService setConnectionDraining(ConnectionDraining connectionDraining) {
this.connectionDraining = connectionDraining;
return this;
}
/**
* Connection Tracking configuration for this BackendService. Connection tracking policy settings
* are only available for Network Load Balancing and Internal TCP/UDP Load Balancing.
* @return value or {@code null} for none
*/
public BackendServiceConnectionTrackingPolicy getConnectionTrackingPolicy() {
return connectionTrackingPolicy;
}
/**
* Connection Tracking configuration for this BackendService. Connection tracking policy settings
* are only available for Network Load Balancing and Internal TCP/UDP Load Balancing.
* @param connectionTrackingPolicy connectionTrackingPolicy or {@code null} for none
*/
public BackendService setConnectionTrackingPolicy(BackendServiceConnectionTrackingPolicy connectionTrackingPolicy) {
this.connectionTrackingPolicy = connectionTrackingPolicy;
return this;
}
/**
* Consistent Hash-based load balancing can be used to provide soft session affinity based on HTTP
* headers, cookies or other properties. This load balancing policy is applicable only for HTTP
* connections. The affinity to a particular destination host will be lost when one or more hosts
* are added/removed from the destination service. This field specifies parameters that control
* consistent hashing. This field is only applicable when localityLbPolicy is set to MAGLEV or
* RING_HASH. This field is applicable to either: - A regional backend service with the
* service_protocol set to HTTP, HTTPS, or HTTP2, and load_balancing_scheme set to
* INTERNAL_MANAGED. - A global backend service with the load_balancing_scheme set to
* INTERNAL_SELF_MANAGED.
* @return value or {@code null} for none
*/
public ConsistentHashLoadBalancerSettings getConsistentHash() {
return consistentHash;
}
/**
* Consistent Hash-based load balancing can be used to provide soft session affinity based on HTTP
* headers, cookies or other properties. This load balancing policy is applicable only for HTTP
* connections. The affinity to a particular destination host will be lost when one or more hosts
* are added/removed from the destination service. This field specifies parameters that control
* consistent hashing. This field is only applicable when localityLbPolicy is set to MAGLEV or
* RING_HASH. This field is applicable to either: - A regional backend service with the
* service_protocol set to HTTP, HTTPS, or HTTP2, and load_balancing_scheme set to
* INTERNAL_MANAGED. - A global backend service with the load_balancing_scheme set to
* INTERNAL_SELF_MANAGED.
* @param consistentHash consistentHash or {@code null} for none
*/
public BackendService setConsistentHash(ConsistentHashLoadBalancerSettings consistentHash) {
this.consistentHash = consistentHash;
return this;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @return value or {@code null} for none
*/
public java.lang.String getCreationTimestamp() {
return creationTimestamp;
}
/**
* [Output Only] Creation timestamp in RFC3339 text format.
* @param creationTimestamp creationTimestamp or {@code null} for none
*/
public BackendService setCreationTimestamp(java.lang.String creationTimestamp) {
this.creationTimestamp = creationTimestamp;
return this;
}
/**
* Headers that the load balancer adds to proxied requests. See [Creating custom
* headers](https://cloud.google.com/load-balancing/docs/custom-headers).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getCustomRequestHeaders() {
return customRequestHeaders;
}
/**
* Headers that the load balancer adds to proxied requests. See [Creating custom
* headers](https://cloud.google.com/load-balancing/docs/custom-headers).
* @param customRequestHeaders customRequestHeaders or {@code null} for none
*/
public BackendService setCustomRequestHeaders(java.util.List<java.lang.String> customRequestHeaders) {
this.customRequestHeaders = customRequestHeaders;
return this;
}
/**
* Headers that the load balancer adds to proxied responses. See [Creating custom
* headers](https://cloud.google.com/load-balancing/docs/custom-headers).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getCustomResponseHeaders() {
return customResponseHeaders;
}
/**
* Headers that the load balancer adds to proxied responses. See [Creating custom
* headers](https://cloud.google.com/load-balancing/docs/custom-headers).
* @param customResponseHeaders customResponseHeaders or {@code null} for none
*/
public BackendService setCustomResponseHeaders(java.util.List<java.lang.String> customResponseHeaders) {
this.customResponseHeaders = customResponseHeaders;
return this;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* An optional description of this resource. Provide this property when you create the resource.
* @param description description or {@code null} for none
*/
public BackendService setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* [Output Only] The resource URL for the edge security policy associated with this backend
* service.
* @return value or {@code null} for none
*/
public java.lang.String getEdgeSecurityPolicy() {
return edgeSecurityPolicy;
}
/**
* [Output Only] The resource URL for the edge security policy associated with this backend
* service.
* @param edgeSecurityPolicy edgeSecurityPolicy or {@code null} for none
*/
public BackendService setEdgeSecurityPolicy(java.lang.String edgeSecurityPolicy) {
this.edgeSecurityPolicy = edgeSecurityPolicy;
return this;
}
/**
* If true, enables Cloud CDN for the backend service of an external HTTP(S) load balancer.
* @return value or {@code null} for none
*/
public java.lang.Boolean getEnableCDN() {
return enableCDN;
}
/**
* If true, enables Cloud CDN for the backend service of an external HTTP(S) load balancer.
* @param enableCDN enableCDN or {@code null} for none
*/
public BackendService setEnableCDN(java.lang.Boolean enableCDN) {
this.enableCDN = enableCDN;
return this;
}
/**
* Requires at least one backend instance group to be defined as a backup (failover) backend. For
* load balancers that have configurable failover: [Internal TCP/UDP Load
* Balancing](https://cloud.google.com/load-balancing/docs/internal/failover-overview) and
* [external TCP/UDP Load Balancing](https://cloud.google.com/load-balancing/docs/network
* /networklb-failover-overview).
* @return value or {@code null} for none
*/
public BackendServiceFailoverPolicy getFailoverPolicy() {
return failoverPolicy;
}
/**
* Requires at least one backend instance group to be defined as a backup (failover) backend. For
* load balancers that have configurable failover: [Internal TCP/UDP Load
* Balancing](https://cloud.google.com/load-balancing/docs/internal/failover-overview) and
* [external TCP/UDP Load Balancing](https://cloud.google.com/load-balancing/docs/network
* /networklb-failover-overview).
* @param failoverPolicy failoverPolicy or {@code null} for none
*/
public BackendService setFailoverPolicy(BackendServiceFailoverPolicy failoverPolicy) {
this.failoverPolicy = failoverPolicy;
return this;
}
/**
* Fingerprint of this resource. A hash of the contents stored in this object. This field is used
* in optimistic locking. This field will be ignored when inserting a BackendService. An up-to-
* date fingerprint must be provided in order to update the BackendService, otherwise the request
* will fail with error 412 conditionNotMet. To see the latest fingerprint, make a get() request
* to retrieve a BackendService.
* @see #decodeFingerprint()
* @return value or {@code null} for none
*/
public java.lang.String getFingerprint() {
return fingerprint;
}
/**
* Fingerprint of this resource. A hash of the contents stored in this object. This field is used
* in optimistic locking. This field will be ignored when inserting a BackendService. An up-to-
* date fingerprint must be provided in order to update the BackendService, otherwise the request
* will fail with error 412 conditionNotMet. To see the latest fingerprint, make a get() request
* to retrieve a BackendService.
* @see #getFingerprint()
* @return Base64 decoded value or {@code null} for none
*
* @since 1.14
*/
public byte[] decodeFingerprint() {
return com.google.api.client.util.Base64.decodeBase64(fingerprint);
}
/**
* Fingerprint of this resource. A hash of the contents stored in this object. This field is used
* in optimistic locking. This field will be ignored when inserting a BackendService. An up-to-
* date fingerprint must be provided in order to update the BackendService, otherwise the request
* will fail with error 412 conditionNotMet. To see the latest fingerprint, make a get() request
* to retrieve a BackendService.
* @see #encodeFingerprint()
* @param fingerprint fingerprint or {@code null} for none
*/
public BackendService setFingerprint(java.lang.String fingerprint) {
this.fingerprint = fingerprint;
return this;
}
/**
* Fingerprint of this resource. A hash of the contents stored in this object. This field is used
* in optimistic locking. This field will be ignored when inserting a BackendService. An up-to-
* date fingerprint must be provided in order to update the BackendService, otherwise the request
* will fail with error 412 conditionNotMet. To see the latest fingerprint, make a get() request
* to retrieve a BackendService.
* @see #setFingerprint()
*
* <p>
* The value is encoded Base64 or {@code null} for none.
* </p>
*
* @since 1.14
*/
public BackendService encodeFingerprint(byte[] fingerprint) {
this.fingerprint = com.google.api.client.util.Base64.encodeBase64URLSafeString(fingerprint);
return this;
}
/**
* The list of URLs to the healthChecks, httpHealthChecks (legacy), or httpsHealthChecks (legacy)
* resource for health checking this backend service. Not all backend services support legacy
* health checks. See Load balancer guide. Currently, at most one health check can be specified
* for each backend service. Backend services with instance group or zonal NEG backends must have
* a health check. Backend services with internet or serverless NEG backends must not have a
* health check.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getHealthChecks() {
return healthChecks;
}
/**
* The list of URLs to the healthChecks, httpHealthChecks (legacy), or httpsHealthChecks (legacy)
* resource for health checking this backend service. Not all backend services support legacy
* health checks. See Load balancer guide. Currently, at most one health check can be specified
* for each backend service. Backend services with instance group or zonal NEG backends must have
* a health check. Backend services with internet or serverless NEG backends must not have a
* health check.
* @param healthChecks healthChecks or {@code null} for none
*/
public BackendService setHealthChecks(java.util.List<java.lang.String> healthChecks) {
this.healthChecks = healthChecks;
return this;
}
/**
* The configurations for Identity-Aware Proxy on this resource. Not available for Internal
* TCP/UDP Load Balancing and Network Load Balancing.
* @return value or {@code null} for none
*/
public BackendServiceIAP getIap() {
return iap;
}
/**
* The configurations for Identity-Aware Proxy on this resource. Not available for Internal
* TCP/UDP Load Balancing and Network Load Balancing.
* @param iap iap or {@code null} for none
*/
public BackendService setIap(BackendServiceIAP iap) {
this.iap = iap;
return this;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @return value or {@code null} for none
*/
public java.math.BigInteger getId() {
return id;
}
/**
* [Output Only] The unique identifier for the resource. This identifier is defined by the server.
* @param id id or {@code null} for none
*/
public BackendService setId(java.math.BigInteger id) {
this.id = id;
return this;
}
/**
* [Output Only] Type of resource. Always compute#backendService for backend services.
* @return value or {@code null} for none
*/
public java.lang.String getKind() {
return kind;
}
/**
* [Output Only] Type of resource. Always compute#backendService for backend services.
* @param kind kind or {@code null} for none
*/
public BackendService setKind(java.lang.String kind) {
this.kind = kind;
return this;
}
/**
* Specifies the load balancer type. A backend service created for one type of load balancer
* cannot be used with another. For more information, refer to Choosing a load balancer.
* @return value or {@code null} for none
*/
public java.lang.String getLoadBalancingScheme() {
return loadBalancingScheme;
}
/**
* Specifies the load balancer type. A backend service created for one type of load balancer
* cannot be used with another. For more information, refer to Choosing a load balancer.
* @param loadBalancingScheme loadBalancingScheme or {@code null} for none
*/
public BackendService setLoadBalancingScheme(java.lang.String loadBalancingScheme) {
this.loadBalancingScheme = loadBalancingScheme;
return this;
}
/**
* The load balancing algorithm used within the scope of the locality. The possible values are: -
* ROUND_ROBIN: This is a simple policy in which each healthy backend is selected in round robin
* order. This is the default. - LEAST_REQUEST: An O(1) algorithm which selects two random healthy
* hosts and picks the host which has fewer active requests. - RING_HASH: The ring/modulo hash
* load balancer implements consistent hashing to backends. The algorithm has the property that
* the addition/removal of a host from a set of N hosts only affects 1/N of the requests. -
* RANDOM: The load balancer selects a random healthy host. - ORIGINAL_DESTINATION: Backend host
* is selected based on the client connection metadata, i.e., connections are opened to the same
* address as the destination address of the incoming connection before the connection was
* redirected to the load balancer. - MAGLEV: used as a drop in replacement for the ring hash load
* balancer. Maglev is not as stable as ring hash but has faster table lookup build times and host
* selection times. For more information about Maglev, see
* https://ai.google/research/pubs/pub44824 This field is applicable to either: - A regional
* backend service with the service_protocol set to HTTP, HTTPS, or HTTP2, and
* load_balancing_scheme set to INTERNAL_MANAGED. - A global backend service with the
* load_balancing_scheme set to INTERNAL_SELF_MANAGED. If sessionAffinity is not NONE, and this
* field is not set to MAGLEV or RING_HASH, session affinity settings will not take effect. Only
* ROUND_ROBIN and RING_HASH are supported when the backend service is referenced by a URL map
* that is bound to target gRPC proxy that has validateForProxyless field set to true.
* @return value or {@code null} for none
*/
public java.lang.String getLocalityLbPolicy() {
return localityLbPolicy;
}
/**
* The load balancing algorithm used within the scope of the locality. The possible values are: -
* ROUND_ROBIN: This is a simple policy in which each healthy backend is selected in round robin
* order. This is the default. - LEAST_REQUEST: An O(1) algorithm which selects two random healthy
* hosts and picks the host which has fewer active requests. - RING_HASH: The ring/modulo hash
* load balancer implements consistent hashing to backends. The algorithm has the property that
* the addition/removal of a host from a set of N hosts only affects 1/N of the requests. -
* RANDOM: The load balancer selects a random healthy host. - ORIGINAL_DESTINATION: Backend host
* is selected based on the client connection metadata, i.e., connections are opened to the same
* address as the destination address of the incoming connection before the connection was
* redirected to the load balancer. - MAGLEV: used as a drop in replacement for the ring hash load
* balancer. Maglev is not as stable as ring hash but has faster table lookup build times and host
* selection times. For more information about Maglev, see
* https://ai.google/research/pubs/pub44824 This field is applicable to either: - A regional
* backend service with the service_protocol set to HTTP, HTTPS, or HTTP2, and
* load_balancing_scheme set to INTERNAL_MANAGED. - A global backend service with the
* load_balancing_scheme set to INTERNAL_SELF_MANAGED. If sessionAffinity is not NONE, and this
* field is not set to MAGLEV or RING_HASH, session affinity settings will not take effect. Only
* ROUND_ROBIN and RING_HASH are supported when the backend service is referenced by a URL map
* that is bound to target gRPC proxy that has validateForProxyless field set to true.
* @param localityLbPolicy localityLbPolicy or {@code null} for none
*/
public BackendService setLocalityLbPolicy(java.lang.String localityLbPolicy) {
this.localityLbPolicy = localityLbPolicy;
return this;
}
/**
* This field denotes the logging options for the load balancer traffic served by this backend
* service. If logging is enabled, logs will be exported to Stackdriver.
* @return value or {@code null} for none
*/
public BackendServiceLogConfig getLogConfig() {
return logConfig;
}
/**
* This field denotes the logging options for the load balancer traffic served by this backend
* service. If logging is enabled, logs will be exported to Stackdriver.
* @param logConfig logConfig or {@code null} for none
*/
public BackendService setLogConfig(BackendServiceLogConfig logConfig) {
this.logConfig = logConfig;
return this;
}
/**
* Specifies the default maximum duration (timeout) for streams to this service. Duration is
* computed from the beginning of the stream until the response has been completely processed,
* including all retries. A stream that does not complete in this duration is closed. If not
* specified, there will be no timeout limit, i.e. the maximum duration is infinite. This value
* can be overridden in the PathMatcher configuration of the UrlMap that references this backend
* service. This field is only allowed when the loadBalancingScheme of the backend service is
* INTERNAL_SELF_MANAGED.
* @return value or {@code null} for none
*/
public Duration getMaxStreamDuration() {
return maxStreamDuration;
}
/**
* Specifies the default maximum duration (timeout) for streams to this service. Duration is
* computed from the beginning of the stream until the response has been completely processed,
* including all retries. A stream that does not complete in this duration is closed. If not
* specified, there will be no timeout limit, i.e. the maximum duration is infinite. This value
* can be overridden in the PathMatcher configuration of the UrlMap that references this backend
* service. This field is only allowed when the loadBalancingScheme of the backend service is
* INTERNAL_SELF_MANAGED.
* @param maxStreamDuration maxStreamDuration or {@code null} for none
*/
public BackendService setMaxStreamDuration(Duration maxStreamDuration) {
this.maxStreamDuration = maxStreamDuration;
return this;
}
/**
* Name of the resource. Provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Name of the resource. Provided by the client when the resource is created. The name must be
* 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters
* long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?` which means the first
* character must be a lowercase letter, and all following characters must be a dash, lowercase
* letter, or digit, except the last character, which cannot be a dash.
* @param name name or {@code null} for none
*/
public BackendService setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The URL of the network to which this backend service belongs. This field can only be specified
* when the load balancing scheme is set to INTERNAL.
* @return value or {@code null} for none
*/
public java.lang.String getNetwork() {
return network;
}
/**
* The URL of the network to which this backend service belongs. This field can only be specified
* when the load balancing scheme is set to INTERNAL.
* @param network network or {@code null} for none
*/
public BackendService setNetwork(java.lang.String network) {
this.network = network;
return this;
}
/**
* Settings controlling the eviction of unhealthy hosts from the load balancing pool for the
* backend service. If not set, this feature is considered disabled. This field is applicable to
* either: - A regional backend service with the service_protocol set to HTTP, HTTPS, or HTTP2,
* and load_balancing_scheme set to INTERNAL_MANAGED. - A global backend service with the
* load_balancing_scheme set to INTERNAL_SELF_MANAGED. Not supported when the backend service is
* referenced by a URL map that is bound to target gRPC proxy that has validateForProxyless field
* set to true.
* @return value or {@code null} for none
*/
public OutlierDetection getOutlierDetection() {
return outlierDetection;
}
/**
* Settings controlling the eviction of unhealthy hosts from the load balancing pool for the
* backend service. If not set, this feature is considered disabled. This field is applicable to
* either: - A regional backend service with the service_protocol set to HTTP, HTTPS, or HTTP2,
* and load_balancing_scheme set to INTERNAL_MANAGED. - A global backend service with the
* load_balancing_scheme set to INTERNAL_SELF_MANAGED. Not supported when the backend service is
* referenced by a URL map that is bound to target gRPC proxy that has validateForProxyless field
* set to true.
* @param outlierDetection outlierDetection or {@code null} for none
*/
public BackendService setOutlierDetection(OutlierDetection outlierDetection) {
this.outlierDetection = outlierDetection;
return this;
}
/**
* Deprecated in favor of portName. The TCP port to connect on the backend. The default value is
* 80. For Internal TCP/UDP Load Balancing and Network Load Balancing, omit port.
* @return value or {@code null} for none
*/
public java.lang.Integer getPort() {
return port;
}
/**
* Deprecated in favor of portName. The TCP port to connect on the backend. The default value is
* 80. For Internal TCP/UDP Load Balancing and Network Load Balancing, omit port.
* @param port port or {@code null} for none
*/
public BackendService setPort(java.lang.Integer port) {
this.port = port;
return this;
}
/**
* A named port on a backend instance group representing the port for communication to the backend
* VMs in that group. The named port must be [defined on each backend instance
* group](https://cloud.google.com/load-balancing/docs/backend-service#named_ports). This
* parameter has no meaning if the backends are NEGs. For Internal TCP/UDP Load Balancing and
* Network Load Balancing, omit port_name.
* @return value or {@code null} for none
*/
public java.lang.String getPortName() {
return portName;
}
/**
* A named port on a backend instance group representing the port for communication to the backend
* VMs in that group. The named port must be [defined on each backend instance
* group](https://cloud.google.com/load-balancing/docs/backend-service#named_ports). This
* parameter has no meaning if the backends are NEGs. For Internal TCP/UDP Load Balancing and
* Network Load Balancing, omit port_name.
* @param portName portName or {@code null} for none
*/
public BackendService setPortName(java.lang.String portName) {
this.portName = portName;
return this;
}
/**
* The protocol this BackendService uses to communicate with backends. Possible values are HTTP,
* HTTPS, HTTP2, TCP, SSL, UDP or GRPC. depending on the chosen load balancer or Traffic Director
* configuration. Refer to the documentation for the load balancers or for Traffic Director for
* more information. Must be set to GRPC when the backend service is referenced by a URL map that
* is bound to target gRPC proxy.
* @return value or {@code null} for none
*/
public java.lang.String getProtocol() {
return protocol;
}
/**
* The protocol this BackendService uses to communicate with backends. Possible values are HTTP,
* HTTPS, HTTP2, TCP, SSL, UDP or GRPC. depending on the chosen load balancer or Traffic Director
* configuration. Refer to the documentation for the load balancers or for Traffic Director for
* more information. Must be set to GRPC when the backend service is referenced by a URL map that
* is bound to target gRPC proxy.
* @param protocol protocol or {@code null} for none
*/
public BackendService setProtocol(java.lang.String protocol) {
this.protocol = protocol;
return this;
}
/**
* [Output Only] URL of the region where the regional backend service resides. This field is not
* applicable to global backend services. You must specify this field as part of the HTTP request
* URL. It is not settable as a field in the request body.
* @return value or {@code null} for none
*/
public java.lang.String getRegion() {
return region;
}
/**
* [Output Only] URL of the region where the regional backend service resides. This field is not
* applicable to global backend services. You must specify this field as part of the HTTP request
* URL. It is not settable as a field in the request body.
* @param region region or {@code null} for none
*/
public BackendService setRegion(java.lang.String region) {
this.region = region;
return this;
}
/**
* [Output Only] The resource URL for the security policy associated with this backend service.
* @return value or {@code null} for none
*/
public java.lang.String getSecurityPolicy() {
return securityPolicy;
}
/**
* [Output Only] The resource URL for the security policy associated with this backend service.
* @param securityPolicy securityPolicy or {@code null} for none
*/
public BackendService setSecurityPolicy(java.lang.String securityPolicy) {
this.securityPolicy = securityPolicy;
return this;
}
/**
* This field specifies the security settings that apply to this backend service. This field is
* applicable to a global backend service with the load_balancing_scheme set to
* INTERNAL_SELF_MANAGED.
* @return value or {@code null} for none
*/
public SecuritySettings getSecuritySettings() {
return securitySettings;
}
/**
* This field specifies the security settings that apply to this backend service. This field is
* applicable to a global backend service with the load_balancing_scheme set to
* INTERNAL_SELF_MANAGED.
* @param securitySettings securitySettings or {@code null} for none
*/
public BackendService setSecuritySettings(SecuritySettings securitySettings) {
this.securitySettings = securitySettings;
return this;
}
/**
* [Output Only] Server-defined URL for the resource.
* @return value or {@code null} for none
*/
public java.lang.String getSelfLink() {
return selfLink;
}
/**
* [Output Only] Server-defined URL for the resource.
* @param selfLink selfLink or {@code null} for none
*/
public BackendService setSelfLink(java.lang.String selfLink) {
this.selfLink = selfLink;
return this;
}
/**
* [Output Only] Server-defined URL for this resource with the resource id.
* @return value or {@code null} for none
*/
public java.lang.String getSelfLinkWithId() {
return selfLinkWithId;
}
/**
* [Output Only] Server-defined URL for this resource with the resource id.
* @param selfLinkWithId selfLinkWithId or {@code null} for none
*/
public BackendService setSelfLinkWithId(java.lang.String selfLinkWithId) {
this.selfLinkWithId = selfLinkWithId;
return this;
}
/**
* URLs of networkservices.ServiceBinding resources. Can only be set if load balancing scheme is
* INTERNAL_SELF_MANAGED. If set, lists of backends and health checks must be both empty.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getServiceBindings() {
return serviceBindings;
}
/**
* URLs of networkservices.ServiceBinding resources. Can only be set if load balancing scheme is
* INTERNAL_SELF_MANAGED. If set, lists of backends and health checks must be both empty.
* @param serviceBindings serviceBindings or {@code null} for none
*/
public BackendService setServiceBindings(java.util.List<java.lang.String> serviceBindings) {
this.serviceBindings = serviceBindings;
return this;
}
/**
* URL to networkservices.ServiceLbPolicy resource. Can only be set if load balancing scheme is
* EXTERNAL, INTERNAL_MANAGED or INTERNAL_SELF_MANAGED. If used with a backend service, must
* reference a global policy. If used with a regional backend service, must reference a regional
* policy.
* @return value or {@code null} for none
*/
public java.lang.String getServiceLbPolicy() {
return serviceLbPolicy;
}
/**
* URL to networkservices.ServiceLbPolicy resource. Can only be set if load balancing scheme is
* EXTERNAL, INTERNAL_MANAGED or INTERNAL_SELF_MANAGED. If used with a backend service, must
* reference a global policy. If used with a regional backend service, must reference a regional
* policy.
* @param serviceLbPolicy serviceLbPolicy or {@code null} for none
*/
public BackendService setServiceLbPolicy(java.lang.String serviceLbPolicy) {
this.serviceLbPolicy = serviceLbPolicy;
return this;
}
/**
* Type of session affinity to use. The default is NONE. Only NONE and HEADER_FIELD are supported
* when the backend service is referenced by a URL map that is bound to target gRPC proxy that has
* validateForProxyless field set to true. For more details, see: [Session
* Affinity](https://cloud.google.com/load-balancing/docs/backend-service#session_affinity).
* @return value or {@code null} for none
*/
public java.lang.String getSessionAffinity() {
return sessionAffinity;
}
/**
* Type of session affinity to use. The default is NONE. Only NONE and HEADER_FIELD are supported
* when the backend service is referenced by a URL map that is bound to target gRPC proxy that has
* validateForProxyless field set to true. For more details, see: [Session
* Affinity](https://cloud.google.com/load-balancing/docs/backend-service#session_affinity).
* @param sessionAffinity sessionAffinity or {@code null} for none
*/
public BackendService setSessionAffinity(java.lang.String sessionAffinity) {
this.sessionAffinity = sessionAffinity;
return this;
}
/**
* @return value or {@code null} for none
*/
public Subsetting getSubsetting() {
return subsetting;
}
/**
* @param subsetting subsetting or {@code null} for none
*/
public BackendService setSubsetting(Subsetting subsetting) {
this.subsetting = subsetting;
return this;
}
/**
* The backend service timeout has a different meaning depending on the type of load balancer. For
* more information see, Backend service settings The default is 30 seconds. The full range of
* timeout values allowed is 1 - 2,147,483,647 seconds. This value can be overridden in the
* PathMatcher configuration of the UrlMap that references this backend service. Not supported
* when the backend service is referenced by a URL map that is bound to target gRPC proxy that has
* validateForProxyless field set to true. Instead, use maxStreamDuration.
* @return value or {@code null} for none
*/
public java.lang.Integer getTimeoutSec() {
return timeoutSec;
}
/**
* The backend service timeout has a different meaning depending on the type of load balancer. For
* more information see, Backend service settings The default is 30 seconds. The full range of
* timeout values allowed is 1 - 2,147,483,647 seconds. This value can be overridden in the
* PathMatcher configuration of the UrlMap that references this backend service. Not supported
* when the backend service is referenced by a URL map that is bound to target gRPC proxy that has
* validateForProxyless field set to true. Instead, use maxStreamDuration.
* @param timeoutSec timeoutSec or {@code null} for none
*/
public BackendService setTimeoutSec(java.lang.Integer timeoutSec) {
this.timeoutSec = timeoutSec;
return this;
}
@Override
public BackendService set(String fieldName, Object value) {
return (BackendService) super.set(fieldName, value);
}
@Override
public BackendService clone() {
return (BackendService) super.clone();
}
}
| apache-2.0 |
pyros2097/Scene3d | src/scene3d/actions/RunnableAction.java | 1410 | package scene3d.actions;
import scene3d.Action3d;
import com.badlogic.gdx.utils.Pool;
/** An action that runs a {@link Runnable}. Alternatively, the {@link #run()} method can be overridden instead of setting a
* runnable.
* @author Nathan Sweet */
public class RunnableAction extends Action3d {
private Runnable runnable;
private boolean ran;
@Override
public boolean act (float delta) {
if (!ran) {
ran = true;
run();
}
return true;
}
/** Called to run the runnable. */
public void run () {
Pool pool = getPool();
setPool(null); // Ensure this action can't be returned to the pool inside the runnable.
try {
runnable.run();
} finally {
setPool(pool);
}
}
@Override
public void restart () {
ran = false;
}
@Override
public void reset () {
super.reset();
runnable = null;
}
public Runnable getRunnable () {
return runnable;
}
public void setRunnable (Runnable runnable) {
this.runnable = runnable;
}
} | apache-2.0 |
google/depan | DepanViewDoc/prod/src/com/google/devtools/depan/view_doc/eclipse/ui/views/AbstractViewDocViewPart.java | 2280 | /*
* Copyright 2016 The Depan Project Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.depan.view_doc.eclipse.ui.views;
import com.google.devtools.depan.platform.eclipse.ui.views.EditorBoundViewPart;
import com.google.devtools.depan.view_doc.eclipse.ui.editor.ViewEditor;
import org.eclipse.swt.widgets.Composite;
/**
* @author <a href="leeca@pnambic.com">Lee Carver</a>
*/
public abstract class AbstractViewDocViewPart
extends EditorBoundViewPart<ViewEditor> {
public AbstractViewDocViewPart() {
super(ViewEditor.class);
}
@Override
public void createPartControl(Composite parentComposite) {
super.createPartControl(parentComposite);
if (hasEditor()) {
acquireResources();
}
}
/////////////////////////////////////
// ViewDoc/Editor integration
@Override
protected boolean newEditorCallback(ViewEditor editor) {
if (hasEditor()) {
releaseResources();
}
return true;
}
@Override
protected boolean closeEditorCallback(ViewEditor editor) {
if (hasEditor()) {
releaseResources();
}
return true;
}
@Override
public void eOpened(ViewEditor editor) {
super.eOpened(editor);
if (hasEditor()) {
acquireResources();
}
}
@Override
public void eActivated(ViewEditor editor) {
super.eActivated(editor);
if (hasEditor()) {
acquireResources();
}
}
@Override
public void eBroughtToTop(ViewEditor editor) {
super.eBroughtToTop(editor);
if (hasEditor()) {
acquireResources();
}
}
@Override
public void eDeactivated(ViewEditor editor) {
super.eDeactivated(editor);
}
protected abstract void acquireResources();
protected abstract void releaseResources();
}
| apache-2.0 |
alexander071/cf-java-client | cloudfoundry-client/src/main/java/org/cloudfoundry/client/v2/spaces/_ListSpaceServiceInstancesResponse.java | 1138 | /*
* Copyright 2013-2019 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.cloudfoundry.client.v2.spaces;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.cloudfoundry.client.v2.PaginatedResponse;
import org.cloudfoundry.client.v2.serviceinstances.UnionServiceInstanceResource;
import org.immutables.value.Value;
/**
* The response payload for the List all Service Instances for the Space operation
*/
@JsonDeserialize
@Value.Immutable
abstract class _ListSpaceServiceInstancesResponse extends PaginatedResponse<UnionServiceInstanceResource> {
}
| apache-2.0 |
lsmaira/gradle | subprojects/core/src/main/java/org/gradle/api/internal/resources/StringBackedTextResource.java | 2541 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.resources;
import com.google.common.io.Files;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.file.TemporaryFileProvider;
import org.gradle.api.internal.tasks.TaskDependencyInternal;
import org.gradle.api.resources.ResourceException;
import org.gradle.api.resources.internal.TextResourceInternal;
import org.gradle.api.tasks.TaskDependency;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.Charset;
public class StringBackedTextResource implements TextResourceInternal {
private final TemporaryFileProvider tempFileProvider;
private final String string;
public StringBackedTextResource(TemporaryFileProvider tempFileProvider, String string) {
this.tempFileProvider = tempFileProvider;
this.string = string;
}
@Override
public String getDisplayName() {
return "text resource";
}
@Override
public String toString() {
return getDisplayName();
}
public String asString() {
return string;
}
public Reader asReader() {
return new StringReader(string);
}
public File asFile(String charset) {
File file = tempFileProvider.createTemporaryFile("string", ".txt", "resource");
try {
Files.write(string, file, Charset.forName(charset));
} catch (IOException e) {
throw new ResourceException("Could not write " + getDisplayName() + " content to " + file + ".", e);
}
return file;
}
public File asFile() {
return asFile(Charset.defaultCharset().name());
}
public TaskDependency getBuildDependencies() {
return TaskDependencyInternal.EMPTY;
}
public Object getInputProperties() {
return string;
}
public FileCollection getInputFiles() {
return null;
}
}
| apache-2.0 |
weijiancai/metaui | fxbase/src/main/java/com/metaui/fxbase/ui/event/FormFieldClickEvent.java | 738 | package com.metaui.fxbase.ui.event;
import com.metaui.fxbase.ui.component.form.BaseFormField;
import javafx.event.Event;
import javafx.event.EventType;
/**
* 表单字段鼠标单击事件
*
* @author wei_jc
* @since 1.0.0
*/
public class FormFieldClickEvent extends Event {
public static EventType<FormFieldClickEvent> EVENT_TYPE = new EventType<FormFieldClickEvent>("FORM_FIELD_CLICK_EVENT_TYPE");
private BaseFormField formField;
public FormFieldClickEvent(BaseFormField formField) {
super(EVENT_TYPE);
this.formField = formField;
}
public String getName() {
return formField.getConfig().getName();
}
public BaseFormField getFormField() {
return formField;
}
}
| apache-2.0 |
hardfish/justTest | azurecompute/src/test/java/org/jclouds/azurecompute/features/CloudServiceApiLiveTest.java | 5842 | /*
* 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.jclouds.azurecompute.features;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.jclouds.azurecompute.domain.CloudService.Status.UNRECOGNIZED;
import static org.jclouds.util.Predicates2.retry;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.util.List;
import java.util.logging.Logger;
import org.jclouds.azurecompute.domain.CloudService;
import org.jclouds.azurecompute.domain.CloudService.Status;
import org.jclouds.azurecompute.internal.BaseAzureComputeApiLiveTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import java.util.logging.Level;
@Test(groups = "live", testName = "CloudServiceApiLiveTest", singleThreaded = true)
public class CloudServiceApiLiveTest extends BaseAzureComputeApiLiveTest {
private static final String CLOUD_SERVICE = String.format("%s%d-%s",
System.getProperty("user.name"), RAND, CloudServiceApiLiveTest.class.getSimpleName()).toLowerCase();
private Predicate<CloudService> cloudServiceCreated;
private Predicate<CloudService> cloudServiceGone;
@BeforeClass(groups = {"integration", "live"})
@Override
public void setup() {
super.setup();
cloudServiceCreated = retry(new Predicate<CloudService>() {
@Override
public boolean apply(CloudService input) {
return api().get(input.name()).status() == Status.CREATED;
}
}, 600, 5, 5, SECONDS);
cloudServiceGone = retry(new Predicate<CloudService>() {
@Override
public boolean apply(CloudService input) {
return api().get(input.name()) == null;
}
}, 600, 5, 5, SECONDS);
}
private CloudService cloudService;
public void testCreate() {
String requestId = api().createWithLabelInLocation(CLOUD_SERVICE, CLOUD_SERVICE, LOCATION);
assertTrue(operationSucceeded.apply(requestId), requestId);
Logger.getAnonymousLogger().log(Level.INFO, "operation succeeded: {0}", requestId);
cloudService = api().get(CLOUD_SERVICE);
Logger.getAnonymousLogger().log(Level.INFO, "created cloudService: {0}", cloudService);
assertEquals(cloudService.name(), CLOUD_SERVICE);
checkHostedService(cloudService);
assertTrue(cloudServiceCreated.apply(cloudService), cloudService.toString());
cloudService = api().get(cloudService.name());
Logger.getAnonymousLogger().log(Level.INFO, "cloudService available: {0}", cloudService);
}
@Test(dependsOnMethods = "testCreate")
public void testGet() {
CloudService foundCloudService = api().get(cloudService.name());
assertThat(foundCloudService).isEqualToComparingFieldByField(cloudService);
}
@Test(dependsOnMethods = "testGet")
public void testDelete() {
String requestId = api().delete(cloudService.name());
assertTrue(operationSucceeded.apply(requestId), requestId);
Logger.getAnonymousLogger().log(Level.INFO, "operation succeeded: {0}", requestId);
assertTrue(cloudServiceGone.apply(cloudService), cloudService.toString());
Logger.getAnonymousLogger().log(Level.INFO, "cloudService deleted: {0}", cloudService);
}
@Override
@AfterClass(groups = "live", alwaysRun = true)
protected void tearDown() {
String requestId = api().delete(CLOUD_SERVICE);
if (requestId != null) {
operationSucceeded.apply(requestId);
}
super.tearDown();
}
public void testList() {
List<CloudService> response = api().list();
for (CloudService cs : response) {
checkHostedService(cs);
}
if (!response.isEmpty()) {
CloudService cs = response.iterator().next();
assertEquals(api().get(cs.name()), cs);
}
}
private void checkHostedService(CloudService cloudService) {
assertNotNull(cloudService.name(), "ServiceName cannot be null for " + cloudService);
assertTrue(cloudService.location() != null || cloudService.affinityGroup() != null,
"Location or AffinityGroup must be present for " + cloudService);
assertNotNull(cloudService.label(), "Label cannot be null for " + cloudService);
assertNotNull(cloudService.status(), "Status cannot be null for " + cloudService);
assertNotEquals(cloudService.status(), UNRECOGNIZED, "Status cannot be UNRECOGNIZED for " + cloudService);
assertNotNull(cloudService.created(), "Created cannot be null for " + cloudService);
assertNotNull(cloudService.lastModified(), "LastModified cannot be null for " + cloudService);
assertNotNull(cloudService.extendedProperties(), "ExtendedProperties cannot be null for " + cloudService);
}
private CloudServiceApi api() {
return api.getCloudServiceApi();
}
}
| apache-2.0 |
apetresc/aws-sdk-for-java-on-gae | src/main/java/com/amazonaws/services/s3/model/AbortMultipartUploadRequest.java | 4497 | /*
* Copyright 2010-2011 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.s3.model;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.services.s3.AmazonS3;
/**
* The AbortMultipartUploadRequest contains the parameters used for the
* AbortMultipartUpload method.
* <p>
* Required Parameters: BucketName, Key, UploadId
*
* @see AmazonS3#abortMultipartUpload(AbortMultipartUploadRequest)
*/
public class AbortMultipartUploadRequest extends AmazonWebServiceRequest {
/** The name of the bucket containing the multipart upload to abort */
private String bucketName;
/** The key of the multipart upload to abort */
private String key;
/** The ID of the multipart upload to abort */
private String uploadId;
/**
* Constructs a new request to abort a multipart upload.
*
* @param bucketName
* The name of the bucket containing the multipart upload to
* abort.
* @param key
* The key of the multipart upload to abort.
* @param uploadId
* The ID of the multipart upload to abort.
*/
public AbortMultipartUploadRequest(String bucketName, String key, String uploadId) {
this.bucketName = bucketName;
this.key = key;
this.uploadId = uploadId;
}
/**
* Returns the name of the bucket containing the multipart upload to abort.
*/
public String getBucketName() {
return this.bucketName;
}
/**
* Sets the name of the bucket containing the multipart upload to abort.
*/
public void setBucketName(String value) {
this.bucketName = value;
}
/**
* Sets the name of the bucket containing the multipart upload to abort and
* returns the updated object so that additional calls can be chained
* together.
*
* @param bucketName
* The name of the bucket containing the multipart upload to
* abort.
*
* @return The updated AbortMultipartUploadRequest object.
*/
public AbortMultipartUploadRequest withBucketName(String bucketName) {
this.bucketName = bucketName;
return this;
}
/**
* Returns the key of the multipart upload to abort.
*
* @return The key of the multipart upload to abort.
*/
public String getKey() {
return key;
}
/**
* Sets the key of the multipart upload to abort.
*
* @param key
* The key of the multipart upload to abort.
*/
public void setKey(String key) {
this.key = key;
}
/**
* Sets the key of the multipart upload to abort and returns the updated
* AbortMultipartUploadRequest object so that additional method calls can be
* chained together.
*
* @param key
* The key of the multipart upload to abort.
*
* @return The updated AbortMultipartUploadRequest.
*/
public AbortMultipartUploadRequest withKey(String key) {
this.key = key;
return this;
}
/**
* Returns the ID of the upload to abort.
*
* @return the ID of the upload to abort.
*/
public String getUploadId() {
return uploadId;
}
/**
* Sets the ID of the upload to abort.
*
* @return the ID of the upload to abort.
*/
public void setUploadId(String uploadId) {
this.uploadId = uploadId;
}
/**
* Sets the ID of the multipart upload to abort, and returns this updated
* AbortMultipartUploadRequest object so that additional method calls can be
* chained together.
*
* @param uploadId
* The ID of the multipart upload to abort.
*
* @return The updated AbortMultipartUploadRequest object.
*/
public AbortMultipartUploadRequest withUploadId(String uploadId) {
this.uploadId = uploadId;
return this;
}
}
| apache-2.0 |
apetresc/aws-sdk-for-java-on-gae | src/main/java/com/amazonaws/services/autoscaling/model/DescribeAutoScalingGroupsResult.java | 5390 | /*
* Copyright 2010-2011 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.autoscaling.model;
/**
* <p>
* The AutoScalingGroupsType data type.
* </p>
*/
public class DescribeAutoScalingGroupsResult {
/**
* A list of Auto Scaling groups.
*/
private java.util.List<AutoScalingGroup> autoScalingGroups;
/**
* A string that marks the start of the next batch of returned results.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*/
private String nextToken;
/**
* A list of Auto Scaling groups.
*
* @return A list of Auto Scaling groups.
*/
public java.util.List<AutoScalingGroup> getAutoScalingGroups() {
if (autoScalingGroups == null) {
autoScalingGroups = new java.util.ArrayList<AutoScalingGroup>();
}
return autoScalingGroups;
}
/**
* A list of Auto Scaling groups.
*
* @param autoScalingGroups A list of Auto Scaling groups.
*/
public void setAutoScalingGroups(java.util.Collection<AutoScalingGroup> autoScalingGroups) {
java.util.List<AutoScalingGroup> autoScalingGroupsCopy = new java.util.ArrayList<AutoScalingGroup>();
if (autoScalingGroups != null) {
autoScalingGroupsCopy.addAll(autoScalingGroups);
}
this.autoScalingGroups = autoScalingGroupsCopy;
}
/**
* A list of Auto Scaling groups.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param autoScalingGroups A list of Auto Scaling groups.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DescribeAutoScalingGroupsResult withAutoScalingGroups(AutoScalingGroup... autoScalingGroups) {
for (AutoScalingGroup value : autoScalingGroups) {
getAutoScalingGroups().add(value);
}
return this;
}
/**
* A list of Auto Scaling groups.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param autoScalingGroups A list of Auto Scaling groups.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DescribeAutoScalingGroupsResult withAutoScalingGroups(java.util.Collection<AutoScalingGroup> autoScalingGroups) {
java.util.List<AutoScalingGroup> autoScalingGroupsCopy = new java.util.ArrayList<AutoScalingGroup>();
if (autoScalingGroups != null) {
autoScalingGroupsCopy.addAll(autoScalingGroups);
}
this.autoScalingGroups = autoScalingGroupsCopy;
return this;
}
/**
* A string that marks the start of the next batch of returned results.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @return A string that marks the start of the next batch of returned results.
*/
public String getNextToken() {
return nextToken;
}
/**
* A string that marks the start of the next batch of returned results.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param nextToken A string that marks the start of the next batch of returned results.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* A string that marks the start of the next batch of returned results.
* <p>
* Returns a reference to this object so that method calls can be chained together.
* <p>
* <b>Constraints:</b><br/>
* <b>Pattern: </b>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*<br/>
*
* @param nextToken A string that marks the start of the next batch of returned results.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public DescribeAutoScalingGroupsResult withNextToken(String nextToken) {
this.nextToken = nextToken;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("AutoScalingGroups: " + autoScalingGroups + ", ");
sb.append("NextToken: " + nextToken + ", ");
sb.append("}");
return sb.toString();
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-retail/v2alpha/1.31.0/com/google/api/services/retail/v2alpha/model/GoogleCloudRetailV2alphaSetLocalInventoriesResponse.java | 1837 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.retail.v2alpha.model;
/**
* Response of the SetLocalInventories API. Currently empty because there is no meaningful response
* populated from the SetLocalInventories method.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Retail API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudRetailV2alphaSetLocalInventoriesResponse extends com.google.api.client.json.GenericJson {
@Override
public GoogleCloudRetailV2alphaSetLocalInventoriesResponse set(String fieldName, Object value) {
return (GoogleCloudRetailV2alphaSetLocalInventoriesResponse) super.set(fieldName, value);
}
@Override
public GoogleCloudRetailV2alphaSetLocalInventoriesResponse clone() {
return (GoogleCloudRetailV2alphaSetLocalInventoriesResponse) super.clone();
}
}
| apache-2.0 |
nishtahir/Mektory-BeginnersAndroid | TaskManager/app/src/androidTest/java/com/example/taskmanager/ApplicationTest.java | 354 | package com.example.taskmanager;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | apache-2.0 |
masonmei/java-agent | rpc/src/main/java/com/baidu/oped/apm/rpc/common/SocketStateChangeResult.java | 2187 | /*
* Copyright 2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.baidu.oped.apm.rpc.common;
/**
* @author Taejin Koo
*/
public class SocketStateChangeResult {
private final boolean isChange;
private final SocketStateCode beforeState;
private final SocketStateCode currentState;
private final SocketStateCode updateWantedState;
public SocketStateChangeResult(boolean isChange, SocketStateCode beforeState, SocketStateCode currentState, SocketStateCode updateWantedState) {
this.isChange = isChange;
this.beforeState = beforeState;
this.currentState = currentState;
this.updateWantedState = updateWantedState;
}
public boolean isChange() {
return isChange;
}
public SocketStateCode getBeforeState() {
return beforeState;
}
public SocketStateCode getCurrentState() {
return currentState;
}
public SocketStateCode getUpdateWantedState() {
return updateWantedState;
}
@Override
public String toString() {
StringBuilder toString = new StringBuilder();
toString.append("Socket state change ");
if (isChange) {
toString.append("success");
} else {
toString.append("fail");
}
toString.append("(updateWanted:");
toString.append(updateWantedState);
toString.append(" ,before:");
toString.append(beforeState);
toString.append(" ,current:");
toString.append(currentState);
toString.append(").");
return toString.toString();
}
} | apache-2.0 |
NyBatis/NyBatisCore | src/main/java/org/nybatis/core/db/datasource/factory/jdbc/JdbcDataSourceFactory.java | 1556 | package org.nybatis.core.db.datasource.factory.jdbc;
import javax.sql.DataSource;
import org.nybatis.core.db.datasource.factory.parameter.JdbcConnectionProperties;
import org.nybatis.core.db.configuration.connectionPool.JdbcDatasourceProperties;
import org.nybatis.core.db.datasource.DatasourceFactory;
/**
* JDBC datasource factory
*/
public class JdbcDataSourceFactory implements DatasourceFactory {
private JdbcDatasourceProperties datasourceProperties;
private JdbcConnectionProperties connectionProperties;
/**
* Create Pooled Datasource Factory
*
* @param datasourceProperties datasource configuration properties
* @param connectionProperties JDBC connection properties
*/
public JdbcDataSourceFactory( JdbcDatasourceProperties datasourceProperties, JdbcConnectionProperties connectionProperties ) {
this.datasourceProperties = datasourceProperties;
this.connectionProperties = connectionProperties;
}
/**
* Create Unpooled Datasource Factory
*
* @param connectionProperties JDBC connection properties
*/
public JdbcDataSourceFactory( JdbcConnectionProperties connectionProperties ) {
this.datasourceProperties = new JdbcDatasourceProperties();
this.connectionProperties = connectionProperties;
datasourceProperties.setPooled( false );
}
/**
* get datasource
*
* @return datasource
*/
public DataSource getDataSource() {
return datasourceProperties.isPooled()
? new JdbcDataSource( datasourceProperties, connectionProperties )
: new JdbcUnpooledDataSource( connectionProperties );
}
}
| apache-2.0 |
leleliu008/Newton_for_Android_AS | src/main/java/com/fpliu/newton/framework/ui/dialog/alert/SweetAlertDialog.java | 9991 | package com.fpliu.newton.framework.ui.dialog.alert;
import java.util.List;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.Transformation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.fpliu.newton.R;
public class SweetAlertDialog extends Dialog implements View.OnClickListener {
private View mDialogView;
private AnimationSet mModalInAnim;
private AnimationSet mModalOutAnim;
private Animation mOverlayOutAnim;
private Animation mErrorInAnim;
private AnimationSet mErrorXInAnim;
private AnimationSet mSuccessLayoutAnimSet;
private Animation mSuccessBowAnim;
private TextView mTitleTextView;
private TextView mContentTextView;
private String mTitleText;
private String mContentText;
private boolean mShowCancel;
private String mCancelText;
private String mConfirmText;
private int mAlertType;
private FrameLayout mErrorFrame;
private FrameLayout mSuccessFrame;
private SuccessTickView mSuccessTick;
private ImageView mErrorX;
private View mSuccessLeftMask;
private View mSuccessRightMask;
private Drawable mCustomImgDrawable;
private ImageView mCustomImage;
private Button mConfirmButton;
private Button mCancelButton;
private FrameLayout mWarningFrame;
private OnSweetClickListener mCancelClickListener;
private OnSweetClickListener mConfirmClickListener;
public static final int NORMAL_TYPE = 0;
public static final int ERROR_TYPE = 1;
public static final int SUCCESS_TYPE = 2;
public static final int WARNING_TYPE = 3;
public static final int CUSTOM_IMAGE_TYPE = 4;
public static interface OnSweetClickListener {
public void onClick(SweetAlertDialog sweetAlertDialog);
}
public SweetAlertDialog(Context context) {
this(context, NORMAL_TYPE);
}
public SweetAlertDialog(Context context, int alertType) {
super(context, R.style.alert_dialog);
setCancelable(true);
setCanceledOnTouchOutside(false);
mAlertType = alertType;
mErrorInAnim = OptAnimationLoader.loadAnimation(getContext(),
R.anim.error_frame_in);
mErrorXInAnim = (AnimationSet) OptAnimationLoader.loadAnimation(
getContext(), R.anim.error_x_in);
// 2.3.x system don't support alpha-animation on layer-list drawable
// remove it from animation set
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
List<Animation> childAnims = mErrorXInAnim.getAnimations();
int idx = 0;
for (; idx < childAnims.size(); idx++) {
if (childAnims.get(idx) instanceof AlphaAnimation) {
break;
}
}
if (idx < childAnims.size()) {
childAnims.remove(idx);
}
}
mSuccessBowAnim = OptAnimationLoader.loadAnimation(getContext(),
R.anim.success_bow_roate);
mSuccessLayoutAnimSet = (AnimationSet) OptAnimationLoader
.loadAnimation(getContext(), R.anim.success_mask_layout);
mModalInAnim = (AnimationSet) OptAnimationLoader.loadAnimation(
getContext(), R.anim.modal_in);
mModalOutAnim = (AnimationSet) OptAnimationLoader.loadAnimation(
getContext(), R.anim.modal_out);
mModalOutAnim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
mDialogView.setVisibility(View.GONE);
mDialogView.post(new Runnable() {
@Override
public void run() {
SweetAlertDialog.super.dismiss();
}
});
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
// dialog overlay fade out
mOverlayOutAnim = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime,
Transformation t) {
WindowManager.LayoutParams wlp = getWindow().getAttributes();
wlp.alpha = 1 - interpolatedTime;
getWindow().setAttributes(wlp);
}
};
mOverlayOutAnim.setDuration(120);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alert_dialog);
mDialogView = getWindow().getDecorView().findViewById(
android.R.id.content);
mTitleTextView = (TextView) findViewById(R.id.title_text);
mContentTextView = (TextView) findViewById(R.id.content_text);
mErrorFrame = (FrameLayout) findViewById(R.id.error_frame);
mErrorX = (ImageView) mErrorFrame.findViewById(R.id.error_x);
mSuccessFrame = (FrameLayout) findViewById(R.id.success_frame);
mSuccessTick = (SuccessTickView) mSuccessFrame
.findViewById(R.id.success_tick);
mSuccessLeftMask = mSuccessFrame.findViewById(R.id.mask_left);
mSuccessRightMask = mSuccessFrame.findViewById(R.id.mask_right);
mCustomImage = (ImageView) findViewById(R.id.custom_image);
mWarningFrame = (FrameLayout) findViewById(R.id.warning_frame);
mConfirmButton = (Button) findViewById(R.id.confirm_button);
mCancelButton = (Button) findViewById(R.id.cancel_button);
mConfirmButton.setOnClickListener(this);
mCancelButton.setOnClickListener(this);
setTitleText(mTitleText);
setContentText(mContentText);
showCancelButton(mShowCancel);
setCancelText(mCancelText);
setConfirmText(mConfirmText);
changeAlertType(mAlertType, true);
}
private void restore() {
mCustomImage.setVisibility(View.GONE);
mErrorFrame.setVisibility(View.GONE);
mSuccessFrame.setVisibility(View.GONE);
mWarningFrame.setVisibility(View.GONE);
mConfirmButton.setBackgroundResource(R.drawable.blue_button_background);
mErrorFrame.clearAnimation();
mErrorX.clearAnimation();
mSuccessTick.clearAnimation();
mSuccessLeftMask.clearAnimation();
mSuccessRightMask.clearAnimation();
}
private void playAnimation() {
if (mAlertType == ERROR_TYPE) {
mErrorFrame.startAnimation(mErrorInAnim);
mErrorX.startAnimation(mErrorXInAnim);
} else if (mAlertType == SUCCESS_TYPE) {
mSuccessTick.startTickAnim();
mSuccessRightMask.startAnimation(mSuccessBowAnim);
}
}
private void changeAlertType(int alertType, boolean fromCreate) {
mAlertType = alertType;
// call after created views
if (mDialogView != null) {
if (!fromCreate) {
// restore all of views state before switching alert type
restore();
}
switch (mAlertType) {
case ERROR_TYPE:
mErrorFrame.setVisibility(View.VISIBLE);
break;
case SUCCESS_TYPE:
mSuccessFrame.setVisibility(View.VISIBLE);
// initial rotate layout of success mask
mSuccessLeftMask.startAnimation(mSuccessLayoutAnimSet
.getAnimations().get(0));
mSuccessRightMask.startAnimation(mSuccessLayoutAnimSet
.getAnimations().get(1));
break;
case WARNING_TYPE:
mConfirmButton
.setBackgroundResource(R.drawable.red_button_background);
mWarningFrame.setVisibility(View.VISIBLE);
break;
case CUSTOM_IMAGE_TYPE:
setCustomImage(mCustomImgDrawable);
break;
}
if (!fromCreate) {
playAnimation();
}
}
}
public int getAlerType() {
return mAlertType;
}
public void changeAlertType(int alertType) {
changeAlertType(alertType, false);
}
public String getTitleText() {
return mTitleText;
}
public SweetAlertDialog setTitleText(String text) {
mTitleText = text;
if (mTitleTextView != null && mTitleText != null) {
mTitleTextView.setText(mTitleText);
}
return this;
}
public SweetAlertDialog setCustomImage(Drawable drawable) {
mCustomImgDrawable = drawable;
if (mCustomImage != null && mCustomImgDrawable != null) {
mCustomImage.setVisibility(View.VISIBLE);
mCustomImage.setImageDrawable(mCustomImgDrawable);
}
return this;
}
public SweetAlertDialog setCustomImage(int resourceId) {
return setCustomImage(getContext().getResources().getDrawable(
resourceId));
}
public String getContentText() {
return mContentText;
}
public SweetAlertDialog setContentText(String text) {
mContentText = text;
if (mContentTextView != null && mContentText != null) {
mContentTextView.setVisibility(View.VISIBLE);
mContentTextView.setText(mContentText);
}
return this;
}
public boolean isShowCancelButton() {
return mShowCancel;
}
public SweetAlertDialog showCancelButton(boolean isShow) {
mShowCancel = isShow;
if (mCancelButton != null) {
mCancelButton.setVisibility(mShowCancel ? View.VISIBLE : View.GONE);
}
return this;
}
public String getCancelText() {
return mCancelText;
}
public SweetAlertDialog setCancelText(String text) {
mCancelText = text;
if (mCancelButton != null && mCancelText != null) {
mCancelButton.setText(mCancelText);
}
return this;
}
public String getConfirmText() {
return mConfirmText;
}
public SweetAlertDialog setConfirmText(String text) {
mConfirmText = text;
if (mConfirmButton != null && mConfirmText != null) {
mConfirmButton.setText(mConfirmText);
}
return this;
}
public SweetAlertDialog setCancelClickListener(OnSweetClickListener listener) {
mCancelClickListener = listener;
return this;
}
public SweetAlertDialog setConfirmClickListener(
OnSweetClickListener listener) {
mConfirmClickListener = listener;
return this;
}
protected void onStart() {
mDialogView.startAnimation(mModalInAnim);
playAnimation();
}
public void dismiss() {
mConfirmButton.startAnimation(mOverlayOutAnim);
mDialogView.startAnimation(mModalOutAnim);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.cancel_button) {
if (mCancelClickListener != null) {
mCancelClickListener.onClick(SweetAlertDialog.this);
} else {
dismiss();
}
} else if (v.getId() == R.id.confirm_button) {
if (mConfirmClickListener != null) {
mConfirmClickListener.onClick(SweetAlertDialog.this);
} else {
dismiss();
}
}
}
}
| apache-2.0 |