repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
Aeronica/mxTune | src/main/java/net/aeronica/mods/mxtune/gui/util/GuiLockButton.java | 3399 | /*
* Aeronica's mxTune MOD
* Copyright 2019, Paul Boese a.k.a. Aeronica
*
* 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.aeronica.mods.mxtune.gui.util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
@SideOnly(Side.CLIENT)
public class GuiLockButton extends GuiButtonMX
{
private boolean locked;
public GuiLockButton(int buttonId, int x, int y)
{
super(buttonId, x, y, 20, 20, "");
}
public boolean isLocked()
{
return this.locked;
}
public void setLocked(boolean lockedIn)
{
this.locked = lockedIn;
}
/**
* Draws this button to the screen.
*/
@Override
public void drawButton(@Nonnull Minecraft mc, int mouseX, int mouseY, float partialTicks)
{
if (this.visible)
{
mc.getTextureManager().bindTexture(GuiButton.BUTTON_TEXTURES);
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
boolean flag = mouseX >= this.x && mouseY >= this.y && mouseX < this.x + this.width && mouseY < this.y + this.height;
GuiLockButton.Icon guiLockButtonIcon;
if (this.locked)
{
if (!this.enabled)
{
guiLockButtonIcon = GuiLockButton.Icon.LOCKED_DISABLED;
}
else if (flag)
{
guiLockButtonIcon = GuiLockButton.Icon.LOCKED_HOVER;
}
else
{
guiLockButtonIcon = GuiLockButton.Icon.LOCKED;
}
}
else if (!this.enabled)
{
guiLockButtonIcon = GuiLockButton.Icon.UNLOCKED_DISABLED;
}
else if (flag)
{
guiLockButtonIcon = GuiLockButton.Icon.UNLOCKED_HOVER;
}
else
{
guiLockButtonIcon = GuiLockButton.Icon.UNLOCKED;
}
this.drawTexturedModalRect(this.x, this.y, guiLockButtonIcon.getX(), guiLockButtonIcon.getY(), this.width, this.height);
}
}
@SideOnly(Side.CLIENT)
enum Icon
{
LOCKED(0, 146),
LOCKED_HOVER(0, 166),
LOCKED_DISABLED(0, 186),
UNLOCKED(20, 146),
UNLOCKED_HOVER(20, 166),
UNLOCKED_DISABLED(20, 186);
private final int x;
private final int y;
Icon(int xIn, int yIn)
{
this.x = xIn;
this.y = yIn;
}
public int getX()
{
return this.x;
}
public int getY()
{
return this.y;
}
}
}
| apache-2.0 |
selckin/swu | swu-base/src/main/java/be/selckin/swu/model/DiscardingModel.java | 722 | package be.selckin.swu.model;
import com.google.common.base.Preconditions;
import org.apache.wicket.model.IModel;
public class DiscardingModel<T> implements IModel<T> {
private transient T obj;
public DiscardingModel(T obj) {
Preconditions.checkNotNull(obj);
this.obj = obj;
}
@Override
public T getObject() {
Preconditions.checkNotNull(obj, "Attempting to use a detached discarding model");
return obj;
}
@Override
public void setObject(T object) {
this.obj = object;
}
@Override
public void detach() {
obj = null;
}
public static <T> DiscardingModel<T> of(T t) {
return new DiscardingModel<T>(t);
}
}
| apache-2.0 |
ymn/lorsource | src/main/java/ru/org/linux/user/BanInfo.java | 1118 | /*
* Copyright 1998-2015 Linux.org.ru
* 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 ru.org.linux.user;
import java.sql.Timestamp;
public class BanInfo {
private final Timestamp date;
private final String reason;
private final User moderator;
public BanInfo(Timestamp date, String reason, User moderator) {
this.date = date;
this.reason = reason;
this.moderator = moderator;
}
public Timestamp getDate() {
return date;
}
public String getReason() {
return reason;
}
public User getModerator() {
return moderator;
}
}
| apache-2.0 |
Unicon/cas | support/cas-server-support-saml-idp/src/main/java/org/apereo/cas/support/saml/services/SamlIdPSingleLogoutServiceLogoutUrlBuilder.java | 3511 | package org.apereo.cas.support.saml.services;
import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.logout.DefaultSingleLogoutServiceLogoutUrlBuilder;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade;
import org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver;
import org.apereo.cas.web.UrlValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
import java.util.Optional;
/**
* This is {@link SamlIdPSingleLogoutServiceLogoutUrlBuilder}.
*
* @author Misagh Moayyed
* @since 5.0.0
*/
public class SamlIdPSingleLogoutServiceLogoutUrlBuilder extends DefaultSingleLogoutServiceLogoutUrlBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(SamlIdPSingleLogoutServiceLogoutUrlBuilder.class);
/**
* The Services manager.
*/
protected ServicesManager servicesManager;
/**
* The Saml registered service caching metadata resolver.
*/
protected SamlRegisteredServiceCachingMetadataResolver samlRegisteredServiceCachingMetadataResolver;
public SamlIdPSingleLogoutServiceLogoutUrlBuilder(final ServicesManager servicesManager,
final SamlRegisteredServiceCachingMetadataResolver resolver,
final UrlValidator urlValidator) {
super(urlValidator);
this.servicesManager = servicesManager;
this.samlRegisteredServiceCachingMetadataResolver = resolver;
}
@Override
public URL determineLogoutUrl(final RegisteredService registeredService,
final WebApplicationService singleLogoutService) {
try {
if (registeredService instanceof SamlRegisteredService) {
final URL location = buildLogoutUrl(registeredService, singleLogoutService);
if (location != null) {
LOGGER.info("Final logout URL built for [{}] is [{}]", registeredService, location);
return location;
}
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
LOGGER.debug("Service [{}] is not a SAML service, or its logout url could not be determined", registeredService);
return super.determineLogoutUrl(registeredService, singleLogoutService);
}
private URL buildLogoutUrl(final RegisteredService registeredService, final WebApplicationService singleLogoutService) throws Exception {
LOGGER.debug("Building logout url for SAML service [{}]", registeredService);
final String entityID = singleLogoutService.getId();
LOGGER.debug("Located entity id [{}]", entityID);
final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> adaptor =
SamlRegisteredServiceServiceProviderMetadataFacade.get(this.samlRegisteredServiceCachingMetadataResolver,
SamlRegisteredService.class.cast(registeredService), entityID);
if (!adaptor.isPresent()) {
LOGGER.warn("Cannot find metadata linked to [{}]", entityID);
return null;
}
final String location = adaptor.get().getSingleLogoutService().getLocation();
return new URL(location);
}
}
| apache-2.0 |
CMPUT301W15T13/TravelPlanner | TravelPlanner/src/ca/ualberta/cmput301w15t13/Models/Tag.java | 830 | package ca.ualberta.cmput301w15t13.Models;
/**
* This class models a Tag
* object. Using the Tag model
* over an arrayList of Strings
* is favorable as we can define Tag
* operations more easily and
* map the same tag to a new claim.
*
* This should be used as a way
* of indicating or marking something
* about a paticular claim object
*
* Classes it works with:
* Claim, TagManager
*/
public class Tag {
String tagName;
public Tag(String tagName){
this.tagName = tagName;
}
public String getTagName() {
return this.tagName;
}
public void setTagName(String name) {
if (name == "") {
this.tagName = "Unnamed";
} else {
this.tagName = name;
}
}
//Defines how a tag is displayed
//if using an ArrayAdapter<tag>
@Override
public String toString() {
return (tagName);
}
}
| apache-2.0 |
jeffoffutt/OJ | src/openjava/mop/AmbiguousClassesException.java | 734 | /*
* AmbiguousClassesException.java
*
* @author Michiaki Tatsubori
* @version %VERSION% %DATE%
* @see java.lang.Object
*
* COPYRIGHT 1999 by Michiaki Tatsubori, ALL RIGHTS RESERVED.
*/
package openjava.mop;
/**
* The exception <code>AmbiguousClassesException</code> is thrown if the
* additional <code>OJClass</code> object has the same name with another
* <code>OJClass</code> object's.
* <p>
*
* @author Michiaki Tatsubori
* @version 1.0
* @since $Id: AmbiguousClassesException.java,v 1.2 2003/02/19 02:55:01 tatsubori Exp $
* @see java.lang.Object
*/
public class AmbiguousClassesException extends MOPException {
public AmbiguousClassesException( String access ) {
super( access );
}
}
| apache-2.0 |
Intuso/housemate-client | real/impl/src/main/java/com/intuso/housemate/client/v1_0/real/impl/type/StringType.java | 827 | package com.intuso.housemate.client.v1_0.real.impl.type;
import com.google.inject.Inject;
import com.intuso.housemate.client.v1_0.api.type.serialiser.StringSerialiser;
import com.intuso.housemate.client.v1_0.real.impl.ChildUtil;
import com.intuso.housemate.client.v1_0.real.impl.ioc.Type;
import com.intuso.utilities.collection.ManagedCollectionFactory;
import org.slf4j.Logger;
/**
* Type for a string
*/
public class StringType extends RealPrimitiveType<String> {
@Inject
public StringType(@Type Logger logger,
ManagedCollectionFactory managedCollectionFactory) {
super(ChildUtil.logger(logger, String.class.getName()),
new PrimitiveData("string", "String", "Some text"),
StringSerialiser.INSTANCE,
managedCollectionFactory);
}
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_7189.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_7189 {
}
| apache-2.0 |
nirmal070125/siddhi | modules/siddhi-core/src/main/java/org/wso2/siddhi/core/query/output/ratelimit/PassThroughOutputRateLimiter.java | 1752 | /*
* Copyright (c) 2015, 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.siddhi.core.query.output.ratelimit;
import org.apache.log4j.Logger;
import org.wso2.siddhi.core.event.ComplexEventChunk;
public class PassThroughOutputRateLimiter extends OutputRateLimiter {
private static final Logger log = Logger.getLogger(PassThroughOutputRateLimiter.class);
private String id;
public PassThroughOutputRateLimiter(String id) {
this.id = id;
}
public PassThroughOutputRateLimiter clone(String key) {
PassThroughOutputRateLimiter instance = new PassThroughOutputRateLimiter(id + key);
instance.setLatencyTracker(latencyTracker);
return instance;
}
@Override
public void process(ComplexEventChunk complexEventChunk) {
sendToCallBacks(complexEventChunk);
}
@Override
public void start() {
//Nothing to start
}
@Override
public void stop() {
//Nothing to stop
}
@Override
public Object[] currentState() {
return new Object[0];
}
@Override
public void restoreState(Object[] state) {
}
}
| apache-2.0 |
spring-projects/spring-data-examples | jpa/deferred/src/main/java/example/repo/Customer148Repository.java | 280 | package example.repo;
import example.model.Customer148;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer148Repository extends CrudRepository<Customer148, Long> {
List<Customer148> findByLastName(String lastName);
}
| apache-2.0 |
cocoas/Boomshakalaka | app/src/main/java/com/orcs/boomshakalaka/activity/MainActivity.java | 7068 | package com.orcs.boomshakalaka.activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.orcs.boomshakalaka.R;
import com.orcs.boomshakalaka.fragment.CommunityFragment;
import com.orcs.boomshakalaka.fragment.LibraryFragment;
import com.orcs.boomshakalaka.fragment.PersonalFragment;
import com.orcs.boomshakalaka.fragment.SearchFragment;
import com.orcs.boomshakalaka.widget.DialogCreator;
import java.util.ArrayList;
import java.util.List;
/**
* Author: HuLei
* Version V1.0
* Date: 2016/6/3 18:18.
* Description:
* Modification History:
* Date Author Version Description
* -----------------------------------------------------------------------------------
* 2016/6/3 HuLei 1.0 1.0
* Why & What is modified:
*/
public class MainActivity extends BaseActivity implements View.OnClickListener {
//Tab页面代号
public static final int TAB_COMMUNITY = 0;
public static final int TAB_LIBRARY = 1;
public static final int TAB_SEARCH = 2;
public static final int TAB_PERSONAL = 3;
private long mLastClickBack = 0;
private ViewPager mViewPager;
private RadioButton mTabCommunity;
private RadioButton mTabLibrary;
private RadioButton mTabSearch;
private RadioButton mTabPersonal;
//抽象组件
private ViewPagerAdapter mPagerAdapter;
private CommunityFragment mCommunityFragment;
private LibraryFragment mLibraryFragment;
private SearchFragment mSearchFragment;
private PersonalFragment mPersonalFragment;
private List<Fragment> mFragmentList;
private Dialog mUpdate;
private TextView mText;
private Button mCancel;
private Button mConfirm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ViewPager
mViewPager = (ViewPager) findViewById(R.id.content_container);
//Tab
mTabCommunity = (RadioButton) findViewById(R.id.tab_community);
mTabLibrary = (RadioButton) findViewById(R.id.tab_library);
mTabPersonal = (RadioButton) findViewById(R.id.tab_personal);
mTabSearch = (RadioButton) findViewById(R.id.tab_search);
//view
mTabCommunity.setOnClickListener(this);
mTabLibrary.setOnClickListener(this);
mTabSearch.setOnClickListener(this);
mTabPersonal.setOnClickListener(this);
//初始化主界面4个fragment
mFragmentList = new ArrayList<>();
mCommunityFragment = new CommunityFragment();
mLibraryFragment = new LibraryFragment();
mSearchFragment = new SearchFragment();
mPersonalFragment = new PersonalFragment();
mFragmentList.add(mCommunityFragment);
mFragmentList.add(mLibraryFragment);
mFragmentList.add(mSearchFragment);
mFragmentList.add(mPersonalFragment);
View updateView = LayoutInflater.from(this).inflate(R.layout.update_dialog, null, false);
mUpdate = DialogCreator.createNormalDialog(this, updateView, DialogCreator.Position.CENTER);
mText = (TextView) updateView.findViewById(R.id.title_text);
mCancel = (Button) updateView.findViewById(R.id.cancel);
mConfirm = (Button) updateView.findViewById(R.id.confirm);
//显示更新对话框
// mUpdate.show();
//初始化主界面的ViewPagerAdapter
mPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList);
//使主界面的ViewPager不销毁、不重建
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(mPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
handlePageChange(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
/**
* 处理ViewPager换页,ui元素变化,如appBar和tabBar
*
* @param index 页面索引号
*/
private void handlePageChange(int index) {
switch (index) {
case TAB_COMMUNITY:
mTabCommunity.setChecked(true);
break;
case TAB_LIBRARY:
mTabLibrary.setChecked(true);
break;
case TAB_SEARCH:
mTabSearch.setChecked(true);
break;
case TAB_PERSONAL:
mTabPersonal.setChecked(true);
break;
default:
break;
}
}
@Override
public void onClick(View v) {
int currentPage = mViewPager.getCurrentItem();
switch (v.getId()) {
case R.id.tab_community:
if (currentPage == TAB_COMMUNITY) {
mCommunityFragment.onNotify();
}
mViewPager.setCurrentItem(TAB_COMMUNITY);
break;
case R.id.tab_library:
mViewPager.setCurrentItem(TAB_LIBRARY);
break;
case R.id.tab_search:
mViewPager.setCurrentItem(TAB_SEARCH);
break;
case R.id.tab_personal:
if (currentPage == TAB_PERSONAL) {
mPersonalFragment.onNotify();
}
mViewPager.setCurrentItem(TAB_PERSONAL);
break;
default:
break;
}
}
/**
* 主界面ViewPager的Adapter
*/
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
List<Fragment> fragments;
public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments == null ? 0 : fragments.size();
}
}
@Override
public void onBackPressed() {
long current = System.currentTimeMillis();
if (current - mLastClickBack > 2 * 1000) {
mLastClickBack = System.currentTimeMillis();
Toast.makeText(MainActivity.this, "再按一次返回键退出程序", Toast.LENGTH_SHORT).show();
return;
}
super.onBackPressed();
}
}
| apache-2.0 |
AtividadesSenac/AppDespesas | app/src/main/java/View/MainActivity.java | 3673 | package view;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import milton.appdespesas.R;
public class MainActivity extends AppCompatActivity {
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private EditText editTextDtInicio, editTextDtFinal;
private int year, yearFinal, month, monthFinal, day, dayFinal;
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2 + 1, arg3);
}
};
private DatePickerDialog.OnDateSetListener myDateListener2 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDateFinal(arg1, arg2 + 1, arg3);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
yearFinal = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
monthFinal = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
dayFinal = calendar.get(Calendar.DAY_OF_MONTH);
editTextDtInicio = (EditText) findViewById(R.id.editTextDtInicio);
editTextDtFinal = (EditText) findViewById(R.id.editTextDtFinal);
showDate(year, month + 1, day);
showDateFinal(yearFinal, monthFinal, dayFinal);
}
@SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
.show();
}
@SuppressWarnings("deprecation")
public void setDateFinal(View view) {
showDialog(002);
Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT)
.show();
}
@Override
@SuppressWarnings("deprecation")
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
if (id == 002) {
return new DatePickerDialog(this, myDateListener2, yearFinal, monthFinal, dayFinal);
}
return null;
}
private void showDate(int year, int month, int day) {
editTextDtInicio.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
private void showDateFinal(int year, int month, int day) {
editTextDtFinal.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
// return true;
// }
} | apache-2.0 |
fSergio101/orchextra-android-sdk | orchextrasdk/src/main/java/com/gigigo/orchextra/delegates/SaveUserDelegateImpl.java | 1696 | /*
* Created by Orchextra
*
* Copyright (C) 2016 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.delegates;
import com.gigigo.ggglogger.GGGLogImpl;
import com.gigigo.ggglogger.LogLevel;
import com.gigigo.orchextra.control.controllers.authentication.SaveUserController;
import com.gigigo.orchextra.control.controllers.authentication.SaveUserDelegate;
import com.gigigo.orchextra.domain.model.entities.authentication.Crm;
public class SaveUserDelegateImpl implements SaveUserDelegate {
private final SaveUserController saveUserController;
public SaveUserDelegateImpl(SaveUserController saveUserController) {
this.saveUserController = saveUserController;
}
@Override public void init() {
saveUserController.attachView(this);
}
@Override public void destroy() {
saveUserController.detachView();
}
@Override public void saveUserSuccessful() {
destroy();
}
@Override public void saveUserError() {
GGGLogImpl.log("Save user was not successful", LogLevel.ERROR);
destroy();
}
@Override
public void saveUser(Crm crm) {
init();
saveUserController.saveUser(crm);
}
}
| apache-2.0 |
wayhap/WASample | src/cn/way/wandroid/views/ScratchViewFragment.java | 1525 | package cn.way.wandroid.views;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import cn.way.wandroid.R;
import cn.way.wandroid.views.WScratchView.ProgressListener;
/**
* @author Wayne
* @2015年4月30日
*/
public class ScratchViewFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent data = new Intent("RESULT");
data.putExtra("p1", "i am p1");
getActivity().setResult(2001, data);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_scratchview, container,false);
final WScratchView scratchView = (WScratchView) view.findViewById(R.id.scratchView);
scratchView.setResultText("谢谢惠顾");
Bitmap coverBitmap =
BitmapFactory.decodeResource(getResources(), R.drawable.empty_photo);
scratchView.setCoverBitmap(coverBitmap);
scratchView.setProgressListener(new ProgressListener() {
@Override
public void onProgressChanged(float progress) {
if (progress>=0.5) {
scratchView.clear();
}
}
});
view.findViewById(R.id.resetBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
scratchView.reset();
}
});
return view;
}
}
| apache-2.0 |
gustavoanatoly/hbase | hbase-rest/src/test/java/org/apache/hadoop/hbase/rest/TestScannersWithLabels.java | 10165 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.rest;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse;
import org.apache.hadoop.hbase.rest.client.Client;
import org.apache.hadoop.hbase.rest.client.Cluster;
import org.apache.hadoop.hbase.rest.client.Response;
import org.apache.hadoop.hbase.rest.model.CellModel;
import org.apache.hadoop.hbase.rest.model.CellSetModel;
import org.apache.hadoop.hbase.rest.model.RowModel;
import org.apache.hadoop.hbase.rest.model.ScannerModel;
import org.apache.hadoop.hbase.security.User;
import org.apache.hadoop.hbase.security.visibility.CellVisibility;
import org.apache.hadoop.hbase.security.visibility.ScanLabelGenerator;
import org.apache.hadoop.hbase.security.visibility.SimpleScanLabelGenerator;
import org.apache.hadoop.hbase.security.visibility.VisibilityClient;
import org.apache.hadoop.hbase.security.visibility.VisibilityConstants;
import org.apache.hadoop.hbase.security.visibility.VisibilityController;
import org.apache.hadoop.hbase.security.visibility.VisibilityUtils;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.testclassification.RestTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@Category({RestTests.class, MediumTests.class})
public class TestScannersWithLabels {
private static final TableName TABLE = TableName.valueOf("TestScannersWithLabels");
private static final String CFA = "a";
private static final String CFB = "b";
private static final String COLUMN_1 = CFA + ":1";
private static final String COLUMN_2 = CFB + ":2";
private final static String TOPSECRET = "topsecret";
private final static String PUBLIC = "public";
private final static String PRIVATE = "private";
private final static String CONFIDENTIAL = "confidential";
private final static String SECRET = "secret";
private static User SUPERUSER;
private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
private static final HBaseRESTTestingUtility REST_TEST_UTIL = new HBaseRESTTestingUtility();
private static Client client;
private static JAXBContext context;
private static Marshaller marshaller;
private static Unmarshaller unmarshaller;
private static Configuration conf;
private static int insertData(TableName tableName, String column, double prob) throws IOException {
byte[] k = new byte[3];
byte[][] famAndQf = KeyValue.parseColumn(Bytes.toBytes(column));
List<Put> puts = new ArrayList<>(9);
for (int i = 0; i < 9; i++) {
Put put = new Put(Bytes.toBytes("row" + i));
put.setDurability(Durability.SKIP_WAL);
put.addColumn(famAndQf[0], famAndQf[1], k);
put.setCellVisibility(new CellVisibility("(" + SECRET + "|" + CONFIDENTIAL + ")" + "&" + "!"
+ TOPSECRET));
puts.add(put);
}
try (Table table = TEST_UTIL.getConnection().getTable(tableName)) {
table.put(puts);
}
return puts.size();
}
private static int countCellSet(CellSetModel model) {
int count = 0;
Iterator<RowModel> rows = model.getRows().iterator();
while (rows.hasNext()) {
RowModel row = rows.next();
Iterator<CellModel> cells = row.getCells().iterator();
while (cells.hasNext()) {
cells.next();
count++;
}
}
return count;
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
SUPERUSER = User.createUserForTesting(conf, "admin",
new String[] { "supergroup" });
conf = TEST_UTIL.getConfiguration();
conf.setClass(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS,
SimpleScanLabelGenerator.class, ScanLabelGenerator.class);
conf.setInt("hfile.format.version", 3);
conf.set("hbase.superuser", SUPERUSER.getShortName());
conf.set("hbase.coprocessor.master.classes", VisibilityController.class.getName());
conf.set("hbase.coprocessor.region.classes", VisibilityController.class.getName());
TEST_UTIL.startMiniCluster(1);
// Wait for the labels table to become available
TEST_UTIL.waitTableEnabled(VisibilityConstants.LABELS_TABLE_NAME.getName(), 50000);
createLabels();
setAuths();
REST_TEST_UTIL.startServletContainer(conf);
client = new Client(new Cluster().add("localhost", REST_TEST_UTIL.getServletPort()));
context = JAXBContext.newInstance(CellModel.class, CellSetModel.class, RowModel.class,
ScannerModel.class);
marshaller = context.createMarshaller();
unmarshaller = context.createUnmarshaller();
Admin admin = TEST_UTIL.getAdmin();
if (admin.tableExists(TABLE)) {
return;
}
HTableDescriptor htd = new HTableDescriptor(TABLE);
htd.addFamily(new HColumnDescriptor(CFA));
htd.addFamily(new HColumnDescriptor(CFB));
admin.createTable(htd);
insertData(TABLE, COLUMN_1, 1.0);
insertData(TABLE, COLUMN_2, 0.5);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
REST_TEST_UTIL.shutdownServletContainer();
TEST_UTIL.shutdownMiniCluster();
}
private static void createLabels() throws IOException, InterruptedException {
PrivilegedExceptionAction<VisibilityLabelsResponse> action = new PrivilegedExceptionAction<VisibilityLabelsResponse>() {
public VisibilityLabelsResponse run() throws Exception {
String[] labels = { SECRET, CONFIDENTIAL, PRIVATE, PUBLIC, TOPSECRET };
try (Connection conn = ConnectionFactory.createConnection(conf)) {
VisibilityClient.addLabels(conn, labels);
} catch (Throwable t) {
throw new IOException(t);
}
return null;
}
};
SUPERUSER.runAs(action);
}
private static void setAuths() throws Exception {
String[] labels = { SECRET, CONFIDENTIAL, PRIVATE, PUBLIC, TOPSECRET };
try (Connection conn = ConnectionFactory.createConnection(conf)) {
VisibilityClient.setAuths(conn, labels, User.getCurrent().getShortName());
} catch (Throwable t) {
throw new IOException(t);
}
}
@Test
public void testSimpleScannerXMLWithLabelsThatReceivesNoData() throws IOException, JAXBException {
final int BATCH_SIZE = 5;
// new scanner
ScannerModel model = new ScannerModel();
model.setBatch(BATCH_SIZE);
model.addColumn(Bytes.toBytes(COLUMN_1));
model.addLabel(PUBLIC);
StringWriter writer = new StringWriter();
marshaller.marshal(model, writer);
byte[] body = Bytes.toBytes(writer.toString());
// recall previous put operation with read-only off
conf.set("hbase.rest.readonly", "false");
Response response = client.put("/" + TABLE + "/scanner", Constants.MIMETYPE_XML, body);
assertEquals(response.getCode(), 201);
String scannerURI = response.getLocation();
assertNotNull(scannerURI);
// get a cell set
response = client.get(scannerURI, Constants.MIMETYPE_XML);
// Respond with 204 as there are no cells to be retrieved
assertEquals(response.getCode(), 204);
// With no content in the payload, the 'Content-Type' header is not echo back
}
@Test
public void testSimpleScannerXMLWithLabelsThatReceivesData() throws IOException, JAXBException {
// new scanner
ScannerModel model = new ScannerModel();
model.setBatch(5);
model.addColumn(Bytes.toBytes(COLUMN_1));
model.addLabel(SECRET);
StringWriter writer = new StringWriter();
marshaller.marshal(model, writer);
byte[] body = Bytes.toBytes(writer.toString());
// recall previous put operation with read-only off
conf.set("hbase.rest.readonly", "false");
Response response = client.put("/" + TABLE + "/scanner", Constants.MIMETYPE_XML, body);
assertEquals(response.getCode(), 201);
String scannerURI = response.getLocation();
assertNotNull(scannerURI);
// get a cell set
response = client.get(scannerURI, Constants.MIMETYPE_XML);
// Respond with 204 as there are no cells to be retrieved
assertEquals(response.getCode(), 200);
assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
CellSetModel cellSet = (CellSetModel) unmarshaller.unmarshal(new ByteArrayInputStream(response
.getBody()));
assertEquals(countCellSet(cellSet), 5);
}
}
| apache-2.0 |
hardlove/AS-MyProject | MyProject/map/src/main/java/com/future/map/gaode/utils/LocationClientManager.java | 6836 | package com.future.map.gaode.utils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Created by Chenlu on 2016/8/23 0023.
*/
public class LocationClientManager implements AMapLocationListener{
private static final String TAG = "LocationClientManager";
private AMapLocationClient mlocationClient;
private AMapLocationClientOption mLocationOption;
private Context mContext;
private List<OnLocationChangeCallBack> mCallBacks;
private static LocationClientManager instance;
private boolean isStart;
public static LocationClientManager getInstance(Context context) {
synchronized (TAG) {
if (instance == null) {
synchronized (TAG) {
if (instance == null) {
instance = new LocationClientManager(context);
return instance;
}
}
}
}
return instance;
}
private LocationClientManager(Context context) {
mContext = context.getApplicationContext();
mCallBacks = new ArrayList<>();
String sha1 = getSHA1(context);
Log.i(TAG, "sha11~~ :" + sha1);
init();
}
public interface OnLocationChangeCallBack{
void succeed(AMapLocation aMapLocation);
void failed(int errorCode, String errorInfo);
}
public void registerOnLocationChangeCallBack(OnLocationChangeCallBack onLocationChangeCallBack) {
if (onLocationChangeCallBack != null && !mCallBacks.contains(onLocationChangeCallBack)) {
mCallBacks.add(onLocationChangeCallBack);
synchronized (this) {
if (!isStart) {
//启动定位
mlocationClient.startLocation();
isStart = true;
}
}
}
}
public void unRegisterOnLocationChangeCallBack(OnLocationChangeCallBack onLocationChangeCallBack) {
if (mCallBacks.contains(onLocationChangeCallBack)) {
mCallBacks.remove(onLocationChangeCallBack);
synchronized (this) {
if (mCallBacks.size() == 0) {
//停止定位
mlocationClient.stopLocation();
isStart = false;
}
}
}
}
private void init() {
mlocationClient = new AMapLocationClient(mContext);
mLocationOption = new AMapLocationClientOption();
//设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
mLocationOption.setInterval(2000);
//设置返回地址信息,默认为true
mLocationOption.setNeedAddress(true);
//设置定位参数
mlocationClient.setLocationOption(mLocationOption);
mlocationClient.setLocationListener(this);
}
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
if (aMapLocation != null) {
if (aMapLocation.getErrorCode() == 0) {
//定位成功回调信息,设置相关消息
aMapLocation.getLocationType();//获取当前定位结果来源,如网络定位结果,详见定位类型表
aMapLocation.getLatitude();//获取纬度
aMapLocation.getLongitude();//获取经度
aMapLocation.getAccuracy();//获取精度信息
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(aMapLocation.getTime());
df.format(date);//定位时间
aMapLocation.getAddress();//地址,如果option中设置isNeedAddress为false,则没有此结果,网络定位结果中会有地址信息,GPS定位不返回地址信息。
aMapLocation.getCountry();//国家信息
aMapLocation.getProvince();//省信息
aMapLocation.getCity();//城市信息
aMapLocation.getDistrict();//城区信息
aMapLocation.getStreet();//街道信息
aMapLocation.getStreetNum();//街道门牌号信息
aMapLocation.getCityCode();//城市编码
aMapLocation.getAdCode();//地区编码
aMapLocation.getAoiName();//获取当前定位点的AOI信息
for (int i = 0; i < mCallBacks.size(); i++) {
mCallBacks.get(i).succeed(aMapLocation);
}
} else {
//显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。
int errorCode = aMapLocation.getErrorCode();
String errorInfo = aMapLocation.getErrorInfo();
Log.e("AmapError","location Error, ErrCode:" + errorCode + ", errInfo:" + errorInfo);
for (int i = 0; i < mCallBacks.size(); i++) {
mCallBacks.get(i).failed(errorCode, errorInfo);
}
}
}
}
public static String getSHA1(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
context.getPackageName(), PackageManager.GET_SIGNATURES);
byte[] cert = info.signatures[0].toByteArray();
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] publicKey = md.digest(cert);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < publicKey.length; i++) {
String appendString = Integer.toHexString(0xFF & publicKey[i])
.toUpperCase(Locale.US);
if (appendString.length() == 1)
hexString.append("0");
hexString.append(appendString);
hexString.append(":");
}
String result = hexString.toString();
return result.substring(0, result.length()-1);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
}
| apache-2.0 |
ceylon/ceylon | tools/src/org/eclipse/ceylon/tools/new_/Environment.java | 1007 | /********************************************************************************
* Copyright (c) 2011-2017 Red Hat Inc. and/or its affiliates and others
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/
package org.eclipse.ceylon.tools.new_;
import java.util.HashMap;
import java.util.Map;
public class Environment {
private Map<String, String> map = new HashMap<String, String>();
public String get(String key) {
return map.get(key);
}
public void put(String key, String value) {
if (key == null || value == null) {
throw new IllegalArgumentException();
}
map.put(key, value);
}
public String toString() {
return map.toString();
}
}
| apache-2.0 |
socialsensor/socialmedia-abstractions | src/main/java/eu/socialsensor/framework/retrievers/socialmedia/TopsyRetriever.java | 3846 | package eu.socialsensor.framework.retrievers.socialmedia;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
//import com.maruti.otterapi.Otter4JavaException;
//import com.maruti.otterapi.TopsyConfig;
//import com.maruti.otterapi.search.Post;
//import com.maruti.otterapi.search.Search;
//import com.maruti.otterapi.search.SearchCriteria;
//import com.maruti.otterapi.search.SearchResponse;
import eu.socialsensor.framework.common.domain.Feed;
import eu.socialsensor.framework.common.domain.Item;
import eu.socialsensor.framework.common.domain.MediaItem;
import eu.socialsensor.framework.common.domain.StreamUser;
import eu.socialsensor.framework.common.domain.feeds.KeywordsFeed;
import eu.socialsensor.framework.common.domain.feeds.ListFeed;
import eu.socialsensor.framework.common.domain.feeds.LocationFeed;
import eu.socialsensor.framework.common.domain.feeds.SourceFeed;
/**
* Class responsible for retrieving Topsy image content based on keywords
* The retrieval process takes place through Topsy API.
* @author ailiakop
* @email ailiakop@iti.gr
*/
public class TopsyRetriever implements SocialMediaRetriever{
private Logger logger = Logger.getLogger(TopsyRetriever.class);
//private TopsyConfig topsyConfig;
public TopsyRetriever(String apiKey) {
//topsyConfig = new TopsyConfig();
//topsyConfig.setApiKey(apiKey);
//topsyConfig.setSetProxy(false);
}
@Override
public List<Item> retrieveUserFeeds(SourceFeed feed){
return new ArrayList<Item>();
}
@Override
public List<Item> retrieveKeywordsFeeds(KeywordsFeed feed){
List<Item> items = new ArrayList<Item>();
/*
Date dateToRetrieve = feed.getDateToRetrieve();
//SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
Search searchTopsy = new Search();
searchTopsy.setTopsyConfig(topsyConfig);
SearchResponse results = null;
try {
SearchCriteria criteria = new SearchCriteria();
criteria.setQuery(feed.getKeyword().getName());
criteria.setType("image");
results = searchTopsy.search(criteria);
List<Post> posts = results.getResult().getList();
for(Post post : posts){
String since = post.getFirstpost_date();
if(since != null) {
Long publicationDate = Long.parseLong(since) * 1000;
if(publicationDate > dateToRetrieve.getTime()) {
TopsyItem topsyItem = new TopsyItem(post);
items.add(topsyItem);
}
}
}
} catch (Otter4JavaException e) {
e.printStackTrace();
}
*/
return items;
}
@Override
public List<Item> retrieveLocationFeeds(LocationFeed feed){
return new ArrayList<Item>();
}
@Override
public List<Item> retrieveListsFeeds(ListFeed feed) {
return new ArrayList<Item>();
}
@Override
public List<Item> retrieve (Feed feed) {
switch(feed.getFeedtype()) {
case SOURCE:
SourceFeed userFeed = (SourceFeed) feed;
return retrieveUserFeeds(userFeed);
case KEYWORDS:
KeywordsFeed keyFeed = (KeywordsFeed) feed;
return retrieveKeywordsFeeds(keyFeed);
case LOCATION:
LocationFeed locationFeed = (LocationFeed) feed;
return retrieveLocationFeeds(locationFeed);
case LIST:
ListFeed listFeed = (ListFeed) feed;
return retrieveListsFeeds(listFeed);
default:
logger.error("Unkonwn Feed Type: " + feed.toJSONString());
break;
}
return new ArrayList<Item>();
}
@Override
public void stop(){
}
@Override
public MediaItem getMediaItem(String id) {
// TODO Auto-generated method stub
return null;
}
@Override
public StreamUser getStreamUser(String uid) {
// TODO Auto-generated method stub
return null;
}
}
| apache-2.0 |
DigitalAssetCom/hlp-candidate | server/core/src/test/java/org/hyperledger/core/bitcoin/PersistentBlocksTest.java | 8819 | /**
* 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.hyperledger.core.bitcoin;
import org.hyperledger.common.*;
import org.hyperledger.core.PersistentBlocks;
import org.hyperledger.core.StoredBlock;
import org.hyperledger.core.StoredHeader;
import org.hyperledger.core.StoredTransaction;
import org.hyperledger.core.kvstore.LevelDBStore;
import org.hyperledger.core.kvstore.MemoryStore;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import static org.junit.Assert.assertTrue;
public class PersistentBlocksTest {
private StoredBlock readBlock(String blockfile) throws IOException, HyperLedgerException {
Reader reader = new InputStreamReader(this.getClass().getResource("/" + blockfile).openStream());
char[] buff = new char[1024];
StringBuilder result = new StringBuilder();
int len;
while ((len = reader.read(buff)) > 0)
result.append(buff, 0, len);
Block b = Block.fromWireDump(result.toString(), WireFormatter.bitcoin, BitcoinHeader.class);
List<StoredTransaction> storedTxList = new ArrayList<>();
for (Transaction t : b.getTransactions()) {
storedTxList.add(new StoredTransaction(t, 0));
}
return new StoredBlock(new StoredHeader(b.getHeader(), 0.0, 0), storedTxList);
}
@Test
public void memtest() throws IOException, HyperLedgerException {
MemoryStore memstore = new MemoryStore();
PersistentBlocks blocks = new BitcoinPersistentBlocks(memstore);
StoredBlock b1 = readBlock("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9.hexblock");
blocks.writeBlock(b1);
StoredBlock b2 = readBlock("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9.hexblock");
blocks.writeBlock(b2);
assertTrue(blocks.hasBlock(new BID("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9")));
assertTrue(blocks.hasTransaction(new TID("df39000a50d3d115cee18ab7ad1a65f0b1f012e5c58cc248ba325392b174201b")));
blocks.readBlock(new BID("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9"));
int spentOutputs = 0;
for (Transaction t : b1.getTransactions()) {
for (Coin o : t.getCoins()) {
Set<StoredTransaction> spendingTransaction = blocks.getSpendingTransactions(o.getOutpoint());
if (!spendingTransaction.isEmpty()) {
++spentOutputs;
}
}
}
assertTrue(spentOutputs == 1158);
int nUses = 0;
for (Transaction t : b2.getTransactions()) {
for (TransactionOutput o : t.getOutputs()) {
Address a = o.getOutputAddress();
if (a != null)
nUses += blocks.getTransactionsWithOutput(a.getAddressScript()).size();
}
}
assert (nUses == 28533);
}
@Test
public void diskTest1() throws IOException, HyperLedgerException {
LevelDBStore diskstore = new LevelDBStore("/tmp/" + UUID.randomUUID(), 100);
diskstore.open();
diskstore.startBatch();
PersistentBlocks blocks = new BitcoinPersistentBlocks(diskstore);
StoredBlock b1 = readBlock("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9.hexblock");
blocks.writeBlock(b1);
StoredBlock b2 = readBlock("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9.hexblock");
blocks.writeBlock(b2);
diskstore.endBatch();
assertTrue(blocks.hasBlock(new BID("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9")));
assertTrue(blocks.hasTransaction(new TID("df39000a50d3d115cee18ab7ad1a65f0b1f012e5c58cc248ba325392b174201b")));
blocks.readBlock(new BID("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9"));
int spentOutputs = 0;
for (Transaction t : b1.getTransactions()) {
for (Coin o : t.getCoins()) {
Set<StoredTransaction> spendingTransaction = blocks.getSpendingTransactions(o.getOutpoint());
if (!spendingTransaction.isEmpty()) {
++spentOutputs;
}
}
}
assertTrue(spentOutputs == 1158);
int nUses = 0;
for (Transaction t : b2.getTransactions()) {
for (TransactionOutput o : t.getOutputs()) {
Address a = o.getOutputAddress();
if (a != null)
nUses += blocks.getTransactionsWithOutput(a.getAddressScript()).size();
}
}
assert (nUses == 28533);
diskstore.close();
}
@Test
public void diskTest2() throws IOException, HyperLedgerException {
LevelDBStore diskstore = new LevelDBStore("/tmp/" + UUID.randomUUID(), 100);
diskstore.open();
diskstore.startBatch();
PersistentBlocks blocks = new BitcoinPersistentBlocks(diskstore);
StoredBlock b1 = readBlock("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9.hexblock");
blocks.writeBlock(b1);
StoredBlock b2 = readBlock("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9.hexblock");
blocks.writeBlock(b2);
assertTrue(blocks.hasBlock(new BID("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9")));
assertTrue(blocks.hasTransaction(new TID("df39000a50d3d115cee18ab7ad1a65f0b1f012e5c58cc248ba325392b174201b")));
blocks.readBlock(new BID("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9"));
int spentOutputs = 0;
for (Transaction t : b1.getTransactions()) {
for (Coin o : t.getCoins()) {
Set<StoredTransaction> spendingTransaction = blocks.getSpendingTransactions(o.getOutpoint());
if (!spendingTransaction.isEmpty()) {
++spentOutputs;
}
}
}
assertTrue(spentOutputs == 1158);
int nUses = 0;
for (Transaction t : b2.getTransactions()) {
for (TransactionOutput o : t.getOutputs()) {
Address a = o.getOutputAddress();
if (a != null)
nUses += blocks.getTransactionsWithOutput(a.getAddressScript()).size();
}
}
assert (nUses == 28533);
diskstore.endBatch();
diskstore.close();
}
@Test
public void diskTest3() throws IOException, HyperLedgerException {
LevelDBStore diskstore = new LevelDBStore("/tmp/" + UUID.randomUUID(), 100);
diskstore.open();
PersistentBlocks blocks = new BitcoinPersistentBlocks(diskstore);
StoredBlock b1 = readBlock("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9.hexblock");
blocks.writeBlock(b1);
StoredBlock b2 = readBlock("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9.hexblock");
blocks.writeBlock(b2);
assertTrue(blocks.hasBlock(new BID("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9")));
assertTrue(blocks.hasTransaction(new TID("df39000a50d3d115cee18ab7ad1a65f0b1f012e5c58cc248ba325392b174201b")));
blocks.readBlock(new BID("000000000000000001f942eb4bfa0aeccb6a14c268f4c72d5fff17270da771b9"));
int spentOutputs = 0;
for (Transaction t : b1.getTransactions()) {
for (Coin o : t.getCoins()) {
Set<StoredTransaction> spendingTransaction = blocks.getSpendingTransactions(o.getOutpoint());
if (!spendingTransaction.isEmpty()) {
++spentOutputs;
}
}
}
assertTrue(spentOutputs == 1158);
int nUses = 0;
for (Transaction t : b2.getTransactions()) {
for (TransactionOutput o : t.getOutputs()) {
Address a = o.getOutputAddress();
if (a != null)
nUses += blocks.getTransactionsWithOutput(a.getAddressScript()).size();
}
}
assert (nUses == 28533);
diskstore.close();
}
}
| apache-2.0 |
juebanlin/util4j | util4j/src/test/java/net/jueb/util4j/beta/tools/image/CutImage.java | 7153 | package net.jueb.util4j.beta.tools.image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
//import com.langhua.ImageUtils.ImageUtils;
public class CutImage {
// 源图片路径名称如:c:\1.jpg
private String srcpath;
// 剪切图片存放路径名称.如:c:\2.jpg
private String subpath;
// 剪切点x坐标
private int x;
private int y;
// 剪切点宽度
private int width;
private int height;
public CutImage() {
}
public CutImage(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
/**
* 对图片裁剪,并把裁剪完蛋新图片保存 。
*/
public void cut() throws IOException {
FileInputStream is = null;
ImageInputStream iis = null;
try {
// 读取图片文件
is = new FileInputStream(srcpath);
/**
* 返回包含所有当前已注册 ImageReader 的 Iterator,这些 ImageReader 声称能够解码指定格式。
* 参数:formatName - 包含非正式格式名称 . (例如 "jpeg" 或 "tiff")等 。
*/
Iterator<ImageReader> it = ImageIO
.getImageReadersByFormatName("jpg");
ImageReader reader = it.next();
// 获取图片流
iis = ImageIO.createImageInputStream(is);
/**
* iis:读取源.true:只向前搜索.将它标记为 ‘只向前搜索’。 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许
* reader 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。
*/
reader.setInput(iis, true);
/**
* <p>
* 描述如何对流进行解码的类
* <p>
* .用于指定如何在输入时从 Java Image I/O 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 将从其
* ImageReader 实现的 getDefaultReadParam 方法中返回 ImageReadParam 的实例。
*/
ImageReadParam param = reader.getDefaultReadParam();
/**
* 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域,通过 Rectangle 对象
* 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。
*/
Rectangle rect = new Rectangle(x, y, width, height);
// 提供一个 BufferedImage,将其用作解码像素数据的目标。
param.setSourceRegion(rect);
/**
* 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象,并将 它作为一个完整的
* BufferedImage 返回。
*/
BufferedImage bi = reader.read(0, param);
// 保存新图片
ImageIO.write(bi, "jpg", new File(subpath));
} finally {
if (is != null)
is.close();
if (iis != null)
iis.close();
}
}
/**
* 图像切割
*
* @param srcImageFile
* 源图像地址
* @param descDir
* 切片目标文件夹
* @param destWidth
* 目标切片宽度
* @param destHeight
* 目标切片高度 返回一个List,保存九张图片的图片名
*/
public static java.util.List<String> cutImg(String srcImageFile,
String descDir, int destWidth, int destHeight) {
java.util.List<String> list = new java.util.ArrayList<String>(9);
try {
String dir = null;
// 读取源图像
BufferedImage bi = ImageIO.read(new File(srcImageFile));
int srcWidth = bi.getHeight(); // 源图宽度
int srcHeight = bi.getWidth(); // 源图高度
if (srcWidth > destWidth && srcHeight > destHeight) {
destWidth = 300; // 切片宽度
destHeight = 300; // 切片高度
int cols = 0; // 切片横向数量
int rows = 0; // 切片纵向数量
// 计算切片的横向和纵向数量
if (srcWidth % destWidth == 0) {
cols = srcWidth / destWidth;
} else {
cols = (int) Math.floor(srcWidth / destWidth) + 1;
}
if (srcHeight % destHeight == 0) {
rows = srcHeight / destHeight;
} else {
rows = (int) Math.floor(srcHeight / destHeight) + 1;
}
// 循环建立切片
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
CutImage cutImage = new CutImage(j * 300, i * 300, 300,
300);
cutImage.setSrcpath(srcImageFile);
dir = descDir + "cut_image_" + i + "_" + j + ".jpg";
cutImage.setSubpath(dir);
cutImage.cut();
list.add("cut_image_" + i + "_" + j + ".jpg");
//ImageUtils.pressText("水印", dir, "宋体", 1, 1, 25, 10, 10);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getSrcpath() {
return srcpath;
}
public void setSrcpath(String srcpath) {
this.srcpath = srcpath;
}
public String getSubpath() {
return subpath;
}
public void setSubpath(String subpath) {
this.subpath = subpath;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
| apache-2.0 |
icza/scelight | src-app/hu/scelight/sc2/rep/model/messageevents/MsgEvent.java | 1156 | /*
* Project Scelight
*
* Copyright (c) 2013 Andras Belicza <iczaaa@gmail.com>
*
* This software is the property of Andras Belicza.
* Copying, modifying, distributing, refactoring without the author's permission
* is prohibited and protected by Law.
*/
package hu.scelight.sc2.rep.model.messageevents;
import hu.scelight.sc2.rep.s2prot.Event;
import hu.scelightapi.sc2.rep.model.messageevents.IMsgEvent;
import java.util.Map;
/**
* General message event.
*
* @author Andras Belicza
*/
public class MsgEvent extends Event implements IMsgEvent {
/**
* Creates a new {@link MsgEvent}.
*
* @param struct event data structure
* @param id id of the event
* @param name type name of the event
* @param loop game loop when the event occurred
* @param userId user id causing the event
*/
public MsgEvent( final Map< String, Object > struct, final int id, final String name, final int loop, final int userId ) {
super( struct, id, name, loop, userId );
}
@Override
public Recipient getRecipient() {
return Recipient.fromRawValue( this.< Integer > get( F_RECIPIENT ) );
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-location/src/main/java/com/amazonaws/services/location/model/transform/SearchPlaceIndexForTextRequestMarshaller.java | 4061 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.location.model.transform;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.location.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* SearchPlaceIndexForTextRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class SearchPlaceIndexForTextRequestMarshaller {
private static final MarshallingInfo<List> BIASPOSITION_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("BiasPosition").build();
private static final MarshallingInfo<List> FILTERBBOX_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("FilterBBox").build();
private static final MarshallingInfo<List> FILTERCOUNTRIES_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("FilterCountries").build();
private static final MarshallingInfo<String> INDEXNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH)
.marshallLocationName("IndexName").build();
private static final MarshallingInfo<String> LANGUAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Language").build();
private static final MarshallingInfo<Integer> MAXRESULTS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MaxResults").build();
private static final MarshallingInfo<String> TEXT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Text").build();
private static final SearchPlaceIndexForTextRequestMarshaller instance = new SearchPlaceIndexForTextRequestMarshaller();
public static SearchPlaceIndexForTextRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(SearchPlaceIndexForTextRequest searchPlaceIndexForTextRequest, ProtocolMarshaller protocolMarshaller) {
if (searchPlaceIndexForTextRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(searchPlaceIndexForTextRequest.getBiasPosition(), BIASPOSITION_BINDING);
protocolMarshaller.marshall(searchPlaceIndexForTextRequest.getFilterBBox(), FILTERBBOX_BINDING);
protocolMarshaller.marshall(searchPlaceIndexForTextRequest.getFilterCountries(), FILTERCOUNTRIES_BINDING);
protocolMarshaller.marshall(searchPlaceIndexForTextRequest.getIndexName(), INDEXNAME_BINDING);
protocolMarshaller.marshall(searchPlaceIndexForTextRequest.getLanguage(), LANGUAGE_BINDING);
protocolMarshaller.marshall(searchPlaceIndexForTextRequest.getMaxResults(), MAXRESULTS_BINDING);
protocolMarshaller.marshall(searchPlaceIndexForTextRequest.getText(), TEXT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
jspare-projects/jspare-container | jspare-core/src/test/java/org/jspare/core/helpers/Bar.java | 715 | /*
* Copyright 2016 JSpare.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.jspare.core.helpers;
public class Bar {
public int maxIntegerValue() {
return Integer.MAX_VALUE;
}
}
| apache-2.0 |
chao4kakaluote/Music | app/src/test/java/com/example/administrator/music/ExampleUnitTest.java | 409 | package com.example.administrator.music;
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 |
jnuyanfa/YanFa-LeetCode-with-JAVA | src/leetcode007_ReserseInteger/LeetCode_007_ReverseInteger.java | 1712 | import org.junit.Test;
import javax.sound.midi.Soundbank;
public class LeetCode_007_ReverseInteger
{
// public int reverse(int x)
// {
// boolean flag = true;
// if(x == Integer.MIN_VALUE)
// return 0;
// if(x < -9)
// {
// flag = false;
// x = Math.abs(x);
// }
// else if(x < 10)
// return x;
//
// while(x%10==0)
// x /= 10;
//
// String s = String.valueOf(x);
// char[] s_char = s.toCharArray();
//
// StringBuilder stringBuilder = new StringBuilder();
// for(int i = s_char.length-1; i>=0; i--)
// {
// stringBuilder.append(s_char[i]);
// }
//
// long tmp = Long.parseLong(stringBuilder.toString());
// if(tmp > Integer.MAX_VALUE)
// x = 0;
// else
// x = (int)tmp;
//
// return flag?x:0-x;
// }
public int reverse(int x)
{
if(x > -10 && x < 10) //一位数直接返回
return x;
if(x == Integer.MIN_VALUE) //特殊,这个值求绝对值还是它自身,原因为它求绝对值会发生正溢出
return 0;
int flag = x > 0 ? 1 : -1; //记录下符号
x = Math.abs(x);
long result = 0;
while(x != 0)
{
int tmp = x % 10;
result = result * 10 + tmp; //反转
x /= 10;
}
return result > Integer.MAX_VALUE ? 0 : flag * (int) result;
}
@Test
public void testReverse()
{
System.out.println(Integer.MIN_VALUE);
System.out.println(Integer.MAX_VALUE);
System.out.println(reverse(Integer.MIN_VALUE));
}
}
| apache-2.0 |
sao-albacete/aoa-migrator | src/main/java/org/sao/aoa/migrator/model/tables/CitaHistorico.java | 9205 | /**
* This class is generated by jOOQ
*/
package org.sao.aoa.migrator.model.tables;
import org.sao.aoa.migrator.model.AnuarioSchema;
import org.sao.aoa.migrator.model.tables.records.CitaHistoricoRecord;
/**
* This class is generated by jOOQ.
*
* Históricos de cita recopiladas
*/
@javax.annotation.Generated(value = { "http://www.jooq.org", "3.3.2" },
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class CitaHistorico extends org.jooq.impl.TableImpl<CitaHistoricoRecord> {
private static final long serialVersionUID = 305350526;
/**
* The singleton instance of <code>cita_historico</code>
*/
public static final CitaHistorico CITA_HISTORICO = new CitaHistorico();
/**
* The class holding records for this type
*/
@Override
public java.lang.Class<CitaHistoricoRecord> getRecordType() {
return CitaHistoricoRecord.class;
}
/**
* The column <code>cita_historico.id</code>. Identificador de la cita
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "Identificador de la cita");
/**
* The column <code>cita_historico.fechaHistorico</code>. Fecha de alta del registro histórico
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.sql.Timestamp> FECHAHISTORICO = createField("fechaHistorico", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "Fecha de alta del registro histórico");
/**
* The column <code>cita_historico.usuarioHistorico</code>. Usuario que realizó el cambio
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.String> USUARIOHISTORICO = createField("usuarioHistorico", org.jooq.impl.SQLDataType.VARCHAR.length(250).nullable(false), this, "Usuario que realizó el cambio");
/**
* The column <code>cita_historico.cita_id</code>. Id de cita
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> CITA_ID = createField("cita_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "Id de cita");
/**
* The column <code>cita_historico.fechaAlta</code>. Fecha de alta de la cita
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.sql.Timestamp> FECHAALTA = createField("fechaAlta", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, "Fecha de alta de la cita");
/**
* The column <code>cita_historico.cantidad</code>. Número de individuos de la especie citada
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> CANTIDAD = createField("cantidad", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "Número de individuos de la especie citada");
/**
* The column <code>cita_historico.observaciones</code>. Observaciones sobre la cita
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.String> OBSERVACIONES = createField("observaciones", org.jooq.impl.SQLDataType.CLOB.length(65535), this, "Observaciones sobre la cita");
/**
* The column <code>cita_historico.indSeleccionada</code>. Indica si la cita es seleccionada para el anuario (1) o no (0)
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Byte> INDSELECCIONADA = createField("indSeleccionada", org.jooq.impl.SQLDataType.TINYINT, this, "Indica si la cita es seleccionada para el anuario (1) o no (0)");
/**
* The column <code>cita_historico.lugar_id</code>. Identificador del lugar donde se produjo la cita
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> LUGAR_ID = createField("lugar_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "Identificador del lugar donde se produjo la cita");
/**
* The column <code>cita_historico.indRarezaHomologada</code>. Indica si la cita es de una rareza homologada (1) o no (0)
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> INDRAREZAHOMOLOGADA = createField("indRarezaHomologada", org.jooq.impl.SQLDataType.INTEGER, this, "Indica si la cita es de una rareza homologada (1) o no (0)");
/**
* The column <code>cita_historico.observador_principal_id</code>.
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> OBSERVADOR_PRINCIPAL_ID = createField("observador_principal_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>cita_historico.clase_reproduccion_id</code>.
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> CLASE_REPRODUCCION_ID = createField("clase_reproduccion_id", org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* The column <code>cita_historico.fuente_id</code>.
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> FUENTE_ID = createField("fuente_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>cita_historico.indHabitatRaro</code>. Indica si la cita fue en un habitat raro para la especie vista (1) o no (0)
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Byte> INDHABITATRARO = createField("indHabitatRaro", org.jooq.impl.SQLDataType.TINYINT, this, "Indica si la cita fue en un habitat raro para la especie vista (1) o no (0)");
/**
* The column <code>cita_historico.indCriaHabitatRaro</code>. Indica si la cita es de una especie criando en un habitat raro (1) o no (0)
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Byte> INDCRIAHABITATRARO = createField("indCriaHabitatRaro", org.jooq.impl.SQLDataType.TINYINT, this, "Indica si la cita es de una especie criando en un habitat raro (1) o no (0)");
/**
* The column <code>cita_historico.indHerido</code>. Indica si el individuo/s citado/s estaba/n herido/s (1) o no (0)
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Byte> INDHERIDO = createField("indHerido", org.jooq.impl.SQLDataType.TINYINT, this, "Indica si el individuo/s citado/s estaba/n herido/s (1) o no (0)");
/**
* The column <code>cita_historico.indComportamiento</code>. Descripción del comportamiento de la especie
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Byte> INDCOMPORTAMIENTO = createField("indComportamiento", org.jooq.impl.SQLDataType.TINYINT, this, "Descripción del comportamiento de la especie");
/**
* The column <code>cita_historico.especie_id</code>. Identificador de la especie
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> ESPECIE_ID = createField("especie_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "Identificador de la especie");
/**
* The column <code>cita_historico.criterio_seleccion_cita_id</code>. Criterio utilizado en la selección de la cita
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> CRITERIO_SELECCION_CITA_ID = createField("criterio_seleccion_cita_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "Criterio utilizado en la selección de la cita");
/**
* The column <code>cita_historico.importancia_cita_id</code>.
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> IMPORTANCIA_CITA_ID = createField("importancia_cita_id", org.jooq.impl.SQLDataType.INTEGER.defaulted(true), this, "");
/**
* The column <code>cita_historico.estudio_id</code>.
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Integer> ESTUDIO_ID = createField("estudio_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaulted(true), this, "");
/**
* The column <code>cita_historico.indPrivacidad</code>. Indica si los datos sensibles de la cita de la especie deben ser privados (0) o públicos (1)
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Byte> INDPRIVACIDAD = createField("indPrivacidad", org.jooq.impl.SQLDataType.TINYINT.nullable(false).defaulted(true), this, "Indica si los datos sensibles de la cita de la especie deben ser privados (0) o públicos (1)");
/**
* The column <code>cita_historico.indFoto</code>.
*/
public final org.jooq.TableField<CitaHistoricoRecord, java.lang.Byte> INDFOTO = createField("indFoto", org.jooq.impl.SQLDataType.TINYINT.nullable(false).defaulted(true), this, "");
/**
* Create a <code>cita_historico</code> table reference
*/
public CitaHistorico() {
this(AnuarioSchema.getTablePrefix() + "cita_historico", null);
}
/**
* Create an aliased <code>cita_historico</code> table reference
*/
public CitaHistorico(java.lang.String alias) {
this(alias, CitaHistorico.CITA_HISTORICO);
}
private CitaHistorico(java.lang.String alias, org.jooq.Table<CitaHistoricoRecord> aliased) {
this(alias, aliased, null);
}
private CitaHistorico(java.lang.String alias, org.jooq.Table<CitaHistoricoRecord> aliased, org.jooq.Field<?>[] parameters) {
super(alias, AnuarioSchema.ANUARIO_SCHEMA, aliased, parameters, "Históricos de cita recopiladas");
}
/**
* {@inheritDoc}
*/
@Override
public CitaHistorico as(java.lang.String alias) {
return new CitaHistorico(alias, this);
}
/**
* Rename this table
*/
public CitaHistorico rename(java.lang.String name) {
return new CitaHistorico(name, null);
}
}
| apache-2.0 |
OpenUniversity/ovirt-engine | backend/manager/modules/common/src/main/java/org/ovirt/engine/core/common/businessentities/VdsSpmStatus.java | 642 | package org.ovirt.engine.core.common.businessentities;
import java.util.HashMap;
public enum VdsSpmStatus {
None(0),
Contending(1),
SPM(2);
private int intValue;
private static final HashMap<Integer, VdsSpmStatus> mappings = new HashMap<>();
static {
for (VdsSpmStatus vdsSpmStatus : values()) {
mappings.put(vdsSpmStatus.getValue(), vdsSpmStatus);
}
}
private VdsSpmStatus(int value) {
intValue = value;
}
public int getValue() {
return intValue;
}
public static VdsSpmStatus forValue(int value) {
return mappings.get(value);
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-lakeformation/src/main/java/com/amazonaws/services/lakeformation/model/transform/DescribeResourceRequestMarshaller.java | 2048 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.lakeformation.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.lakeformation.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DescribeResourceRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DescribeResourceRequestMarshaller {
private static final MarshallingInfo<String> RESOURCEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ResourceArn").build();
private static final DescribeResourceRequestMarshaller instance = new DescribeResourceRequestMarshaller();
public static DescribeResourceRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DescribeResourceRequest describeResourceRequest, ProtocolMarshaller protocolMarshaller) {
if (describeResourceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(describeResourceRequest.getResourceArn(), RESOURCEARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
googleads/google-ads-java | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/CustomInterestOperation.java | 44696 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/services/custom_interest_service.proto
package com.google.ads.googleads.v10.services;
/**
* <pre>
* A single operation (create, update) on a custom interest.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.CustomInterestOperation}
*/
public final class CustomInterestOperation extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v10.services.CustomInterestOperation)
CustomInterestOperationOrBuilder {
private static final long serialVersionUID = 0L;
// Use CustomInterestOperation.newBuilder() to construct.
private CustomInterestOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CustomInterestOperation() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new CustomInterestOperation();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private CustomInterestOperation(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
com.google.ads.googleads.v10.resources.CustomInterest.Builder subBuilder = null;
if (operationCase_ == 1) {
subBuilder = ((com.google.ads.googleads.v10.resources.CustomInterest) operation_).toBuilder();
}
operation_ =
input.readMessage(com.google.ads.googleads.v10.resources.CustomInterest.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.CustomInterest) operation_);
operation_ = subBuilder.buildPartial();
}
operationCase_ = 1;
break;
}
case 18: {
com.google.ads.googleads.v10.resources.CustomInterest.Builder subBuilder = null;
if (operationCase_ == 2) {
subBuilder = ((com.google.ads.googleads.v10.resources.CustomInterest) operation_).toBuilder();
}
operation_ =
input.readMessage(com.google.ads.googleads.v10.resources.CustomInterest.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom((com.google.ads.googleads.v10.resources.CustomInterest) operation_);
operation_ = subBuilder.buildPartial();
}
operationCase_ = 2;
break;
}
case 34: {
com.google.protobuf.FieldMask.Builder subBuilder = null;
if (updateMask_ != null) {
subBuilder = updateMask_.toBuilder();
}
updateMask_ = input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(updateMask_);
updateMask_ = subBuilder.buildPartial();
}
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.CustomInterestServiceProto.internal_static_google_ads_googleads_v10_services_CustomInterestOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.CustomInterestServiceProto.internal_static_google_ads_googleads_v10_services_CustomInterestOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.CustomInterestOperation.class, com.google.ads.googleads.v10.services.CustomInterestOperation.Builder.class);
}
private int operationCase_ = 0;
private java.lang.Object operation_;
public enum OperationCase
implements com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
CREATE(1),
UPDATE(2),
OPERATION_NOT_SET(0);
private final int value;
private OperationCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static OperationCase valueOf(int value) {
return forNumber(value);
}
public static OperationCase forNumber(int value) {
switch (value) {
case 1: return CREATE;
case 2: return UPDATE;
case 0: return OPERATION_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public static final int UPDATE_MASK_FIELD_NUMBER = 4;
private com.google.protobuf.FieldMask updateMask_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return updateMask_ != null;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return getUpdateMask();
}
public static final int CREATE_FIELD_NUMBER = 1;
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
* @return Whether the create field is set.
*/
@java.lang.Override
public boolean hasCreate() {
return operationCase_ == 1;
}
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
* @return The create.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomInterest getCreate() {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomInterest) operation_;
}
return com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
}
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomInterestOrBuilder getCreateOrBuilder() {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomInterest) operation_;
}
return com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
}
public static final int UPDATE_FIELD_NUMBER = 2;
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomInterest getUpdate() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.CustomInterest) operation_;
}
return com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
}
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomInterestOrBuilder getUpdateOrBuilder() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.CustomInterest) operation_;
}
return com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (operationCase_ == 1) {
output.writeMessage(1, (com.google.ads.googleads.v10.resources.CustomInterest) operation_);
}
if (operationCase_ == 2) {
output.writeMessage(2, (com.google.ads.googleads.v10.resources.CustomInterest) operation_);
}
if (updateMask_ != null) {
output.writeMessage(4, getUpdateMask());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (operationCase_ == 1) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, (com.google.ads.googleads.v10.resources.CustomInterest) operation_);
}
if (operationCase_ == 2) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, (com.google.ads.googleads.v10.resources.CustomInterest) operation_);
}
if (updateMask_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, getUpdateMask());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v10.services.CustomInterestOperation)) {
return super.equals(obj);
}
com.google.ads.googleads.v10.services.CustomInterestOperation other = (com.google.ads.googleads.v10.services.CustomInterestOperation) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask()
.equals(other.getUpdateMask())) return false;
}
if (!getOperationCase().equals(other.getOperationCase())) return false;
switch (operationCase_) {
case 1:
if (!getCreate()
.equals(other.getCreate())) return false;
break;
case 2:
if (!getUpdate()
.equals(other.getUpdate())) return false;
break;
case 0:
default:
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
switch (operationCase_) {
case 1:
hash = (37 * hash) + CREATE_FIELD_NUMBER;
hash = (53 * hash) + getCreate().hashCode();
break;
case 2:
hash = (37 * hash) + UPDATE_FIELD_NUMBER;
hash = (53 * hash) + getUpdate().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v10.services.CustomInterestOperation prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* A single operation (create, update) on a custom interest.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v10.services.CustomInterestOperation}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.services.CustomInterestOperation)
com.google.ads.googleads.v10.services.CustomInterestOperationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v10.services.CustomInterestServiceProto.internal_static_google_ads_googleads_v10_services_CustomInterestOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v10.services.CustomInterestServiceProto.internal_static_google_ads_googleads_v10_services_CustomInterestOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v10.services.CustomInterestOperation.class, com.google.ads.googleads.v10.services.CustomInterestOperation.Builder.class);
}
// Construct using com.google.ads.googleads.v10.services.CustomInterestOperation.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (updateMaskBuilder_ == null) {
updateMask_ = null;
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
operationCase_ = 0;
operation_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v10.services.CustomInterestServiceProto.internal_static_google_ads_googleads_v10_services_CustomInterestOperation_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomInterestOperation getDefaultInstanceForType() {
return com.google.ads.googleads.v10.services.CustomInterestOperation.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomInterestOperation build() {
com.google.ads.googleads.v10.services.CustomInterestOperation result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomInterestOperation buildPartial() {
com.google.ads.googleads.v10.services.CustomInterestOperation result = new com.google.ads.googleads.v10.services.CustomInterestOperation(this);
if (updateMaskBuilder_ == null) {
result.updateMask_ = updateMask_;
} else {
result.updateMask_ = updateMaskBuilder_.build();
}
if (operationCase_ == 1) {
if (createBuilder_ == null) {
result.operation_ = operation_;
} else {
result.operation_ = createBuilder_.build();
}
}
if (operationCase_ == 2) {
if (updateBuilder_ == null) {
result.operation_ = operation_;
} else {
result.operation_ = updateBuilder_.build();
}
}
result.operationCase_ = operationCase_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v10.services.CustomInterestOperation) {
return mergeFrom((com.google.ads.googleads.v10.services.CustomInterestOperation)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v10.services.CustomInterestOperation other) {
if (other == com.google.ads.googleads.v10.services.CustomInterestOperation.getDefaultInstance()) return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
switch (other.getOperationCase()) {
case CREATE: {
mergeCreate(other.getCreate());
break;
}
case UPDATE: {
mergeUpdate(other.getUpdate());
break;
}
case OPERATION_NOT_SET: {
break;
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v10.services.CustomInterestOperation parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v10.services.CustomInterestOperation) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int operationCase_ = 0;
private java.lang.Object operation_;
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public Builder clearOperation() {
operationCase_ = 0;
operation_ = null;
onChanged();
return this;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder> updateMaskBuilder_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return updateMaskBuilder_ != null || updateMask_ != null;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
onChanged();
} else {
updateMaskBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder setUpdateMask(
com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
onChanged();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (updateMask_ != null) {
updateMask_ =
com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial();
} else {
updateMask_ = value;
}
onChanged();
} else {
updateMaskBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder clearUpdateMask() {
if (updateMaskBuilder_ == null) {
updateMask_ = null;
onChanged();
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null ?
com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask, com.google.protobuf.FieldMask.Builder, com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(),
getParentForChildren(),
isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomInterest, com.google.ads.googleads.v10.resources.CustomInterest.Builder, com.google.ads.googleads.v10.resources.CustomInterestOrBuilder> createBuilder_;
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
* @return Whether the create field is set.
*/
@java.lang.Override
public boolean hasCreate() {
return operationCase_ == 1;
}
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
* @return The create.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomInterest getCreate() {
if (createBuilder_ == null) {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomInterest) operation_;
}
return com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
} else {
if (operationCase_ == 1) {
return createBuilder_.getMessage();
}
return com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
}
}
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
*/
public Builder setCreate(com.google.ads.googleads.v10.resources.CustomInterest value) {
if (createBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
createBuilder_.setMessage(value);
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
*/
public Builder setCreate(
com.google.ads.googleads.v10.resources.CustomInterest.Builder builderForValue) {
if (createBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
createBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
*/
public Builder mergeCreate(com.google.ads.googleads.v10.resources.CustomInterest value) {
if (createBuilder_ == null) {
if (operationCase_ == 1 &&
operation_ != com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v10.resources.CustomInterest.newBuilder((com.google.ads.googleads.v10.resources.CustomInterest) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 1) {
createBuilder_.mergeFrom(value);
}
createBuilder_.setMessage(value);
}
operationCase_ = 1;
return this;
}
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
*/
public Builder clearCreate() {
if (createBuilder_ == null) {
if (operationCase_ == 1) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 1) {
operationCase_ = 0;
operation_ = null;
}
createBuilder_.clear();
}
return this;
}
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
*/
public com.google.ads.googleads.v10.resources.CustomInterest.Builder getCreateBuilder() {
return getCreateFieldBuilder().getBuilder();
}
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomInterestOrBuilder getCreateOrBuilder() {
if ((operationCase_ == 1) && (createBuilder_ != null)) {
return createBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 1) {
return (com.google.ads.googleads.v10.resources.CustomInterest) operation_;
}
return com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
}
}
/**
* <pre>
* Create operation: No resource name is expected for the new custom
* interest.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest create = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomInterest, com.google.ads.googleads.v10.resources.CustomInterest.Builder, com.google.ads.googleads.v10.resources.CustomInterestOrBuilder>
getCreateFieldBuilder() {
if (createBuilder_ == null) {
if (!(operationCase_ == 1)) {
operation_ = com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
}
createBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomInterest, com.google.ads.googleads.v10.resources.CustomInterest.Builder, com.google.ads.googleads.v10.resources.CustomInterestOrBuilder>(
(com.google.ads.googleads.v10.resources.CustomInterest) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 1;
onChanged();;
return createBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomInterest, com.google.ads.googleads.v10.resources.CustomInterest.Builder, com.google.ads.googleads.v10.resources.CustomInterestOrBuilder> updateBuilder_;
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomInterest getUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.CustomInterest) operation_;
}
return com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
} else {
if (operationCase_ == 2) {
return updateBuilder_.getMessage();
}
return com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
*/
public Builder setUpdate(com.google.ads.googleads.v10.resources.CustomInterest value) {
if (updateBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
updateBuilder_.setMessage(value);
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
*/
public Builder setUpdate(
com.google.ads.googleads.v10.resources.CustomInterest.Builder builderForValue) {
if (updateBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
updateBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
*/
public Builder mergeUpdate(com.google.ads.googleads.v10.resources.CustomInterest value) {
if (updateBuilder_ == null) {
if (operationCase_ == 2 &&
operation_ != com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v10.resources.CustomInterest.newBuilder((com.google.ads.googleads.v10.resources.CustomInterest) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 2) {
updateBuilder_.mergeFrom(value);
}
updateBuilder_.setMessage(value);
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
*/
public Builder clearUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
}
updateBuilder_.clear();
}
return this;
}
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
*/
public com.google.ads.googleads.v10.resources.CustomInterest.Builder getUpdateBuilder() {
return getUpdateFieldBuilder().getBuilder();
}
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v10.resources.CustomInterestOrBuilder getUpdateOrBuilder() {
if ((operationCase_ == 2) && (updateBuilder_ != null)) {
return updateBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v10.resources.CustomInterest) operation_;
}
return com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The custom interest is expected to have a valid
* resource name.
* </pre>
*
* <code>.google.ads.googleads.v10.resources.CustomInterest update = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomInterest, com.google.ads.googleads.v10.resources.CustomInterest.Builder, com.google.ads.googleads.v10.resources.CustomInterestOrBuilder>
getUpdateFieldBuilder() {
if (updateBuilder_ == null) {
if (!(operationCase_ == 2)) {
operation_ = com.google.ads.googleads.v10.resources.CustomInterest.getDefaultInstance();
}
updateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v10.resources.CustomInterest, com.google.ads.googleads.v10.resources.CustomInterest.Builder, com.google.ads.googleads.v10.resources.CustomInterestOrBuilder>(
(com.google.ads.googleads.v10.resources.CustomInterest) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 2;
onChanged();;
return updateBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.services.CustomInterestOperation)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v10.services.CustomInterestOperation)
private static final com.google.ads.googleads.v10.services.CustomInterestOperation DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v10.services.CustomInterestOperation();
}
public static com.google.ads.googleads.v10.services.CustomInterestOperation getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CustomInterestOperation>
PARSER = new com.google.protobuf.AbstractParser<CustomInterestOperation>() {
@java.lang.Override
public CustomInterestOperation parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new CustomInterestOperation(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<CustomInterestOperation> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CustomInterestOperation> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v10.services.CustomInterestOperation getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
vespa-engine/vespa | jrt/tests/com/yahoo/jrt/TlsDetectionTest.java | 3572 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;
import static org.junit.Assert.assertEquals;
public class TlsDetectionTest {
static private String message(byte[] data) {
String msg = "isTls([";
String delimiter = "";
for (byte b: data) {
msg += delimiter + (b & 0xff);
delimiter = ", ";
}
msg += "])";
return msg;
}
static private void checkTls(boolean expect, int ... values) {
byte[] data = new byte[values.length];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) values[i];
}
assertEquals(message(data), expect, MaybeTlsCryptoSocket.looksLikeTlsToMe(data));
}
@org.junit.Test public void testValidHandshake() {
checkTls(true, 22, 3, 1, 10, 255, 1, 0, 10, 251);
checkTls(true, 22, 3, 3, 10, 255, 1, 0, 10, 251);
}
@org.junit.Test public void testDataOfWrongSize() {
checkTls(false, 22, 3, 1, 10, 255, 1, 0, 10);
checkTls(false, 22, 3, 1, 10, 255, 1, 0, 10, 251, 0);
}
@org.junit.Test public void testDataNotTaggedAsHandshake() {
checkTls(false, 23, 3, 1, 10, 255, 1, 0, 10, 251);
}
@org.junit.Test public void testDataWithBadMajorVersion() {
checkTls(false, 22, 0, 1, 10, 255, 1, 0, 10, 251);
checkTls(false, 22, 1, 1, 10, 255, 1, 0, 10, 251);
checkTls(false, 22, 2, 1, 10, 255, 1, 0, 10, 251);
checkTls(false, 22, 4, 1, 10, 255, 1, 0, 10, 251);
checkTls(false, 22, 5, 1, 10, 255, 1, 0, 10, 251);
}
@org.junit.Test public void testDataWithBadMinorVersion() {
checkTls(false, 22, 3, 0, 10, 255, 1, 0, 10, 251);
checkTls(false, 22, 3, 2, 10, 255, 1, 0, 10, 251);
checkTls(false, 22, 3, 4, 10, 255, 1, 0, 10, 251);
checkTls(false, 22, 3, 5, 10, 255, 1, 0, 10, 251);
}
@org.junit.Test public void testDataNotTaggedAsClientHello() {
checkTls(false, 22, 3, 1, 10, 255, 0, 0, 10, 251);
checkTls(false, 22, 3, 1, 10, 255, 2, 0, 10, 251);
}
@org.junit.Test public void testFrameSizeLimits() {
checkTls(false, 22, 3, 1, 255, 255, 1, 0, 255, 251); // max
checkTls(false, 22, 3, 1, 72, 1, 1, 0, 71, 253); // 18k + 1
checkTls(true, 22, 3, 1, 72, 0, 1, 0, 71, 252); // 18k
checkTls(true, 22, 3, 1, 0, 4, 1, 0, 0, 0); // 4
checkTls(false, 22, 3, 1, 0, 3, 1, 0, 0, 0); // 3 - capped
checkTls(false, 22, 3, 1, 0, 3, 1, 255, 255, 255); // 3 - wrapped
}
@org.junit.Test public void testFrameAndClientHelloSizeRelationship() {
checkTls(true, 22, 3, 1, 10, 255, 1, 0, 10, 251);
checkTls(false, 22, 3, 1, 10, 255, 1, 1, 10, 251);
checkTls(false, 22, 3, 1, 10, 255, 1, 2, 10, 251);
checkTls(false, 22, 3, 1, 10, 5, 1, 0, 10, 0);
checkTls(true, 22, 3, 1, 10, 5, 1, 0, 10, 1);
checkTls(false, 22, 3, 1, 10, 5, 1, 0, 10, 2);
checkTls(false, 22, 3, 1, 10, 5, 1, 0, 9, 1);
checkTls(true, 22, 3, 1, 10, 5, 1, 0, 10, 1);
checkTls(false, 22, 3, 1, 10, 5, 1, 0, 11, 1);
checkTls(true, 22, 3, 1, 10, 5, 1, 0, 10, 1);
checkTls(true, 22, 3, 1, 10, 4, 1, 0, 10, 0);
checkTls(true, 22, 3, 1, 10, 3, 1, 0, 9, 255);
checkTls(true, 22, 3, 1, 10, 2, 1, 0, 9, 254);
checkTls(true, 22, 3, 1, 10, 1, 1, 0, 9, 253);
checkTls(true, 22, 3, 1, 10, 0, 1, 0, 9, 252);
}
}
| apache-2.0 |
tilioteo/hypothesis | backend/data-service/src/main/java/org/hypothesis/data/service/GroupServiceImpl.java | 4715 | /**
* Apache Licence Version 2.0
* Please read the LICENCE file
*/
package org.hypothesis.data.service;
import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hypothesis.data.interfaces.GroupService;
import org.hypothesis.data.model.FieldConstants;
import org.hypothesis.data.model.Group;
import org.hypothesis.data.model.User;
import javax.enterprise.inject.Default;
import java.util.List;
/**
* @author Kamil Morong, Tilioteo Ltd
*
* Hypothesis
*
*/
@SuppressWarnings("serial")
@Default
public class GroupServiceImpl implements GroupService {
private static final Logger log = Logger.getLogger(GroupServiceImpl.class);
private final HibernateDao<Group, Long> groupDao;
public GroupServiceImpl() {
groupDao = new HibernateDao<>(Group.class);
}
/*
* (non-Javadoc)
*
* @see
* org.hypothesis.data.service.GroupService#merge(org.hypothesis.data.model.
* Group)
*/
@Override
public Group merge(Group group) {
try {
groupDao.beginTransaction();
group = mergeInit(group);
groupDao.commit();
return group;
} catch (Exception e) {
log.error(e.getMessage());
groupDao.rollback();
}
return null;
}
private Group mergeInit(Group group) {
groupDao.clear();
group = groupDao.merge(group);
Hibernate.initialize(group.getUsers());
return group;
}
/*
* (non-Javadoc)
*
* @see
* org.hypothesis.data.service.GroupService#add(org.hypothesis.data.model.
* Group)
*/
@Override
public Group add(Group group) {
log.debug("addGroup");
try {
groupDao.beginTransaction();
// group = mergeInit(group);
// groupDao.clear();
group = groupDao.merge(group);
group = groupDao.makePersistent(group);
groupDao.commit();
return group;
} catch (Exception e) {
log.error(e.getMessage());
groupDao.rollback();
// throw e;
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.hypothesis.data.service.GroupService#deleteAll()
*/
@Override
public void deleteAll() {
log.debug("deleteAllGroups");
try {
this.findAll().forEach(this::delete);
} catch (Exception e) {
log.error(e.getMessage());
}
}
/*
* (non-Javadoc)
*
* @see
* org.hypothesis.data.service.GroupService#delete(org.hypothesis.data.model
* .Group)
*/
@Override
public void delete(Group group) {
log.debug("deleteGroup");
try {
groupDao.beginTransaction();
group = mergeInit(group);
// groupDao.clear();
groupDao.makeTransient(group);
groupDao.commit();
} catch (Exception e) {
log.error(e.getMessage());
groupDao.rollback();
}
}
/*
* (non-Javadoc)
*
* @see org.hypothesis.data.service.GroupService#findAll()
*/
@Override
public List<Group> findAll() {
log.debug("findAllGroups");
try {
groupDao.beginTransaction();
List<Group> allGroups = groupDao.findAll();
groupDao.commit();
return allGroups;
} catch (Exception e) {
log.error(e.getMessage());
groupDao.rollback();
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.hypothesis.data.service.GroupService#find(long)
*/
@Override
public Group findById(Long id) {
log.debug("findGroup");
try {
groupDao.beginTransaction();
Group grp = groupDao.findById(id, true);
groupDao.commit();
return grp;
} catch (Exception e) {
log.error(e.getMessage());
groupDao.rollback();
}
return null;
}
/*
* (non-Javadoc)
*
* @see
* org.hypothesis.data.service.GroupService#findOwnerGroups(org.hypothesis.
* data.model.User)
*/
@Override
public List<Group> findOwnerGroups(User owner) {
log.debug("findOwnerGroups");
try {
groupDao.beginTransaction();
List<Group> allGroups = groupDao
.findByCriteria(Restrictions.eq(FieldConstants.PROPERTY_OWNER_ID, owner.getId()));
groupDao.commit();
return allGroups;
} catch (Exception e) {
log.error(e.getMessage());
groupDao.rollback();
// throw e;
return null;
}
}
/*
* (non-Javadoc)
*
* @see
* org.hypothesis.data.service.GroupService#groupNameExists(java.lang.Long,
* java.lang.String)
*/
@Override
public boolean groupNameExists(Long id, String name) {
log.debug("groupNameExists");
try {
groupDao.beginTransaction();
Criterion crit = (id == null) ? Restrictions.eq(FieldConstants.NAME, name)
: Restrictions.and(Restrictions.eq(FieldConstants.NAME, name),
Restrictions.ne(FieldConstants.ID, id));
List<Group> groups = groupDao.findByCriteria(crit);
groupDao.commit();
return !groups.isEmpty();
} catch (Exception e) {
log.error(e.getMessage());
groupDao.rollback();
// throw e;
return false;
}
}
}
| apache-2.0 |
bazelbuild/intellij | aspect/testing/tests/src/com/google/idea/blaze/aspect/java/dependencies/testsrc/FooExporterExporter.java | 716 | /*
* Copyright 2017 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.aspect.java.dependencies.testsrc;
class FooExporterExporter {}
| apache-2.0 |
jaferreiro/gora-indra | gora-core/src/main/java/org/apache/gora/persistency/Persistent.java | 3068 | /**
* 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.gora.persistency;
import java.util.List;
import org.apache.avro.Schema.Field;
import org.apache.avro.specific.SpecificRecord;
import org.apache.gora.persistency.Dirtyable;
/**
* Objects that are persisted by Gora implements this interface.
*/
public interface Persistent extends SpecificRecord, Dirtyable {
public static String DIRTY_BYTES_FIELD_NAME = "__g__dirty";
/**
* Clears the inner state of the object without any modification to the actual
* data on the data store. This method should be called before re-using the
* object to hold the data for another result.
*/
void clear();
/**
* Returns whether the field has been modified.
*
* @param fieldIndex
* the offset of the field in the object
* @return whether the field has been modified.
*/
boolean isDirty(int fieldIndex);
/**
* Returns whether the field has been modified.
*
* @param field
* the name of the field
* @return whether the field has been modified.
*/
boolean isDirty(String field);
/**
* Sets all the fields of the object as dirty.
*/
void setDirty();
/**
* Sets the field as dirty.
*
* @param fieldIndex
* the offset of the field in the object
*/
void setDirty(int fieldIndex);
/**
* Sets the field as dirty.
*
* @param field
* the name of the field
*/
void setDirty(String field);
/**
* Sets the fields as dirty.
*
* @param fields
* the names of the fields
*/
void setDirty(String[] fields);
/**
* Clears the field as dirty.
*
* @param fieldIndex
* the offset of the field in the object
*/
void clearDirty(int fieldIndex);
/**
* Clears the field as dirty.
*
* @param field
* the name of the field
*/
void clearDirty(String field);
/**
* Get an object which can be used to mark this field as deleted (rather than
* state unknown, which is indicated by null).
*
* @return a tombstone.
*/
public abstract Tombstone getTombstone();
/**
* Get a list of fields from this persistent object's schema that are not
* managed by Gora.
*
* @return the unmanaged fields
*/
public List<Field> getUnmanagedFields();
/**
* Constructs a new instance of the object by using appropriate builder. This
* method is intended to be used by Gora framework.
*
* @return a new instance of the object
*/
Persistent newInstance();
} | apache-2.0 |
oehme/analysing-gradle-performance | my-app/src/test/java/org/gradle/test/performance/mediummonolithicjavaproject/p155/Test3115.java | 2111 | package org.gradle.test.performance.mediummonolithicjavaproject.p155;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test3115 {
Production3115 objectUnderTest = new Production3115();
@Test
public void testProperty0() {
String value = "value";
objectUnderTest.setProperty0(value);
assertEquals(value, objectUnderTest.getProperty0());
}
@Test
public void testProperty1() {
String value = "value";
objectUnderTest.setProperty1(value);
assertEquals(value, objectUnderTest.getProperty1());
}
@Test
public void testProperty2() {
String value = "value";
objectUnderTest.setProperty2(value);
assertEquals(value, objectUnderTest.getProperty2());
}
@Test
public void testProperty3() {
String value = "value";
objectUnderTest.setProperty3(value);
assertEquals(value, objectUnderTest.getProperty3());
}
@Test
public void testProperty4() {
String value = "value";
objectUnderTest.setProperty4(value);
assertEquals(value, objectUnderTest.getProperty4());
}
@Test
public void testProperty5() {
String value = "value";
objectUnderTest.setProperty5(value);
assertEquals(value, objectUnderTest.getProperty5());
}
@Test
public void testProperty6() {
String value = "value";
objectUnderTest.setProperty6(value);
assertEquals(value, objectUnderTest.getProperty6());
}
@Test
public void testProperty7() {
String value = "value";
objectUnderTest.setProperty7(value);
assertEquals(value, objectUnderTest.getProperty7());
}
@Test
public void testProperty8() {
String value = "value";
objectUnderTest.setProperty8(value);
assertEquals(value, objectUnderTest.getProperty8());
}
@Test
public void testProperty9() {
String value = "value";
objectUnderTest.setProperty9(value);
assertEquals(value, objectUnderTest.getProperty9());
}
} | apache-2.0 |
photo/mobile-android | submodules/Android-Feather/src/com/aviary/android/feather/widget/ToolbarView.java | 9694 | package com.aviary.android.feather.widget;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.ViewSwitcher.ViewFactory;
import com.aviary.android.feather.R;
// TODO: Auto-generated Javadoc
/**
* The Class ToolbarView.
*/
public class ToolbarView extends ViewFlipper implements ViewFactory {
/**
* The listener interface for receiving onToolbarClick events. The class that is interested in processing a onToolbarClick event
* implements this interface, and the object created with that class is registered with a component using the component's
* <code>addOnToolbarClickListener<code> method. When
* the onToolbarClick event occurs, that object's appropriate
* method is invoked.
*
* @see OnToolbarClickEvent
*/
public static interface OnToolbarClickListener {
/**
* On save click.
*/
void onSaveClick();
/**
* On apply click.
*/
void onApplyClick();
/**
* On cancel click.
*/
void onCancelClick();
};
/**
* The Enum STATE.
*/
public static enum STATE {
/** The STAT e_ save. */
STATE_SAVE,
/** The STAT e_ apply. */
STATE_APPLY,
};
/** The m apply button. */
private Button mApplyButton;
/** The m save button. */
private Button mSaveButton;
/** The m title text. */
private TextSwitcher mTitleText;
/** The m aviary logo. */
private TextView mAviaryLogo;
/** The is animating. */
@SuppressWarnings("unused")
private boolean isAnimating;
/** The m current state. */
private STATE mCurrentState;
/** The m out animation. */
private Animation mOutAnimation;
/** The m in animation. */
private Animation mInAnimation;
/** The m listener. */
private OnToolbarClickListener mListener;
/** The m clickable. */
private boolean mClickable;
/** The Constant MSG_SHOW_CHILD. */
private static final int MSG_SHOW_CHILD = 1;
/** The m handler. */
private Handler mHandler = new Handler() {
@Override
public void handleMessage( android.os.Message msg ) {
switch ( msg.what ) {
case MSG_SHOW_CHILD:
setDisplayedChild( msg.arg1 );
break;
}
};
};
/**
* Instantiates a new toolbar view.
*
* @param context
* the context
*/
public ToolbarView( Context context ) {
super( context );
init( context, null );
}
/**
* Instantiates a new toolbar view.
*
* @param context
* the context
* @param attrs
* the attrs
*/
public ToolbarView( Context context, AttributeSet attrs ) {
super( context, attrs );
init( context, attrs );
}
/**
* Inits the.
*
* @param context
* the context
* @param attrs
* the attrs
*/
private void init( Context context, AttributeSet attrs ) {
mCurrentState = STATE.STATE_SAVE;
setAnimationCacheEnabled( true );
setAlwaysDrawnWithCacheEnabled( true );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setClickable(boolean)
*/
@Override
public void setClickable( boolean clickable ) {
mClickable = clickable;
}
/*
* (non-Javadoc)
*
* @see android.view.View#isClickable()
*/
@Override
public boolean isClickable() {
return mClickable;
}
/**
* Gets the in animation time.
*
* @return the in animation time
*/
public long getInAnimationTime() {
return mInAnimation.getDuration() + mInAnimation.getStartOffset();
}
/**
* Gets the out animation time.
*
* @return the out animation time
*/
public long getOutAnimationTime() {
return mOutAnimation.getDuration() + mOutAnimation.getStartOffset();
}
/*
* (non-Javadoc)
*
* @see android.view.View#onFinishInflate()
*/
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mApplyButton = (Button) findViewById( R.id.toolbar_content_panel ).findViewById( R.id.button_apply );
mSaveButton = (Button) findViewById( R.id.toolbar_main_panel ).findViewById( R.id.button_save );
mTitleText = (TextSwitcher) findViewById( R.id.toolbar_title );
mTitleText.setFactory( this );
mAviaryLogo = (TextView) findViewById( R.id.aviary_logo );
mInAnimation = AnimationUtils.loadAnimation( getContext(), R.anim.feather_push_up_in );
mInAnimation.setStartOffset( 100 );
mOutAnimation = AnimationUtils.loadAnimation( getContext(), R.anim.feather_push_up_out );
mOutAnimation.setStartOffset( 100 );
mOutAnimation.setAnimationListener( mInAnimationListener );
mInAnimation.setAnimationListener( mInAnimationListener );
setInAnimation( mInAnimation );
setOutAnimation( mOutAnimation );
mApplyButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View v ) {
if ( mListener != null && mCurrentState == STATE.STATE_APPLY && isClickable() ) mListener.onApplyClick();
}
} );
mSaveButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick( View v ) {
if ( mListener != null && mCurrentState == STATE.STATE_SAVE && isClickable() ) mListener.onSaveClick();
}
} );
}
/**
* Change the current toolbar state creating an animation between the current and the new view state.
*
* @param state
* the state
* @param showMiddle
* the show middle
*/
public void setState( STATE state, final boolean showMiddle ) {
if ( state != mCurrentState ) {
mCurrentState = state;
post( new Runnable() {
@Override
public void run() {
switch ( mCurrentState ) {
case STATE_APPLY:
showApplyState();
break;
case STATE_SAVE:
showSaveState( showMiddle );
break;
}
}
} );
}
}
/**
* Return the current toolbar state.
*
* @return the state
* @see #STATE
*/
public STATE getState() {
return mCurrentState;
}
/**
* Set the toolbar click listener.
*
* @param listener
* the new on toolbar click listener
* @see OnToolbarClickListener
*/
public void setOnToolbarClickListener( OnToolbarClickListener listener ) {
mListener = listener;
}
/**
* Sets the apply enabled.
*
* @param value
* the new apply enabled
*/
public void setApplyEnabled( boolean value ) {
mApplyButton.setEnabled( value );
}
public void setApplyVisibility( boolean visible ) {
mApplyButton.setVisibility( visible ? View.VISIBLE : View.GONE );
}
/*
* (non-Javadoc)
*
* @see android.view.View#setSaveEnabled(boolean)
*/
@Override
public void setSaveEnabled( boolean value ) {
mSaveButton.setEnabled( value );
}
/**
* Sets the title.
*
* @param value
* the new title
*/
public void setTitle( CharSequence value ) {
mTitleText.setText( value );
}
public void setTitle( CharSequence value, boolean animate ) {
if( !animate ){
Animation inAnimation = mTitleText.getInAnimation();
Animation outAnimation = mTitleText.getOutAnimation();
mTitleText.setInAnimation( null );
mTitleText.setOutAnimation( null );
mTitleText.setText( value );
mTitleText.setInAnimation( inAnimation );
mTitleText.setOutAnimation( outAnimation );
} else {
setTitle( value );
}
}
/**
* Sets the title.
*
* @param resourceId
* the new title
*/
public void setTitle( int resourceId ) {
setTitle( getContext().getString( resourceId ) );
}
public void setTitle( int resourceId, boolean animate ) {
setTitle( getContext().getString( resourceId ), animate );
}
/**
* Show apply state.
*/
private void showApplyState() {
setDisplayedChild( getChildCount() - 1 );
}
/**
* Show save state.
*
* @param showMiddle
* the show middle
*/
private void showSaveState( boolean showMiddle ) {
if ( showMiddle && getChildCount() == 3 )
setDisplayedChild( 1 );
else
setDisplayedChild( 0 );
}
/**
* Enable children cache.
*/
@SuppressWarnings("unused")
private void enableChildrenCache() {
setChildrenDrawnWithCacheEnabled( true );
setChildrenDrawingCacheEnabled( true );
for ( int i = 0; i < getChildCount(); i++ ) {
final View child = getChildAt( i );
child.setDrawingCacheEnabled( true );
child.buildDrawingCache( true );
}
}
/**
* Clear children cache.
*/
@SuppressWarnings("unused")
private void clearChildrenCache() {
setChildrenDrawnWithCacheEnabled( false );
}
/** The m in animation listener. */
AnimationListener mInAnimationListener = new AnimationListener() {
@Override
public void onAnimationStart( Animation animation ) {
isAnimating = true;
}
@Override
public void onAnimationRepeat( Animation animation ) {}
@Override
public void onAnimationEnd( Animation animation ) {
isAnimating = false;
if ( getDisplayedChild() == 1 && getChildCount() > 2 ) {
Thread t = new Thread( new Runnable() {
@Override
public void run() {
try {
Thread.sleep( 300 );
} catch ( InterruptedException e ) {
e.printStackTrace();
}
Message msg = mHandler.obtainMessage( MSG_SHOW_CHILD );
msg.arg1 = 0;
mHandler.sendMessage( msg );
}
} );
t.start();
}
}
};
/*
* (non-Javadoc)
*
* @see android.widget.ViewSwitcher.ViewFactory#makeView()
*/
@Override
public View makeView() {
View text = LayoutInflater.from( getContext() ).inflate( R.layout.feather_toolbar_title_text, null );
return text;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/model/ParametersInCacheKeyAndForwardedToOrigin.java | 53873 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cloudfront.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* This object determines the values that CloudFront includes in the cache key. These values can include HTTP headers,
* cookies, and URL query strings. CloudFront uses the cache key to find an object in its cache that it can return to
* the viewer.
* </p>
* <p>
* The headers, cookies, and query strings that are included in the cache key are automatically included in requests
* that CloudFront sends to the origin. CloudFront sends a request when it can’t find an object in its cache that
* matches the request’s cache key. If you want to send values to the origin but <i>not</i> include them in the cache
* key, use <code>OriginRequestPolicy</code>.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudfront-2020-05-31/ParametersInCacheKeyAndForwardedToOrigin"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ParametersInCacheKeyAndForwardedToOrigin implements Serializable, Cloneable {
/**
* <p>
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key and
* included in requests that CloudFront sends to the origin.
* </p>
* <p>
* This field is related to the <code>EnableAcceptEncodingBrotli</code> field. If one or both of these fields is
* <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then CloudFront
* does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy attached,
* do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront always includes
* the <code>Accept-Encoding</code> header in origin requests when the value of this field is <code>true</code>, so
* including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code> header
* the same as any other HTTP header in the viewer request. By default, it’s not included in the cache key and it’s
* not included in origin requests. In this case, you can manually add <code>Accept-Encoding</code> to the headers
* whitelist like any other HTTP header.
* </p>
*/
private Boolean enableAcceptEncodingGzip;
/**
* <p>
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key and
* included in requests that CloudFront sends to the origin.
* </p>
* <p>
* This field is related to the <code>EnableAcceptEncodingGzip</code> field. If one or both of these fields is
* <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then CloudFront
* does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy attached,
* do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront always includes
* the <code>Accept-Encoding</code> header in origin requests when the value of this field is <code>true</code>, so
* including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code> header
* the same as any other HTTP header in the viewer request. By default, it’s not included in the cache key and it’s
* not included in origin requests. In this case, you can manually add <code>Accept-Encoding</code> to the headers
* whitelist like any other HTTP header.
* </p>
*/
private Boolean enableAcceptEncodingBrotli;
/**
* <p>
* An object that determines whether any HTTP headers (and if so, which headers) are included in the cache key and
* automatically included in requests that CloudFront sends to the origin.
* </p>
*/
private CachePolicyHeadersConfig headersConfig;
/**
* <p>
* An object that determines whether any cookies in viewer requests (and if so, which cookies) are included in the
* cache key and automatically included in requests that CloudFront sends to the origin.
* </p>
*/
private CachePolicyCookiesConfig cookiesConfig;
/**
* <p>
* An object that determines whether any URL query strings in viewer requests (and if so, which query strings) are
* included in the cache key and automatically included in requests that CloudFront sends to the origin.
* </p>
*/
private CachePolicyQueryStringsConfig queryStringsConfig;
/**
* <p>
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key and
* included in requests that CloudFront sends to the origin.
* </p>
* <p>
* This field is related to the <code>EnableAcceptEncodingBrotli</code> field. If one or both of these fields is
* <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then CloudFront
* does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy attached,
* do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront always includes
* the <code>Accept-Encoding</code> header in origin requests when the value of this field is <code>true</code>, so
* including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code> header
* the same as any other HTTP header in the viewer request. By default, it’s not included in the cache key and it’s
* not included in origin requests. In this case, you can manually add <code>Accept-Encoding</code> to the headers
* whitelist like any other HTTP header.
* </p>
*
* @param enableAcceptEncodingGzip
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key
* and included in requests that CloudFront sends to the origin.</p>
* <p>
* This field is related to the <code>EnableAcceptEncodingBrotli</code> field. If one or both of these fields
* is <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then
* CloudFront does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy
* attached, do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront
* always includes the <code>Accept-Encoding</code> header in origin requests when the value of this field is
* <code>true</code>, so including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code>
* header the same as any other HTTP header in the viewer request. By default, it’s not included in the cache
* key and it’s not included in origin requests. In this case, you can manually add
* <code>Accept-Encoding</code> to the headers whitelist like any other HTTP header.
*/
public void setEnableAcceptEncodingGzip(Boolean enableAcceptEncodingGzip) {
this.enableAcceptEncodingGzip = enableAcceptEncodingGzip;
}
/**
* <p>
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key and
* included in requests that CloudFront sends to the origin.
* </p>
* <p>
* This field is related to the <code>EnableAcceptEncodingBrotli</code> field. If one or both of these fields is
* <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then CloudFront
* does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy attached,
* do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront always includes
* the <code>Accept-Encoding</code> header in origin requests when the value of this field is <code>true</code>, so
* including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code> header
* the same as any other HTTP header in the viewer request. By default, it’s not included in the cache key and it’s
* not included in origin requests. In this case, you can manually add <code>Accept-Encoding</code> to the headers
* whitelist like any other HTTP header.
* </p>
*
* @return A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key
* and included in requests that CloudFront sends to the origin.</p>
* <p>
* This field is related to the <code>EnableAcceptEncodingBrotli</code> field. If one or both of these
* fields is <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code>
* header, then CloudFront does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy
* attached, do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront
* always includes the <code>Accept-Encoding</code> header in origin requests when the value of this field
* is <code>true</code>, so including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code>
* header the same as any other HTTP header in the viewer request. By default, it’s not included in the
* cache key and it’s not included in origin requests. In this case, you can manually add
* <code>Accept-Encoding</code> to the headers whitelist like any other HTTP header.
*/
public Boolean getEnableAcceptEncodingGzip() {
return this.enableAcceptEncodingGzip;
}
/**
* <p>
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key and
* included in requests that CloudFront sends to the origin.
* </p>
* <p>
* This field is related to the <code>EnableAcceptEncodingBrotli</code> field. If one or both of these fields is
* <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then CloudFront
* does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy attached,
* do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront always includes
* the <code>Accept-Encoding</code> header in origin requests when the value of this field is <code>true</code>, so
* including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code> header
* the same as any other HTTP header in the viewer request. By default, it’s not included in the cache key and it’s
* not included in origin requests. In this case, you can manually add <code>Accept-Encoding</code> to the headers
* whitelist like any other HTTP header.
* </p>
*
* @param enableAcceptEncodingGzip
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key
* and included in requests that CloudFront sends to the origin.</p>
* <p>
* This field is related to the <code>EnableAcceptEncodingBrotli</code> field. If one or both of these fields
* is <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then
* CloudFront does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy
* attached, do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront
* always includes the <code>Accept-Encoding</code> header in origin requests when the value of this field is
* <code>true</code>, so including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code>
* header the same as any other HTTP header in the viewer request. By default, it’s not included in the cache
* key and it’s not included in origin requests. In this case, you can manually add
* <code>Accept-Encoding</code> to the headers whitelist like any other HTTP header.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ParametersInCacheKeyAndForwardedToOrigin withEnableAcceptEncodingGzip(Boolean enableAcceptEncodingGzip) {
setEnableAcceptEncodingGzip(enableAcceptEncodingGzip);
return this;
}
/**
* <p>
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key and
* included in requests that CloudFront sends to the origin.
* </p>
* <p>
* This field is related to the <code>EnableAcceptEncodingBrotli</code> field. If one or both of these fields is
* <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then CloudFront
* does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy attached,
* do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront always includes
* the <code>Accept-Encoding</code> header in origin requests when the value of this field is <code>true</code>, so
* including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code> header
* the same as any other HTTP header in the viewer request. By default, it’s not included in the cache key and it’s
* not included in origin requests. In this case, you can manually add <code>Accept-Encoding</code> to the headers
* whitelist like any other HTTP header.
* </p>
*
* @return A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key
* and included in requests that CloudFront sends to the origin.</p>
* <p>
* This field is related to the <code>EnableAcceptEncodingBrotli</code> field. If one or both of these
* fields is <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code>
* header, then CloudFront does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy
* attached, do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront
* always includes the <code>Accept-Encoding</code> header in origin requests when the value of this field
* is <code>true</code>, so including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code>
* header the same as any other HTTP header in the viewer request. By default, it’s not included in the
* cache key and it’s not included in origin requests. In this case, you can manually add
* <code>Accept-Encoding</code> to the headers whitelist like any other HTTP header.
*/
public Boolean isEnableAcceptEncodingGzip() {
return this.enableAcceptEncodingGzip;
}
/**
* <p>
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key and
* included in requests that CloudFront sends to the origin.
* </p>
* <p>
* This field is related to the <code>EnableAcceptEncodingGzip</code> field. If one or both of these fields is
* <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then CloudFront
* does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy attached,
* do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront always includes
* the <code>Accept-Encoding</code> header in origin requests when the value of this field is <code>true</code>, so
* including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code> header
* the same as any other HTTP header in the viewer request. By default, it’s not included in the cache key and it’s
* not included in origin requests. In this case, you can manually add <code>Accept-Encoding</code> to the headers
* whitelist like any other HTTP header.
* </p>
*
* @param enableAcceptEncodingBrotli
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key
* and included in requests that CloudFront sends to the origin.</p>
* <p>
* This field is related to the <code>EnableAcceptEncodingGzip</code> field. If one or both of these fields
* is <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then
* CloudFront does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy
* attached, do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront
* always includes the <code>Accept-Encoding</code> header in origin requests when the value of this field is
* <code>true</code>, so including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code>
* header the same as any other HTTP header in the viewer request. By default, it’s not included in the cache
* key and it’s not included in origin requests. In this case, you can manually add
* <code>Accept-Encoding</code> to the headers whitelist like any other HTTP header.
*/
public void setEnableAcceptEncodingBrotli(Boolean enableAcceptEncodingBrotli) {
this.enableAcceptEncodingBrotli = enableAcceptEncodingBrotli;
}
/**
* <p>
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key and
* included in requests that CloudFront sends to the origin.
* </p>
* <p>
* This field is related to the <code>EnableAcceptEncodingGzip</code> field. If one or both of these fields is
* <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then CloudFront
* does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy attached,
* do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront always includes
* the <code>Accept-Encoding</code> header in origin requests when the value of this field is <code>true</code>, so
* including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code> header
* the same as any other HTTP header in the viewer request. By default, it’s not included in the cache key and it’s
* not included in origin requests. In this case, you can manually add <code>Accept-Encoding</code> to the headers
* whitelist like any other HTTP header.
* </p>
*
* @return A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key
* and included in requests that CloudFront sends to the origin.</p>
* <p>
* This field is related to the <code>EnableAcceptEncodingGzip</code> field. If one or both of these fields
* is <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then
* CloudFront does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy
* attached, do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront
* always includes the <code>Accept-Encoding</code> header in origin requests when the value of this field
* is <code>true</code>, so including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code>
* header the same as any other HTTP header in the viewer request. By default, it’s not included in the
* cache key and it’s not included in origin requests. In this case, you can manually add
* <code>Accept-Encoding</code> to the headers whitelist like any other HTTP header.
*/
public Boolean getEnableAcceptEncodingBrotli() {
return this.enableAcceptEncodingBrotli;
}
/**
* <p>
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key and
* included in requests that CloudFront sends to the origin.
* </p>
* <p>
* This field is related to the <code>EnableAcceptEncodingGzip</code> field. If one or both of these fields is
* <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then CloudFront
* does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy attached,
* do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront always includes
* the <code>Accept-Encoding</code> header in origin requests when the value of this field is <code>true</code>, so
* including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code> header
* the same as any other HTTP header in the viewer request. By default, it’s not included in the cache key and it’s
* not included in origin requests. In this case, you can manually add <code>Accept-Encoding</code> to the headers
* whitelist like any other HTTP header.
* </p>
*
* @param enableAcceptEncodingBrotli
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key
* and included in requests that CloudFront sends to the origin.</p>
* <p>
* This field is related to the <code>EnableAcceptEncodingGzip</code> field. If one or both of these fields
* is <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then
* CloudFront does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy
* attached, do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront
* always includes the <code>Accept-Encoding</code> header in origin requests when the value of this field is
* <code>true</code>, so including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code>
* header the same as any other HTTP header in the viewer request. By default, it’s not included in the cache
* key and it’s not included in origin requests. In this case, you can manually add
* <code>Accept-Encoding</code> to the headers whitelist like any other HTTP header.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ParametersInCacheKeyAndForwardedToOrigin withEnableAcceptEncodingBrotli(Boolean enableAcceptEncodingBrotli) {
setEnableAcceptEncodingBrotli(enableAcceptEncodingBrotli);
return this;
}
/**
* <p>
* A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key and
* included in requests that CloudFront sends to the origin.
* </p>
* <p>
* This field is related to the <code>EnableAcceptEncodingGzip</code> field. If one or both of these fields is
* <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then CloudFront
* does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy attached,
* do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront always includes
* the <code>Accept-Encoding</code> header in origin requests when the value of this field is <code>true</code>, so
* including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code> header
* the same as any other HTTP header in the viewer request. By default, it’s not included in the cache key and it’s
* not included in origin requests. In this case, you can manually add <code>Accept-Encoding</code> to the headers
* whitelist like any other HTTP header.
* </p>
*
* @return A flag that can affect whether the <code>Accept-Encoding</code> HTTP header is included in the cache key
* and included in requests that CloudFront sends to the origin.</p>
* <p>
* This field is related to the <code>EnableAcceptEncodingGzip</code> field. If one or both of these fields
* is <code>true</code> <i>and</i> the viewer request includes the <code>Accept-Encoding</code> header, then
* CloudFront does the following:
* </p>
* <ul>
* <li>
* <p>
* Normalizes the value of the viewer’s <code>Accept-Encoding</code> header
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the cache key
* </p>
* </li>
* <li>
* <p>
* Includes the normalized header in the request to the origin, if a request is necessary
* </p>
* </li>
* </ul>
* <p>
* For more information, see <a href=
* "https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-policy-compressed-objects"
* >Compression support</a> in the <i>Amazon CloudFront Developer Guide</i>.
* </p>
* <p>
* If you set this value to <code>true</code>, and this cache behavior also has an origin request policy
* attached, do not include the <code>Accept-Encoding</code> header in the origin request policy. CloudFront
* always includes the <code>Accept-Encoding</code> header in origin requests when the value of this field
* is <code>true</code>, so including this header in an origin request policy has no effect.
* </p>
* <p>
* If both of these fields are <code>false</code>, then CloudFront treats the <code>Accept-Encoding</code>
* header the same as any other HTTP header in the viewer request. By default, it’s not included in the
* cache key and it’s not included in origin requests. In this case, you can manually add
* <code>Accept-Encoding</code> to the headers whitelist like any other HTTP header.
*/
public Boolean isEnableAcceptEncodingBrotli() {
return this.enableAcceptEncodingBrotli;
}
/**
* <p>
* An object that determines whether any HTTP headers (and if so, which headers) are included in the cache key and
* automatically included in requests that CloudFront sends to the origin.
* </p>
*
* @param headersConfig
* An object that determines whether any HTTP headers (and if so, which headers) are included in the cache
* key and automatically included in requests that CloudFront sends to the origin.
*/
public void setHeadersConfig(CachePolicyHeadersConfig headersConfig) {
this.headersConfig = headersConfig;
}
/**
* <p>
* An object that determines whether any HTTP headers (and if so, which headers) are included in the cache key and
* automatically included in requests that CloudFront sends to the origin.
* </p>
*
* @return An object that determines whether any HTTP headers (and if so, which headers) are included in the cache
* key and automatically included in requests that CloudFront sends to the origin.
*/
public CachePolicyHeadersConfig getHeadersConfig() {
return this.headersConfig;
}
/**
* <p>
* An object that determines whether any HTTP headers (and if so, which headers) are included in the cache key and
* automatically included in requests that CloudFront sends to the origin.
* </p>
*
* @param headersConfig
* An object that determines whether any HTTP headers (and if so, which headers) are included in the cache
* key and automatically included in requests that CloudFront sends to the origin.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ParametersInCacheKeyAndForwardedToOrigin withHeadersConfig(CachePolicyHeadersConfig headersConfig) {
setHeadersConfig(headersConfig);
return this;
}
/**
* <p>
* An object that determines whether any cookies in viewer requests (and if so, which cookies) are included in the
* cache key and automatically included in requests that CloudFront sends to the origin.
* </p>
*
* @param cookiesConfig
* An object that determines whether any cookies in viewer requests (and if so, which cookies) are included
* in the cache key and automatically included in requests that CloudFront sends to the origin.
*/
public void setCookiesConfig(CachePolicyCookiesConfig cookiesConfig) {
this.cookiesConfig = cookiesConfig;
}
/**
* <p>
* An object that determines whether any cookies in viewer requests (and if so, which cookies) are included in the
* cache key and automatically included in requests that CloudFront sends to the origin.
* </p>
*
* @return An object that determines whether any cookies in viewer requests (and if so, which cookies) are included
* in the cache key and automatically included in requests that CloudFront sends to the origin.
*/
public CachePolicyCookiesConfig getCookiesConfig() {
return this.cookiesConfig;
}
/**
* <p>
* An object that determines whether any cookies in viewer requests (and if so, which cookies) are included in the
* cache key and automatically included in requests that CloudFront sends to the origin.
* </p>
*
* @param cookiesConfig
* An object that determines whether any cookies in viewer requests (and if so, which cookies) are included
* in the cache key and automatically included in requests that CloudFront sends to the origin.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ParametersInCacheKeyAndForwardedToOrigin withCookiesConfig(CachePolicyCookiesConfig cookiesConfig) {
setCookiesConfig(cookiesConfig);
return this;
}
/**
* <p>
* An object that determines whether any URL query strings in viewer requests (and if so, which query strings) are
* included in the cache key and automatically included in requests that CloudFront sends to the origin.
* </p>
*
* @param queryStringsConfig
* An object that determines whether any URL query strings in viewer requests (and if so, which query
* strings) are included in the cache key and automatically included in requests that CloudFront sends to the
* origin.
*/
public void setQueryStringsConfig(CachePolicyQueryStringsConfig queryStringsConfig) {
this.queryStringsConfig = queryStringsConfig;
}
/**
* <p>
* An object that determines whether any URL query strings in viewer requests (and if so, which query strings) are
* included in the cache key and automatically included in requests that CloudFront sends to the origin.
* </p>
*
* @return An object that determines whether any URL query strings in viewer requests (and if so, which query
* strings) are included in the cache key and automatically included in requests that CloudFront sends to
* the origin.
*/
public CachePolicyQueryStringsConfig getQueryStringsConfig() {
return this.queryStringsConfig;
}
/**
* <p>
* An object that determines whether any URL query strings in viewer requests (and if so, which query strings) are
* included in the cache key and automatically included in requests that CloudFront sends to the origin.
* </p>
*
* @param queryStringsConfig
* An object that determines whether any URL query strings in viewer requests (and if so, which query
* strings) are included in the cache key and automatically included in requests that CloudFront sends to the
* origin.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ParametersInCacheKeyAndForwardedToOrigin withQueryStringsConfig(CachePolicyQueryStringsConfig queryStringsConfig) {
setQueryStringsConfig(queryStringsConfig);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getEnableAcceptEncodingGzip() != null)
sb.append("EnableAcceptEncodingGzip: ").append(getEnableAcceptEncodingGzip()).append(",");
if (getEnableAcceptEncodingBrotli() != null)
sb.append("EnableAcceptEncodingBrotli: ").append(getEnableAcceptEncodingBrotli()).append(",");
if (getHeadersConfig() != null)
sb.append("HeadersConfig: ").append(getHeadersConfig()).append(",");
if (getCookiesConfig() != null)
sb.append("CookiesConfig: ").append(getCookiesConfig()).append(",");
if (getQueryStringsConfig() != null)
sb.append("QueryStringsConfig: ").append(getQueryStringsConfig());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ParametersInCacheKeyAndForwardedToOrigin == false)
return false;
ParametersInCacheKeyAndForwardedToOrigin other = (ParametersInCacheKeyAndForwardedToOrigin) obj;
if (other.getEnableAcceptEncodingGzip() == null ^ this.getEnableAcceptEncodingGzip() == null)
return false;
if (other.getEnableAcceptEncodingGzip() != null && other.getEnableAcceptEncodingGzip().equals(this.getEnableAcceptEncodingGzip()) == false)
return false;
if (other.getEnableAcceptEncodingBrotli() == null ^ this.getEnableAcceptEncodingBrotli() == null)
return false;
if (other.getEnableAcceptEncodingBrotli() != null && other.getEnableAcceptEncodingBrotli().equals(this.getEnableAcceptEncodingBrotli()) == false)
return false;
if (other.getHeadersConfig() == null ^ this.getHeadersConfig() == null)
return false;
if (other.getHeadersConfig() != null && other.getHeadersConfig().equals(this.getHeadersConfig()) == false)
return false;
if (other.getCookiesConfig() == null ^ this.getCookiesConfig() == null)
return false;
if (other.getCookiesConfig() != null && other.getCookiesConfig().equals(this.getCookiesConfig()) == false)
return false;
if (other.getQueryStringsConfig() == null ^ this.getQueryStringsConfig() == null)
return false;
if (other.getQueryStringsConfig() != null && other.getQueryStringsConfig().equals(this.getQueryStringsConfig()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getEnableAcceptEncodingGzip() == null) ? 0 : getEnableAcceptEncodingGzip().hashCode());
hashCode = prime * hashCode + ((getEnableAcceptEncodingBrotli() == null) ? 0 : getEnableAcceptEncodingBrotli().hashCode());
hashCode = prime * hashCode + ((getHeadersConfig() == null) ? 0 : getHeadersConfig().hashCode());
hashCode = prime * hashCode + ((getCookiesConfig() == null) ? 0 : getCookiesConfig().hashCode());
hashCode = prime * hashCode + ((getQueryStringsConfig() == null) ? 0 : getQueryStringsConfig().hashCode());
return hashCode;
}
@Override
public ParametersInCacheKeyAndForwardedToOrigin clone() {
try {
return (ParametersInCacheKeyAndForwardedToOrigin) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
avilardo/rest-springmvc | src/main/java/br/com/avilardo/spring/sample/model/Member.java | 615 | package br.com.avilardo.spring.sample.model;
public class Member {
private String firstName;
private String lastName;
public Member() {
// TODO Auto-generated constructor stub
}
public Member(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
| apache-2.0 |
akquinet/jbosscc-wildfly-examples | ejb-remote-example/ejb-remote-example-ejb-client/src/main/java/de/akquinet/jbosscc/Main.java | 1333 | package de.akquinet.jbosscc;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import de.akquinet.jbosscc.ejb.Calculator;
public class Main {
private Context context = null;
public static void main(String[] args) throws Exception {
Main main = new Main();
try {
main.createInitialContext();
Calculator calculator = main.lookup();
System.out.println(calculator);
int result = calculator.add(1, 1);
System.out.println(result);
} finally {
main.closeContext();
}
}
public Calculator lookup() throws NamingException {
final String appName = "";
final String moduleName = "remote";
final String distinctName = "";
final String beanName = "calculator";
final String viewClassName = Calculator.class.getName();
Calculator calc = (Calculator) context.lookup("ejb:" + appName + "/" + moduleName
+ "/" + distinctName + "/" + beanName + "!" + viewClassName);
return calc;
}
public void createInitialContext() throws NamingException {
Properties prop = new Properties();
prop.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
context = new InitialContext(prop);
}
public void closeContext() throws NamingException{
if(context != null){
context.close();
}
}
}
| apache-2.0 |
ishubin/test-hub | src/main/java/net/mindengine/testhub/model/builds/Build.java | 2382 | /*******************************************************************************
* Copyright 2016 Ivan Shubin https://github.com/ishubin/test-hub
*
* 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.mindengine.testhub.model.builds;
public class Build {
private Long buildId;
private Long jobId;
private String name;
private Long cntTestsPassed;
private Long cntTestsFailed;
private Long cntTestsSkipped;
public Build() {
}
public Build(Long buildId, Long jobId, String name, Long cntTestsPassed, Long cntTestsFailed, Long cntTestsSkipped) {
this.buildId = buildId;
this.jobId = jobId;
this.name = name;
this.cntTestsPassed = cntTestsPassed;
this.cntTestsFailed = cntTestsFailed;
this.cntTestsSkipped = cntTestsSkipped;
}
public Long getBuildId() {
return buildId;
}
public void setBuildId(Long buildId) {
this.buildId = buildId;
}
public Long getJobId() {
return jobId;
}
public void setJobId(Long jobId) {
this.jobId = jobId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCntTestsPassed() {
return cntTestsPassed;
}
public void setCntTestsPassed(Long cntTestsPassed) {
this.cntTestsPassed = cntTestsPassed;
}
public Long getCntTestsFailed() {
return cntTestsFailed;
}
public void setCntTestsFailed(Long cntTestsFailed) {
this.cntTestsFailed = cntTestsFailed;
}
public Long getCntTestsSkipped() {
return cntTestsSkipped;
}
public void setCntTestsSkipped(Long cntTestsSkipped) {
this.cntTestsSkipped = cntTestsSkipped;
}
}
| apache-2.0 |
bozimmerman/CoffeeMud | com/planet_ink/coffee_mud/Abilities/Specializations/Familiarity_FlailedWeapon.java | 1926 | package com.planet_ink.coffee_mud.Abilities.Specializations;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2018-2022 Bo Zimmerman
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.
*/
public class Familiarity_FlailedWeapon extends Familiarity_Weapon
{
@Override
public String ID()
{
return "Familiarity_FlailedWeapon";
}
private final static String localizedName = CMLib.lang().L("Flailed Weapon Familiarity");
@Override
public String name()
{
return localizedName;
}
public Familiarity_FlailedWeapon()
{
super();
weaponClass=Weapon.CLASS_FLAILED;
}
}
| apache-2.0 |
larrytin/j2objc | jre_emul/android/libcore/luni/src/main/java/java/util/concurrent/atomic/AtomicLong.java | 6727 | /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent.atomic;
/*-[
#include <libkern/OSAtomic.h>
]-*/
/**
* A {@code long} value that may be updated atomically. See the
* {@link java.util.concurrent.atomic} package specification for
* description of the properties of atomic variables. An
* {@code AtomicLong} is used in applications such as atomically
* incremented sequence numbers, and cannot be used as a replacement
* for a {@link java.lang.Long}. However, this class does extend
* {@code Number} to allow uniform access by tools and utilities that
* deal with numerically-based classes.
*
* @since 1.5
* @author Doug Lea
*/
public class AtomicLong extends Number implements java.io.Serializable {
private static final long serialVersionUID = 1927816293512124184L;
// This unused field aligns value on an 8-byte boundary on ARM-64 processors.
private int alignmentPad;
private volatile long value;
/**
* Creates a new AtomicLong with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicLong(long initialValue) {
value = initialValue;
}
/**
* Creates a new AtomicLong with initial value {@code 0}.
*/
public AtomicLong() {
}
/**
* Gets the current value.
*
* @return the current value
*/
public final long get() {
return value;
}
/**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(long newValue) {
value = newValue;
}
/**
* Eventually sets to the given value.
*
* @param newValue the new value
* @since 1.6
*/
public final void lazySet(long newValue) {
value = newValue;
}
/**
* Atomically sets to the given value and returns the old value.
*
* @param newValue the new value
* @return the previous value
*/
public final long getAndSet(long newValue) {
while (true) {
long current = get();
if (compareAndSet(current, newValue))
return current;
}
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(long expect, long update) {
return compareAndSwapValue(expect, update);
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* <p>May <a href="package-summary.html#Spurious">fail spuriously</a>
* and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
* @return true if successful.
*/
public final boolean weakCompareAndSet(long expect, long update) {
return compareAndSwapValue(expect, update);
}
/**
* Atomically increments by one the current value.
*
* @return the previous value
*/
public final long getAndIncrement() {
while (true) {
long current = get();
long next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
public final long getAndDecrement() {
while (true) {
long current = get();
long next = current - 1;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final long getAndAdd(long delta) {
while (true) {
long current = get();
long next = current + delta;
if (compareAndSet(current, next))
return current;
}
}
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final long incrementAndGet() {
for (;;) {
long current = get();
long next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
/**
* Atomically decrements by one the current value.
*
* @return the updated value
*/
public final long decrementAndGet() {
for (;;) {
long current = get();
long next = current - 1;
if (compareAndSet(current, next))
return next;
}
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
public final long addAndGet(long delta) {
for (;;) {
long current = get();
long next = current + delta;
if (compareAndSet(current, next))
return next;
}
}
/**
* Returns the String representation of the current value.
* @return the String representation of the current value.
*/
public String toString() {
return Long.toString(get());
}
/**
* Returns the value of this {@code AtomicLong} as an {@code int}
* after a narrowing primitive conversion.
*/
public int intValue() {
return (int)get();
}
/**
* Returns the value of this {@code AtomicLong} as a {@code long}.
*/
public long longValue() {
return get();
}
/**
* Returns the value of this {@code AtomicLong} as a {@code float}
* after a widening primitive conversion.
*/
public float floatValue() {
return (float)get();
}
/**
* Returns the value of this {@code AtomicLong} as a {@code double}
* after a widening primitive conversion.
*/
public double doubleValue() {
return (double)get();
}
private static native void memoryBarrier() /*-[
OSMemoryBarrier();
]-*/;
private native boolean compareAndSwapValue(long oldValue, long newValue) /*-[
return OSAtomicCompareAndSwap64Barrier(oldValue, newValue, &value_);
]-*/;
}
| apache-2.0 |
jdami/bigpipe-for-java | bigpipe-core/src/main/java/org/cnjava/bigpipe/core/BigPipe.java | 5606 | package org.cnjava.bigpipe.core;
import org.cnjava.bigpipe.core.pagelet.Pagelet;
import org.cnjava.bigpipe.core.render.PageletRenderHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by jiangjk on 16/1/26.
*/
public class BigPipe {
private final static Logger logger = LoggerFactory.getLogger(BigPipe.class);
private List<Pagelet> asyncPagelets = new ArrayList<Pagelet>();
private List<Pagelet> syncPagelets = new ArrayList<Pagelet>();
private BigPipeContext ctx = null;
private static final ExecutorService threadPool = Executors.newCachedThreadPool();
public BigPipe(BigPipeContext ctx) {
this.ctx = ctx;
}
public void addPagelet(Pagelet pagelet) {
if (pagelet.getPageletInfo().isAsync()) {
this.asyncPagelets.add(pagelet);
} else {
this.syncPagelets.add(pagelet);
}
}
public void renderPagelets() {
this.renderSyncPagelet();
this.renderAsyncPagelet();
}
private void renderAsyncPagelet() {
if (null != this.asyncPagelets && this.asyncPagelets.size() > 0) {
ArrayList allFutureTask = new ArrayList();
Iterator iterator = this.asyncPagelets.iterator();
while (iterator.hasNext()) {
final Pagelet pageletTask = (Pagelet) iterator.next();
Callable e = new Callable() {
public Boolean call() throws Exception {
Object logicResult = null;
Callable callable = new Callable() {
public Object call() throws Exception {
try {
Method e = pageletTask.getClass().getMethod(pageletTask.getPageletInfo().getLogicMethod(), HttpServletRequest.class, HttpServletResponse.class);
return e.invoke(pageletTask, BigPipe.this.ctx.getRequest(), BigPipe.this.ctx.getResponse());
} catch (Exception e) {
logger.error("pagelet exec error!", e);
return null;
}
}
};
FutureTask f = new FutureTask(callable);
BigPipe.threadPool.execute(f);
if (logger.isDebugEnabled()) {
logger.debug("pageletId[" + pageletTask.getPageletInfo().getId() + "] logicMethod[" + pageletTask.getPageletInfo().getLogicMethod() + "] begining... ");
}
try {
logicResult = pageletTask.getPageletInfo().getTimeOut() > -1 ? f.get((long) pageletTask.getPageletInfo().getTimeOut(), TimeUnit.MILLISECONDS) : f.get();
} catch (TimeoutException var11) {
f.cancel(true);
logger.warn(pageletTask.getPageletInfo().getId() + " exec timeout[More than " + pageletTask.getPageletInfo().getTimeOut() + " ms]!");
} catch (Exception var12) {
f.cancel(true);
logger.error(pageletTask.getPageletInfo().getId() + " exec error [" + var12.getMessage() + "]!");
logger.error("pagelet exec error!", var12);
} finally {
logger.debug("pageletId[" + pageletTask.getPageletInfo().getId() + "] logicMethod[" + pageletTask.getPageletInfo().getLogicMethod() + "] end! ... ");
String method = pageletTask.getPageletInfo().getJsMethod();
PageletRenderHelper.renderDynamic(BigPipe.this.ctx, logicResult, method, pageletTask.isLazyExec());
return true;
}
}
};
FutureTask task = new FutureTask(e);
threadPool.submit(task);
allFutureTask.add(task);
}
iterator = allFutureTask.iterator();
while (iterator.hasNext()) {
FutureTask pageletTask1 = (FutureTask) iterator.next();
try {
pageletTask1.get();
} catch (Exception var6) {
logger.error("pagelet exec error!", var6);
}
}
}
}
private void renderSyncPagelet() {
if (null != syncPagelets && syncPagelets.size() > 0) {
for (Pagelet p : syncPagelets) {
Object logicResult = null;
try {
Method m = p.getClass().getMethod(p.getPageletInfo().getLogicMethod(), HttpServletRequest.class, HttpServletResponse.class);
logicResult = (m.invoke(p, ctx.getRequest(), ctx.getResponse()));
} catch (Exception e) {
logger.error("pagelet exec error!", e);
} finally {
//获得js解析方法的名称
String method = p.getPageletInfo().getJsMethod();
//通过js脚本动态填充div
PageletRenderHelper.renderDynamic(ctx, logicResult, method,p.isLazyExec());
}
}
}
}
} | apache-2.0 |
m-m-m/java8-backports | mmm-util-backport-java.time/src/main/java/java/time/zone/TzdbZoneRulesCompiler.java | 38032 | /*
* Copyright (c) 2009-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time.zone;
import static java.time.calendrical.ChronoField.HOUR_OF_DAY;
import static java.time.calendrical.ChronoField.MINUTE_OF_HOUR;
import static java.time.calendrical.ChronoField.SECOND_OF_MINUTE;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParsePosition;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.Year;
import java.time.ZoneOffset;
import java.time.calendrical.DateTimeAdjusters;
import java.time.calendrical.DateTimeBuilder;
import java.time.calendrical.DateTimeField;
import java.time.calendrical.JulianDayField;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.zone.ZoneOffsetTransitionRule.TimeDefinition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
/**
* A builder that can read the TZDB time-zone files and build {@code ZoneRules} instances.
*
* <h4>Implementation notes</h4> This class is a mutable builder. A new instance must be created for each
* compile.
*/
final class TzdbZoneRulesCompiler {
/**
* Time parser.
*/
private static final DateTimeFormatter TIME_PARSER;
static {
TIME_PARSER = new DateTimeFormatterBuilder().appendValue(HOUR_OF_DAY).optionalStart().appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2).optionalStart().appendLiteral(':').appendValue(SECOND_OF_MINUTE, 2)
.toFormatter();
}
/**
* Constant for MJD 1972-01-01.
*/
private static final long MJD_1972_01_01 = 41317L;
/**
* Reads a set of TZDB files and builds a single combined data file.
*
* @param args the arguments
*/
public static void main(String[] args) {
if (args.length < 2) {
outputHelp();
return;
}
// parse args
String version = null;
File baseSrcDir = null;
File dstDir = null;
boolean verbose = false;
// parse options
int i;
for (i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("-") == false) {
break;
}
if ("-srcdir".equals(arg)) {
if (baseSrcDir == null && ++i < args.length) {
baseSrcDir = new File(args[i]);
continue;
}
} else if ("-dstdir".equals(arg)) {
if (dstDir == null && ++i < args.length) {
dstDir = new File(args[i]);
continue;
}
} else if ("-version".equals(arg)) {
if (version == null && ++i < args.length) {
version = args[i];
continue;
}
} else if ("-verbose".equals(arg)) {
if (verbose == false) {
verbose = true;
continue;
}
} else if ("-help".equals(arg) == false) {
System.out.println("Unrecognised option: " + arg);
}
outputHelp();
return;
}
// check source directory
if (baseSrcDir == null) {
System.out.println("Source directory must be specified using -srcdir: " + baseSrcDir);
return;
}
if (baseSrcDir.isDirectory() == false) {
System.out.println("Source does not exist or is not a directory: " + baseSrcDir);
return;
}
dstDir = (dstDir != null ? dstDir : baseSrcDir);
// parse source file names
List<String> srcFileNames = Arrays.asList(Arrays.copyOfRange(args, i, args.length));
if (srcFileNames.isEmpty()) {
System.out.println("Source filenames not specified, using default set");
System.out.println("(africa antarctica asia australasia backward etcetera europe northamerica southamerica)");
srcFileNames = Arrays.asList("africa", "antarctica", "asia", "australasia", "backward", "etcetera", "europe",
"northamerica", "southamerica");
}
// find source directories to process
List<File> srcDirs = new ArrayList<File>();
if (version != null) {
File srcDir = new File(baseSrcDir, version);
if (srcDir.isDirectory() == false) {
System.out.println("Version does not represent a valid source directory : " + srcDir);
return;
}
srcDirs.add(srcDir);
} else {
File[] dirs = baseSrcDir.listFiles();
for (File dir : dirs) {
if (dir.isDirectory() && dir.getName().matches("[12][0-9][0-9][0-9][A-Za-z0-9._-]+")) {
srcDirs.add(dir);
}
}
}
if (srcDirs.isEmpty()) {
System.out.println("Source directory contains no valid source folders: " + baseSrcDir);
return;
}
// check destination directory
if (dstDir.exists() == false && dstDir.mkdirs() == false) {
System.out.println("Destination directory could not be created: " + dstDir);
return;
}
if (dstDir.isDirectory() == false) {
System.out.println("Destination is not a directory: " + dstDir);
return;
}
process(srcDirs, srcFileNames, dstDir, verbose);
System.exit(0);
}
/**
* Output usage text for the command line.
*/
private static void outputHelp() {
System.out.println("Usage: TzdbZoneRulesCompiler <options> <tzdb source filenames>");
System.out.println("where options include:");
System.out.println(" -srcdir <directory> Where to find source directories (required)");
System.out.println(" -dstdir <directory> Where to output generated files (default srcdir)");
System.out.println(" -version <version> Specify the version, such as 2009a (optional)");
System.out.println(" -help Print this usage message");
System.out.println(" -verbose Output verbose information during compilation");
System.out.println(" There must be one directory for each version in srcdir");
System.out.println(" Each directory must have the name of the version, such as 2009a");
System.out.println(" Each directory must contain the unpacked tzdb files, such as asia or europe");
System.out.println(" Directories must match the regex [12][0-9][0-9][0-9][A-Za-z0-9._-]+");
System.out.println(" There will be one jar file for each version and one combined jar in dstdir");
System.out.println(" If the version is specified, only that version is processed");
}
/**
* Process to create the jar files.
*/
private static void process(List<File> srcDirs, List<String> srcFileNames, File dstDir, boolean verbose) {
// build actual jar files
Map<Object, Object> deduplicateMap = new HashMap<Object, Object>();
Map<String, SortedMap<String, ZoneRules>> allBuiltZones = new TreeMap<String, SortedMap<String, ZoneRules>>();
Set<String> allRegionIds = new TreeSet<String>();
Set<ZoneRules> allRules = new HashSet<ZoneRules>();
SortedMap<LocalDate, Byte> bestLeapSeconds = null;
for (File srcDir : srcDirs) {
// source files in this directory
List<File> srcFiles = new ArrayList<File>();
for (String srcFileName : srcFileNames) {
File file = new File(srcDir, srcFileName);
if (file.exists()) {
srcFiles.add(file);
}
}
if (srcFiles.isEmpty()) {
continue; // nothing to process
}
File leapSecondsFile = new File(srcDir, "leapseconds");
if (!leapSecondsFile.exists()) {
System.out.println("Version " + srcDir.getName() + " does not include leap seconds information.");
leapSecondsFile = null;
}
// compile
String loopVersion = srcDir.getName();
TzdbZoneRulesCompiler compiler = new TzdbZoneRulesCompiler(loopVersion, srcFiles, leapSecondsFile, verbose);
compiler.setDeduplicateMap(deduplicateMap);
try {
// compile
compiler.compile();
SortedMap<String, ZoneRules> builtZones = compiler.getZones();
SortedMap<LocalDate, Byte> parsedLeapSeconds = compiler.getLeapSeconds();
// output version-specific file
File dstFile = new File(dstDir, "jsr-310-TZDB-" + loopVersion + ".jar");
if (verbose) {
System.out.println("Outputting file: " + dstFile);
}
outputFile(dstFile, loopVersion, builtZones, parsedLeapSeconds);
// create totals
allBuiltZones.put(loopVersion, builtZones);
allRegionIds.addAll(builtZones.keySet());
allRules.addAll(builtZones.values());
// track best possible leap seconds collection
if (compiler.getMostRecentLeapSecond() != null) {
// we've got a live one!
if (bestLeapSeconds == null || compiler.getMostRecentLeapSecond().compareTo(bestLeapSeconds.lastKey()) > 0) {
// found the first one, or found a better one
bestLeapSeconds = parsedLeapSeconds;
}
}
} catch (Exception ex) {
System.out.println("Failed: " + ex.toString());
ex.printStackTrace();
System.exit(1);
}
}
// output merged file
File dstFile = new File(dstDir, "jsr-310-TZDB-all.jar");
if (verbose) {
System.out.println("Outputting combined file: " + dstFile);
}
outputFile(dstFile, allBuiltZones, allRegionIds, allRules, bestLeapSeconds);
}
/**
* Outputs the file.
*/
private static void outputFile(File dstFile, String version, SortedMap<String, ZoneRules> builtZones,
SortedMap<LocalDate, Byte> leapSeconds) {
Map<String, SortedMap<String, ZoneRules>> loopAllBuiltZones = new TreeMap<String, SortedMap<String, ZoneRules>>();
loopAllBuiltZones.put(version, builtZones);
Set<String> loopAllRegionIds = new TreeSet<String>(builtZones.keySet());
Set<ZoneRules> loopAllRules = new HashSet<ZoneRules>(builtZones.values());
outputFile(dstFile, loopAllBuiltZones, loopAllRegionIds, loopAllRules, leapSeconds);
}
/**
* Outputs the file.
*/
private static void outputFile(File dstFile, Map<String, SortedMap<String, ZoneRules>> allBuiltZones,
Set<String> allRegionIds, Set<ZoneRules> allRules, SortedMap<LocalDate, Byte> leapSeconds) {
// try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(dstFile))) {
JarOutputStream jos = null;
try {
jos = new JarOutputStream(new FileOutputStream(dstFile));
outputTZEntry(jos, allBuiltZones, allRegionIds, allRules);
outputLeapSecondEntry(jos, leapSeconds);
} catch (Exception ex) {
System.out.println("Failed: " + ex.toString());
ex.printStackTrace();
System.exit(1);
} finally {
if (jos != null) {
try {
jos.close();
} catch (IOException e) {
// ignore to prevent supression of potential important exception
}
}
}
}
/**
* Outputs the timezone entry in the JAR file.
*/
private static void outputTZEntry(JarOutputStream jos, Map<String, SortedMap<String, ZoneRules>> allBuiltZones,
Set<String> allRegionIds, Set<ZoneRules> allRules) {
// this format is not publicly specified
try {
jos.putNextEntry(new ZipEntry("javax/time/zone/TZDB.dat"));
DataOutputStream out = new DataOutputStream(jos);
// file version
out.writeByte(1);
// group
out.writeUTF("TZDB");
// versions
String[] versionArray = allBuiltZones.keySet().toArray(new String[allBuiltZones.size()]);
out.writeShort(versionArray.length);
for (String version : versionArray) {
out.writeUTF(version);
}
// regions
String[] regionArray = allRegionIds.toArray(new String[allRegionIds.size()]);
out.writeShort(regionArray.length);
for (String regionId : regionArray) {
out.writeUTF(regionId);
}
// rules
List<ZoneRules> rulesList = new ArrayList<ZoneRules>(allRules);
out.writeShort(rulesList.size());
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
for (ZoneRules rules : rulesList) {
baos.reset();
DataOutputStream dataos = new DataOutputStream(baos);
Ser.write(rules, dataos);
dataos.close();
byte[] bytes = baos.toByteArray();
out.writeShort(bytes.length);
out.write(bytes);
}
// link version-region-rules
for (String version : allBuiltZones.keySet()) {
out.writeShort(allBuiltZones.get(version).size());
for (Map.Entry<String, ZoneRules> entry : allBuiltZones.get(version).entrySet()) {
int regionIndex = Arrays.binarySearch(regionArray, entry.getKey());
int rulesIndex = rulesList.indexOf(entry.getValue());
out.writeShort(regionIndex);
out.writeShort(rulesIndex);
}
}
out.flush();
jos.closeEntry();
} catch (Exception ex) {
System.out.println("Failed: " + ex.toString());
ex.printStackTrace();
System.exit(1);
}
}
/**
* Outputs the leap second entries in the JAR file.
*/
private static void outputLeapSecondEntry(JarOutputStream jos, SortedMap<LocalDate, Byte> leapSeconds) {
// this format is not publicly specified
try {
jos.putNextEntry(new ZipEntry("javax/time/LeapSecondRules.dat"));
DataOutputStream out = new DataOutputStream(jos);
// file version
out.writeByte(1);
// count
out.writeInt(leapSeconds.size() + 1);
// first line is fixed in UTC-TAI leap second system, always 10 seconds at 1972-01-01
int offset = 10;
out.writeLong(MJD_1972_01_01);
out.writeInt(offset);
// now treat all the transitions
for (Map.Entry<LocalDate, Byte> rule : leapSeconds.entrySet()) {
out.writeLong(JulianDayField.MODIFIED_JULIAN_DAY.doGet(rule.getKey()));
offset += rule.getValue();
out.writeInt(offset);
}
out.flush();
jos.closeEntry();
} catch (Exception ex) {
System.out.println("Failed: " + ex.toString());
ex.printStackTrace();
System.exit(1);
}
}
// -----------------------------------------------------------------------
/** The TZDB rules. */
private final Map<String, List<TZDBRule>> rules = new HashMap<String, List<TZDBRule>>();
/** The TZDB zones. */
private final Map<String, List<TZDBZone>> zones = new HashMap<String, List<TZDBZone>>();
/** The TZDB links. */
private final Map<String, String> links = new HashMap<String, String>();
/** The built zones. */
private final SortedMap<String, ZoneRules> builtZones = new TreeMap<String, ZoneRules>();
/** A map to deduplicate object instances. */
private Map<Object, Object> deduplicateMap = new HashMap<Object, Object>();
/** Sorted collection of LeapSecondRules. */
private final SortedMap<LocalDate, Byte> leapSeconds = new TreeMap<LocalDate, Byte>();
/** The version to produce. */
private final String version;
/** The source files. */
private final List<File> sourceFiles;
/** The leap seconds file. */
private final File leapSecondsFile;
/** The version to produce. */
private final boolean verbose;
/**
* Creates an instance if you want to invoke the compiler manually.
*
* @param version the version, such as 2009a, not null
* @param sourceFiles the list of source files, not empty, not null
* @param verbose whether to output verbose messages
*/
public TzdbZoneRulesCompiler(String version, List<File> sourceFiles, File leapSecondsFile, boolean verbose) {
this.version = version;
this.sourceFiles = sourceFiles;
this.leapSecondsFile = leapSecondsFile;
this.verbose = verbose;
}
/**
* Compile the rules file.
* <p>
* Use {@link #getZones()} and {@link #getLeapSeconds()} to retrieve the parsed data.
*
* @throws Exception if an error occurs
*/
public void compile() throws Exception {
printVerbose("Compiling TZDB version " + this.version);
parseFiles();
parseLeapSecondsFile();
buildZoneRules();
printVerbose("Compiled TZDB version " + this.version);
}
/**
* Gets the parsed zone rules.
*
* @return the parsed zone rules, not null
*/
public SortedMap<String, ZoneRules> getZones() {
return this.builtZones;
}
/**
* Gets the parsed leap seconds.
*
* @return the parsed and sorted leap seconds, not null
*/
public SortedMap<LocalDate, Byte> getLeapSeconds() {
return this.leapSeconds;
}
/**
* Gets the most recent leap second.
*
* @return the most recent leap second, null if none
*/
private LocalDate getMostRecentLeapSecond() {
return this.leapSeconds.isEmpty() ? null : this.leapSeconds.lastKey();
}
/**
* Sets the deduplication map.
*
* @param deduplicateMap the map to deduplicate items
*/
void setDeduplicateMap(Map<Object, Object> deduplicateMap) {
this.deduplicateMap = deduplicateMap;
}
// -----------------------------------------------------------------------
/**
* Parses the source files.
*
* @throws Exception if an error occurs
*/
private void parseFiles() throws Exception {
for (File file : this.sourceFiles) {
printVerbose("Parsing file: " + file);
parseFile(file);
}
}
/**
* Parses the leap seconds file.
*
* @throws Exception if an error occurs
*/
private void parseLeapSecondsFile() throws Exception {
printVerbose("Parsing leap second file: " + this.leapSecondsFile);
int lineNumber = 1;
String line = null;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(this.leapSecondsFile));
for (; (line = in.readLine()) != null; lineNumber++) {
int index = line.indexOf('#'); // remove comments (doesn't handle # in quotes)
if (index >= 0) {
line = line.substring(0, index);
}
if (line.trim().length() == 0) { // ignore blank lines
continue;
}
LeapSecondRule secondRule = parseLeapSecondRule(line);
this.leapSeconds.put(secondRule.leapDate, secondRule.secondAdjustment);
}
} catch (Exception ex) {
throw new Exception("Failed while processing file '" + this.leapSecondsFile + "' on line " + lineNumber + " '"
+ line + "'", ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
// ignore NPE and IOE
}
}
}
private LeapSecondRule parseLeapSecondRule(String line) {
// # Leap YEAR MONTH DAY HH:MM:SS CORR R/S
// Leap 1972 Jun 30 23:59:60 + S
// Leap 1972 Dec 31 23:59:60 + S
// Leap 1973 Dec 31 23:59:60 + S
// Leap 1974 Dec 31 23:59:60 + S
// Leap 1975 Dec 31 23:59:60 + S
// Leap 1976 Dec 31 23:59:60 + S
// Leap 1977 Dec 31 23:59:60 + S
// Leap 1978 Dec 31 23:59:60 + S
// Leap 1979 Dec 31 23:59:60 + S
// Leap 1981 Jun 30 23:59:60 + S
// Leap 1982 Jun 30 23:59:60 + S
// Leap 1983 Jun 30 23:59:60 + S
StringTokenizer st = new StringTokenizer(line, " \t");
String first = st.nextToken();
if (first.equals("Leap")) {
if (st.countTokens() < 6) {
printVerbose("Invalid leap second line in file: " + this.leapSecondsFile + ", line: " + line);
throw new IllegalArgumentException("Invalid leap second line");
}
} else {
throw new IllegalArgumentException("Unknown line");
}
int year = Integer.parseInt(st.nextToken());
Month month = parseMonth(st.nextToken());
int dayOfMonth = Integer.parseInt(st.nextToken());
LocalDate leapDate = LocalDate.of(year, month, dayOfMonth);
String timeOfLeapSecond = st.nextToken();
byte adjustmentByte = 0;
String adjustment = st.nextToken();
if (adjustment.equals("+")) {
if (!("23:59:60".equals(timeOfLeapSecond))) {
throw new IllegalArgumentException("Leap seconds can only be inserted at 23:59:60 - Date:" + leapDate);
}
adjustmentByte = +1;
} else if (adjustment.equals("-")) {
if (!("23:59:59".equals(timeOfLeapSecond))) {
throw new IllegalArgumentException("Leap seconds can only be removed at 23:59:59 - Date:" + leapDate);
}
adjustmentByte = -1;
} else {
throw new IllegalArgumentException("Invalid adjustment '" + adjustment + "' in leap second rule for " + leapDate);
}
String rollingOrStationary = st.nextToken();
if (!"S".equalsIgnoreCase(rollingOrStationary)) {
throw new IllegalArgumentException("Only stationary ('S') leap seconds are supported, not '"
+ rollingOrStationary + "'");
}
return new LeapSecondRule(leapDate, adjustmentByte);
}
/**
* Parses a source file.
*
* @param file the file being read, not null
* @throws Exception if an error occurs
*/
private void parseFile(File file) throws Exception {
int lineNumber = 1;
String line = null;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
List<TZDBZone> openZone = null;
for (; (line = in.readLine()) != null; lineNumber++) {
int index = line.indexOf('#'); // remove comments (doesn't handle # in quotes)
if (index >= 0) {
line = line.substring(0, index);
}
if (line.trim().length() == 0) { // ignore blank lines
continue;
}
StringTokenizer st = new StringTokenizer(line, " \t");
if (openZone != null && Character.isWhitespace(line.charAt(0)) && st.hasMoreTokens()) {
if (parseZoneLine(st, openZone)) {
openZone = null;
}
} else {
if (st.hasMoreTokens()) {
String first = st.nextToken();
if (first.equals("Zone")) {
if (st.countTokens() < 3) {
printVerbose("Invalid Zone line in file: " + file + ", line: " + line);
throw new IllegalArgumentException("Invalid Zone line");
}
openZone = new ArrayList<TZDBZone>();
this.zones.put(st.nextToken(), openZone);
if (parseZoneLine(st, openZone)) {
openZone = null;
}
} else {
openZone = null;
if (first.equals("Rule")) {
if (st.countTokens() < 9) {
printVerbose("Invalid Rule line in file: " + file + ", line: " + line);
throw new IllegalArgumentException("Invalid Rule line");
}
parseRuleLine(st);
} else if (first.equals("Link")) {
if (st.countTokens() < 2) {
printVerbose("Invalid Link line in file: " + file + ", line: " + line);
throw new IllegalArgumentException("Invalid Link line");
}
String realId = st.nextToken();
String aliasId = st.nextToken();
this.links.put(aliasId, realId);
} else {
throw new IllegalArgumentException("Unknown line");
}
}
}
}
}
} catch (Exception ex) {
throw new Exception("Failed while processing file '" + file + "' on line " + lineNumber + " '" + line + "'", ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
// ignore NPE and IOE
}
}
}
/**
* Parses a Rule line.
*
* @param st the tokenizer, not null
*/
private void parseRuleLine(StringTokenizer st) {
TZDBRule rule = new TZDBRule();
String name = st.nextToken();
if (this.rules.containsKey(name) == false) {
this.rules.put(name, new ArrayList<TZDBRule>());
}
this.rules.get(name).add(rule);
rule.startYear = parseYear(st.nextToken(), 0);
rule.endYear = parseYear(st.nextToken(), rule.startYear);
if (rule.startYear > rule.endYear) {
throw new IllegalArgumentException("Year order invalid: " + rule.startYear + " > " + rule.endYear);
}
parseOptional(st.nextToken()); // type is unused
parseMonthDayTime(st, rule);
rule.savingsAmount = parsePeriod(st.nextToken());
rule.text = parseOptional(st.nextToken());
}
/**
* Parses a Zone line.
*
* @param st the tokenizer, not null
* @return true if the zone is complete
*/
private boolean parseZoneLine(StringTokenizer st, List<TZDBZone> zoneList) {
TZDBZone zone = new TZDBZone();
zoneList.add(zone);
zone.standardOffset = parseOffset(st.nextToken());
String savingsRule = parseOptional(st.nextToken());
if (savingsRule == null) {
zone.fixedSavingsSecs = 0;
zone.savingsRule = null;
} else {
try {
zone.fixedSavingsSecs = parsePeriod(savingsRule);
zone.savingsRule = null;
} catch (Exception ex) {
zone.fixedSavingsSecs = null;
zone.savingsRule = savingsRule;
}
}
zone.text = st.nextToken();
if (st.hasMoreTokens()) {
zone.year = Year.of(Integer.parseInt(st.nextToken()));
if (st.hasMoreTokens()) {
parseMonthDayTime(st, zone);
}
return false;
} else {
return true;
}
}
/**
* Parses a Rule line.
*
* @param st the tokenizer, not null
* @param mdt the object to parse into, not null
*/
private void parseMonthDayTime(StringTokenizer st, TZDBMonthDayTime mdt) {
mdt.month = parseMonth(st.nextToken());
if (st.hasMoreTokens()) {
String dayRule = st.nextToken();
if (dayRule.startsWith("last")) {
mdt.dayOfMonth = -1;
mdt.dayOfWeek = parseDayOfWeek(dayRule.substring(4));
mdt.adjustForwards = false;
} else {
int index = dayRule.indexOf(">=");
if (index > 0) {
mdt.dayOfWeek = parseDayOfWeek(dayRule.substring(0, index));
dayRule = dayRule.substring(index + 2);
} else {
index = dayRule.indexOf("<=");
if (index > 0) {
mdt.dayOfWeek = parseDayOfWeek(dayRule.substring(0, index));
mdt.adjustForwards = false;
dayRule = dayRule.substring(index + 2);
}
}
mdt.dayOfMonth = Integer.parseInt(dayRule);
}
if (st.hasMoreTokens()) {
String timeStr = st.nextToken();
int secsOfDay = parseSecs(timeStr);
if (secsOfDay == 86400) {
mdt.endOfDay = true;
secsOfDay = 0;
}
LocalTime time = deduplicate(LocalTime.ofSecondOfDay(secsOfDay));
mdt.time = time;
mdt.timeDefinition = parseTimeDefinition(timeStr.charAt(timeStr.length() - 1));
}
}
}
private int parseYear(String str, int defaultYear) {
str = str.toLowerCase();
if (matches(str, "minimum")) {
return Year.MIN_YEAR;
} else if (matches(str, "maximum")) {
return Year.MAX_YEAR;
} else if (str.equals("only")) {
return defaultYear;
}
return Integer.parseInt(str);
}
private Month parseMonth(String str) {
str = str.toLowerCase();
for (Month moy : Month.values()) {
if (matches(str, moy.name().toLowerCase())) {
return moy;
}
}
throw new IllegalArgumentException("Unknown month: " + str);
}
private DayOfWeek parseDayOfWeek(String str) {
str = str.toLowerCase();
for (DayOfWeek dow : DayOfWeek.values()) {
if (matches(str, dow.name().toLowerCase())) {
return dow;
}
}
throw new IllegalArgumentException("Unknown day-of-week: " + str);
}
private boolean matches(String str, String search) {
return str.startsWith(search.substring(0, 3)) && search.startsWith(str) && str.length() <= search.length();
}
private String parseOptional(String str) {
return str.equals("-") ? null : str;
}
private int parseSecs(String str) {
if (str.equals("-")) {
return 0;
}
int pos = 0;
if (str.startsWith("-")) {
pos = 1;
}
ParsePosition pp = new ParsePosition(pos);
DateTimeBuilder bld = TIME_PARSER.parseToBuilder(str, pp);
if (bld == null || pp.getErrorIndex() >= 0) {
throw new IllegalArgumentException(str);
}
Map<DateTimeField, Long> parsed = bld.getFieldValueMap();
long hour = parsed.get(HOUR_OF_DAY);
Long min = parsed.get(MINUTE_OF_HOUR);
Long sec = parsed.get(SECOND_OF_MINUTE);
int secs = (int) (hour * 60 * 60 + (min != null ? min : 0) * 60 + (sec != null ? sec : 0));
if (pos == 1) {
secs = -secs;
}
return secs;
}
private ZoneOffset parseOffset(String str) {
int secs = parseSecs(str);
return ZoneOffset.ofTotalSeconds(secs);
}
private int parsePeriod(String str) {
return parseSecs(str);
}
private TimeDefinition parseTimeDefinition(char c) {
switch (c) {
case 's':
case 'S':
// standard time
return TimeDefinition.STANDARD;
case 'u':
case 'U':
case 'g':
case 'G':
case 'z':
case 'Z':
// UTC
return TimeDefinition.UTC;
case 'w':
case 'W':
default :
// wall time
return TimeDefinition.WALL;
}
}
// -----------------------------------------------------------------------
/**
* Build the rules, zones and links into real zones.
*
* @throws Exception if an error occurs
*/
private void buildZoneRules() throws Exception {
// build zones
for (String zoneId : this.zones.keySet()) {
printVerbose("Building zone " + zoneId);
zoneId = deduplicate(zoneId);
List<TZDBZone> tzdbZones = this.zones.get(zoneId);
ZoneRulesBuilder bld = new ZoneRulesBuilder();
for (TZDBZone tzdbZone : tzdbZones) {
bld = tzdbZone.addToBuilder(bld, this.rules);
}
ZoneRules buildRules = bld.toRules(zoneId, this.deduplicateMap);
this.builtZones.put(zoneId, deduplicate(buildRules));
}
// build aliases
for (String aliasId : this.links.keySet()) {
aliasId = deduplicate(aliasId);
String realId = this.links.get(aliasId);
printVerbose("Linking alias " + aliasId + " to " + realId);
ZoneRules realRules = this.builtZones.get(realId);
if (realRules == null) {
realId = this.links.get(realId); // try again (handle alias liked to alias)
printVerbose("Relinking alias " + aliasId + " to " + realId);
realRules = this.builtZones.get(realId);
if (realRules == null) {
throw new IllegalArgumentException("Alias '" + aliasId + "' links to invalid zone '" + realId + "' for '"
+ this.version + "'");
}
}
this.builtZones.put(aliasId, realRules);
}
// remove UTC and GMT
this.builtZones.remove("UTC");
this.builtZones.remove("GMT");
this.builtZones.remove("GMT0");
this.builtZones.remove("GMT+0");
this.builtZones.remove("GMT-0");
}
// -----------------------------------------------------------------------
/**
* Deduplicates an object instance.
*
* @param <T> the generic type
* @param object the object to deduplicate
* @return the deduplicated object
*/
@SuppressWarnings("unchecked")
<T> T deduplicate(T object) {
if (this.deduplicateMap.containsKey(object) == false) {
this.deduplicateMap.put(object, object);
}
return (T) this.deduplicateMap.get(object);
}
// -----------------------------------------------------------------------
/**
* Prints a verbose message.
*
* @param message the message, not null
*/
private void printVerbose(String message) {
if (this.verbose) {
System.out.println(message);
}
}
// -----------------------------------------------------------------------
/**
* Class representing a month-day-time in the TZDB file.
*/
abstract class TZDBMonthDayTime {
/** The month of the cutover. */
Month month = Month.JANUARY;
/** The day-of-month of the cutover. */
int dayOfMonth = 1;
/** Whether to adjust forwards. */
boolean adjustForwards = true;
/** The day-of-week of the cutover. */
DayOfWeek dayOfWeek;
/** The time of the cutover. */
LocalTime time = LocalTime.MIDNIGHT;
/** Whether this is midnight end of day. */
boolean endOfDay;
/** The time of the cutover. */
TimeDefinition timeDefinition = TimeDefinition.WALL;
void adjustToFowards(int year) {
if (this.adjustForwards == false && this.dayOfMonth > 0) {
LocalDate adjustedDate = LocalDate.of(year, this.month, this.dayOfMonth).minusDays(6);
this.dayOfMonth = adjustedDate.getDayOfMonth();
this.month = adjustedDate.getMonth();
this.adjustForwards = true;
}
}
}
// -----------------------------------------------------------------------
/**
* Class representing a rule line in the TZDB file.
*/
final class TZDBRule extends TZDBMonthDayTime {
/** The start year. */
int startYear;
/** The end year. */
int endYear;
/** The amount of savings. */
int savingsAmount;
/** The text name of the zone. */
String text;
void addToBuilder(ZoneRulesBuilder bld) {
adjustToFowards(2004); // irrelevant, treat as leap year
bld.addRuleToWindow(this.startYear, this.endYear, this.month, this.dayOfMonth, this.dayOfWeek, this.time,
this.endOfDay, this.timeDefinition, this.savingsAmount);
}
}
// -----------------------------------------------------------------------
/**
* Class representing a linked set of zone lines in the TZDB file.
*/
final class TZDBZone extends TZDBMonthDayTime {
/** The standard offset. */
ZoneOffset standardOffset;
/** The fixed savings amount. */
Integer fixedSavingsSecs;
/** The savings rule. */
String savingsRule;
/** The text name of the zone. */
String text;
/** The year of the cutover. */
Year year;
ZoneRulesBuilder addToBuilder(ZoneRulesBuilder bld, Map<String, List<TZDBRule>> rules) {
if (this.year != null) {
bld.addWindow(this.standardOffset, toDateTime(this.year.getValue()), this.timeDefinition);
} else {
bld.addWindowForever(this.standardOffset);
}
if (this.fixedSavingsSecs != null) {
bld.setFixedSavingsToWindow(this.fixedSavingsSecs);
} else {
List<TZDBRule> tzdbRules = rules.get(this.savingsRule);
if (tzdbRules == null) {
throw new IllegalArgumentException("Rule not found: " + this.savingsRule);
}
for (TZDBRule tzdbRule : tzdbRules) {
tzdbRule.addToBuilder(bld);
}
}
return bld;
}
private LocalDateTime toDateTime(int year) {
adjustToFowards(year);
LocalDate date;
if (this.dayOfMonth == -1) {
this.dayOfMonth = this.month.length(Year.isLeap(year));
date = LocalDate.of(year, this.month, this.dayOfMonth);
if (this.dayOfWeek != null) {
date = date.with(DateTimeAdjusters.previousOrSame(this.dayOfWeek));
}
} else {
date = LocalDate.of(year, this.month, this.dayOfMonth);
if (this.dayOfWeek != null) {
date = date.with(DateTimeAdjusters.nextOrSame(this.dayOfWeek));
}
}
date = deduplicate(date);
LocalDateTime ldt = LocalDateTime.of(date, this.time);
if (this.endOfDay) {
ldt = ldt.plusDays(1);
}
return ldt;
}
}
// -----------------------------------------------------------------------
/**
* Class representing a rule line in the TZDB file.
*/
public static final class LeapSecondRule {
/**
* Constructs a rule using fields.
*
* @param leapDate Date which has gets leap second adjustment (at the end)
* @param secondAdjustment +1 or -1 for inserting or dropping a second
*/
public LeapSecondRule(LocalDate leapDate, byte secondAdjustment) {
this.leapDate = leapDate;
this.secondAdjustment = secondAdjustment;
}
/** The date of the leap second. */
final LocalDate leapDate;
/**
* The adjustment (in seconds), +1 means a second is inserted, -1 means a second is dropped.
*/
byte secondAdjustment;
}
}
| apache-2.0 |
rdblue/incubator-nifi | nar-bundles/framework-bundle/framework/web/nifi-web-api/src/main/java/org/apache/nifi/audit/RelationshipAuditor.java | 18356 | /*
* 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.audit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.apache.nifi.action.Action;
import org.apache.nifi.action.Component;
import org.apache.nifi.action.Operation;
import org.apache.nifi.action.details.ActionDetails;
import org.apache.nifi.action.details.ConfigureDetails;
import org.apache.nifi.action.details.ConnectDetails;
import org.apache.nifi.connectable.Connectable;
import org.apache.nifi.connectable.Connection;
import org.apache.nifi.connectable.Funnel;
import org.apache.nifi.connectable.Port;
import org.apache.nifi.controller.ProcessorNode;
import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.flowfile.FlowFilePrioritizer;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.remote.RemoteGroupPort;
import org.apache.nifi.remote.TransferDirection;
import org.apache.nifi.web.security.user.NiFiUserUtils;
import org.apache.nifi.user.NiFiUser;
import org.apache.nifi.web.api.dto.ConnectionDTO;
import org.apache.nifi.web.dao.ConnectionDAO;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Audits relationship creation/removal.
*/
@Aspect
public class RelationshipAuditor extends NiFiAuditor {
private static final Logger logger = LoggerFactory.getLogger(RelationshipAuditor.class);
private static final String NAME = "Name";
private static final String FLOW_FILE_EXPIRATION = "File Expiration";
private static final String BACK_PRESSURE_OBJECT_THRESHOLD = "Back Pressure Object Threshold";
private static final String BACK_PRESSURE_DATA_SIZE_THRESHOLD = "Back Pressure Data Size Threshold";
private static final String PRIORITIZERS = "Prioritizers";
/**
* Audits the creation of relationships via createConnection().
*
* This method only needs to be run 'after returning'. However, in Java 7
* the order in which these methods are returned from
* Class.getDeclaredMethods (even though there is no order guaranteed) seems
* to differ from Java 6. SpringAOP depends on this ordering to determine
* advice precedence. By normalizing all advice into Around advice we can
* alleviate this issue.
*
* @param connection
*/
// @AfterReturning(
// pointcut="within(org.apache.nifi.view.dao.ConnectionDAO+) && "
// + "execution(org.apache.nifi.view.model.Connection createConnection(org.apache.nifi.api.dto.ConnectionDTO))",
// returning="connection"
// )
@Around("within(org.apache.nifi.web.dao.ConnectionDAO+) && "
+ "execution(org.apache.nifi.connectable.Connection createConnection(java.lang.String, org.apache.nifi.web.api.dto.ConnectionDTO))")
public Object createConnectionAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// perform the underlying operation
Connection connection = (Connection) proceedingJoinPoint.proceed();
// audit the connection creation
final ConnectDetails connectDetails = createConnectDetails(connection, connection.getRelationships());
final Action action = generateAuditRecordForConnection(connection, Operation.Connect, connectDetails);
// save the actions
if (action != null) {
saveAction(action, logger);
}
return connection;
}
/**
* Audits the creation and removal of relationships via updateConnection().
*
* @param proceedingJoinPoint
* @param connectionDTO
* @param connectionDAO
* @return
* @throws Throwable
*/
@Around("within(org.apache.nifi.web.dao.ConnectionDAO+) && "
+ "execution(org.apache.nifi.connectable.Connection updateConnection(java.lang.String, org.apache.nifi.web.api.dto.ConnectionDTO)) && "
+ "args(groupId, connectionDTO) && "
+ "target(connectionDAO)")
public Object updateConnectionAdvice(ProceedingJoinPoint proceedingJoinPoint, String groupId, ConnectionDTO connectionDTO, ConnectionDAO connectionDAO) throws Throwable {
// get the previous configuration
Connection connection = connectionDAO.getConnection(groupId, connectionDTO.getId());
Connectable previousDestination = connection.getDestination();
Collection<Relationship> previousRelationships = connection.getRelationships();
Map<String, String> values = extractConfiguredPropertyValues(connection, connectionDTO);
// perform the underlying operation
connection = (Connection) proceedingJoinPoint.proceed();
// get the current user
NiFiUser user = NiFiUserUtils.getNiFiUser();
// ensure the user was found
if (user != null) {
Collection<Action> actions = new ArrayList<>();
Map<String, String> updatedValues = extractConfiguredPropertyValues(connection, connectionDTO);
// get the source
Connectable source = connection.getSource();
// get the current target
Connectable destination = connection.getDestination();
// determine if a new target was specified in the initial request
if (destination != null && !previousDestination.getIdentifier().equals(destination.getIdentifier())) {
// record the removal of all relationships from the previous target
final ConnectDetails disconnectDetails = createConnectDetails(connection, source, previousRelationships, previousDestination);
actions.add(generateAuditRecordForConnection(connection, Operation.Disconnect, disconnectDetails));
// record the addition of all relationships to the new target
final ConnectDetails connectDetails = createConnectDetails(connection, connection.getRelationships());
actions.add(generateAuditRecordForConnection(connection, Operation.Connect, connectDetails));
}
// audit and relationships added/removed
Collection<Relationship> newRelationships = connection.getRelationships();
// identify any relationships that were added
if (newRelationships != null) {
List<Relationship> relationshipsToAdd = new ArrayList<>(newRelationships);
if (previousRelationships != null) {
relationshipsToAdd.removeAll(previousRelationships);
}
if (!relationshipsToAdd.isEmpty()) {
final ConnectDetails connectDetails = createConnectDetails(connection, relationshipsToAdd);
actions.add(generateAuditRecordForConnection(connection, Operation.Connect, connectDetails));
}
}
// identify any relationships that were removed
if (previousRelationships != null) {
List<Relationship> relationshipsToRemove = new ArrayList<>(previousRelationships);
if (newRelationships != null) {
relationshipsToRemove.removeAll(newRelationships);
}
if (!relationshipsToRemove.isEmpty()) {
final ConnectDetails connectDetails = createConnectDetails(connection, relationshipsToRemove);
actions.add(generateAuditRecordForConnection(connection, Operation.Disconnect, connectDetails));
}
}
// go through each updated value
Date actionTimestamp = new Date();
for (String property : updatedValues.keySet()) {
String newValue = updatedValues.get(property);
String oldValue = values.get(property);
// ensure the value is changing
if (oldValue == null || newValue == null || !newValue.equals(oldValue)) {
// create the config details
ConfigureDetails configurationDetails = new ConfigureDetails();
configurationDetails.setName(property);
configurationDetails.setValue(newValue);
configurationDetails.setPreviousValue(oldValue);
// create a configuration action
Action configurationAction = new Action();
configurationAction.setUserDn(user.getDn());
configurationAction.setUserName(user.getUserName());
configurationAction.setOperation(Operation.Configure);
configurationAction.setTimestamp(actionTimestamp);
configurationAction.setSourceId(connection.getIdentifier());
configurationAction.setSourceName(connection.getName());
configurationAction.setSourceType(Component.Connection);
configurationAction.setActionDetails(configurationDetails);
actions.add(configurationAction);
}
}
// save the actions
if (!actions.isEmpty()) {
saveActions(actions, logger);
}
}
return connection;
}
/**
* Audits the removal of relationships via deleteConnection().
*
* @param proceedingJoinPoint
* @param id
* @param connectionDAO
* @throws Throwable
*/
@Around("within(org.apache.nifi.web.dao.ConnectionDAO+) && "
+ "execution(void deleteConnection(java.lang.String, java.lang.String)) && "
+ "args(groupId, id) && "
+ "target(connectionDAO)")
public void removeConnectionAdvice(ProceedingJoinPoint proceedingJoinPoint, String groupId, String id, ConnectionDAO connectionDAO) throws Throwable {
// get the connection before performing the update
Connection connection = connectionDAO.getConnection(groupId, id);
// perform the underlying operation
proceedingJoinPoint.proceed();
// audit the connection creation
final ConnectDetails connectDetails = createConnectDetails(connection, connection.getRelationships());
final Action action = generateAuditRecordForConnection(connection, Operation.Disconnect, connectDetails);
// save the actions
if (action != null) {
saveAction(action, logger);
}
}
public ConnectDetails createConnectDetails(final Connection connection, final Collection<Relationship> relationships) {
return createConnectDetails(connection, connection.getSource(), relationships, connection.getDestination());
}
/**
* Creates action details for connect/disconnect actions.
*
* @param connection
* @param relationships
* @return
*/
public ConnectDetails createConnectDetails(final Connection connection, final Connectable source, final Collection<Relationship> relationships, final Connectable destination) {
final Component sourceType = determineConnectableType(source);
final Component destiantionType = determineConnectableType(destination);
// format the relationship names
Collection<String> relationshipNames = new HashSet<>(connection.getRelationships().size());
for (final Relationship relationship : relationships) {
relationshipNames.add(relationship.getName());
}
final String formattedRelationships = relationshipNames.isEmpty() ? StringUtils.EMPTY : StringUtils.join(relationshipNames, ", ");
// create the connect details
final ConnectDetails connectDetails = new ConnectDetails();
connectDetails.setSourceId(source.getIdentifier());
connectDetails.setSourceName(source.getName());
connectDetails.setSourceType(sourceType);
connectDetails.setRelationship(formattedRelationships);
connectDetails.setDestinationId(destination.getIdentifier());
connectDetails.setDestinationName(destination.getName());
connectDetails.setDestinationType(destiantionType);
return connectDetails;
}
/**
* Extracts configured settings from the specified connection only if they
* have also been specified in the connectionDTO.
*
* @param connection
* @param connectionDTO
* @return
*/
private Map<String, String> extractConfiguredPropertyValues(Connection connection, ConnectionDTO connectionDTO) {
Map<String, String> values = new HashMap<>();
if (connectionDTO.getName() != null) {
values.put(NAME, connection.getName());
}
if (connectionDTO.getFlowFileExpiration() != null) {
values.put(FLOW_FILE_EXPIRATION, String.valueOf(connection.getFlowFileQueue().getFlowFileExpiration()));
}
if (connectionDTO.getBackPressureObjectThreshold() != null) {
values.put(BACK_PRESSURE_OBJECT_THRESHOLD, String.valueOf(connection.getFlowFileQueue().getBackPressureObjectThreshold()));
}
if (connectionDTO.getBackPressureDataSizeThreshold() != null) {
values.put(BACK_PRESSURE_DATA_SIZE_THRESHOLD, String.valueOf(connection.getFlowFileQueue().getBackPressureDataSizeThreshold()));
}
if (connectionDTO.getPrioritizers() != null) {
List<String> prioritizers = new ArrayList<>();
for (FlowFilePrioritizer prioritizer : connection.getFlowFileQueue().getPriorities()) {
prioritizers.add(prioritizer.getClass().getCanonicalName());
}
values.put(PRIORITIZERS, StringUtils.join(prioritizers, ", "));
}
return values;
}
/**
* Generates the audit records for the specified connection.
*
* @param connection
* @param operation
* @return
*/
public Action generateAuditRecordForConnection(Connection connection, Operation operation) {
return generateAuditRecordForConnection(connection, operation, null);
}
/**
* Generates the audit records for the specified connection.
*
* @param connection
* @param operation
* @return
*/
public Action generateAuditRecordForConnection(Connection connection, Operation operation, ActionDetails actionDetails) {
Action action = null;
// get the current user
NiFiUser user = NiFiUserUtils.getNiFiUser();
// ensure the user was found
if (user != null) {
// determine the source details
final String connectionId = connection.getIdentifier();
String connectionName = connection.getName();
if (StringUtils.isBlank(connectionName)) {
Collection<String> relationshipNames = new HashSet<>(connection.getRelationships().size());
for (final Relationship relationship : connection.getRelationships()) {
relationshipNames.add(relationship.getName());
}
connectionName = StringUtils.join(relationshipNames, ", ");
}
// go through each relationship added
Date actionTimestamp = new Date();
// create a new relationship action
action = new Action();
action.setUserDn(user.getDn());
action.setUserName(user.getUserName());
action.setOperation(operation);
action.setTimestamp(actionTimestamp);
action.setSourceId(connectionId);
action.setSourceName(connectionName);
action.setSourceType(Component.Connection);
if (actionDetails != null) {
action.setActionDetails(actionDetails);
}
}
return action;
}
/**
* Determines the type of component the specified connectable is.
*
* @param connectable
* @return
*/
private Component determineConnectableType(Connectable connectable) {
String sourceId = connectable.getIdentifier();
Component componentType = Component.Controller;
if (connectable instanceof ProcessorNode) {
componentType = Component.Processor;
} else if (connectable instanceof RemoteGroupPort) {
final RemoteGroupPort remoteGroupPort = (RemoteGroupPort) connectable;
if (TransferDirection.RECEIVE.equals(remoteGroupPort.getTransferDirection())) {
if (remoteGroupPort.getRemoteProcessGroup() == null) {
componentType = Component.InputPort;
} else {
componentType = Component.OutputPort;
}
} else {
if (remoteGroupPort.getRemoteProcessGroup() == null) {
componentType = Component.OutputPort;
} else {
componentType = Component.InputPort;
}
}
} else if (connectable instanceof Port) {
ProcessGroup processGroup = connectable.getProcessGroup();
if (processGroup.getInputPort(sourceId) != null) {
componentType = Component.InputPort;
} else if (processGroup.getOutputPort(sourceId) != null) {
componentType = Component.OutputPort;
}
} else if (connectable instanceof Funnel) {
componentType = Component.Funnel;
}
return componentType;
}
}
| apache-2.0 |
M-Wong/AndroidAppTemplate | app/src/main/java/ch/mwong/apptemplate/presentation/base/WithContext.java | 200 | package ch.mwong.apptemplate.presentation.base;
import android.content.Context;
import android.support.annotation.Nullable;
public interface WithContext {
@Nullable
Context getContext();
}
| apache-2.0 |
absentm/myapplication | app/src/main/java/com/example/dm/myapplication/beans/MusicBean.java | 1849 | package com.example.dm.myapplication.beans;
import java.io.Serializable;
/**
* MusicBean
* Created by dm on 16-11-1.
*/
public class MusicBean implements Serializable {
private long id;
private long album_id;
private String title;
private String artist;
private long duration;
private long size;
private String url;
private String album;
private int isMusic;
private boolean isFavorite = false;
public MusicBean() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getAlbum_id() {
return album_id;
}
public void setAlbum_id(long album_id) {
this.album_id = album_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public int getIsMusic() {
return isMusic;
}
public void setIsMusic(int isMusic) {
this.isMusic = isMusic;
}
public boolean isFavorite() {
return isFavorite;
}
public void setFavorite(boolean favorite) {
isFavorite = favorite;
}
}
| apache-2.0 |
Firujo/PI | src/pt/iscte/lei/pi/firujo/scores/ScoreComparator.java | 522 | package pt.iscte.lei.pi.firujo.scores;
import java.util.Comparator;
/*
* Comparador de resultados, recebe 2 e devolve o resultado - maior - menor - igual em int.
* -1 : maior é o primeiro
* 1 : maior é o segundo
* 0 : são iguais
*/
public class ScoreComparator implements Comparator<Score> {
@Override
public int compare(Score sc1, Score sc2) {
if (sc1.getScore() > sc2.getScore()) {
return -1;
} else if (sc1.getScore() < sc2.getScore()) {
return 1;
} else
return 0;
}
}
| apache-2.0 |
tunsi/maze | src/test/java/me/tunsi/test/spring4/ioc/TestCase.java | 418 | package me.tunsi.test.spring4.ioc;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestCase {
@Test
public void test1() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("me/tunsi/test/spring4/ioc/applicationContext.xml");
Bean1 bean1 = (Bean1)context.getBean("alias1");
bean1.doSomething();
context.close();
}
}
| apache-2.0 |
googleapis/java-monitoring | google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/v3/stub/AlertPolicyServiceStub.java | 2839 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.monitoring.v3.stub;
import static com.google.cloud.monitoring.v3.AlertPolicyServiceClient.ListAlertPoliciesPagedResponse;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.monitoring.v3.AlertPolicy;
import com.google.monitoring.v3.CreateAlertPolicyRequest;
import com.google.monitoring.v3.DeleteAlertPolicyRequest;
import com.google.monitoring.v3.GetAlertPolicyRequest;
import com.google.monitoring.v3.ListAlertPoliciesRequest;
import com.google.monitoring.v3.ListAlertPoliciesResponse;
import com.google.monitoring.v3.UpdateAlertPolicyRequest;
import com.google.protobuf.Empty;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Base stub class for the AlertPolicyService service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public abstract class AlertPolicyServiceStub implements BackgroundResource {
public UnaryCallable<ListAlertPoliciesRequest, ListAlertPoliciesPagedResponse>
listAlertPoliciesPagedCallable() {
throw new UnsupportedOperationException("Not implemented: listAlertPoliciesPagedCallable()");
}
public UnaryCallable<ListAlertPoliciesRequest, ListAlertPoliciesResponse>
listAlertPoliciesCallable() {
throw new UnsupportedOperationException("Not implemented: listAlertPoliciesCallable()");
}
public UnaryCallable<GetAlertPolicyRequest, AlertPolicy> getAlertPolicyCallable() {
throw new UnsupportedOperationException("Not implemented: getAlertPolicyCallable()");
}
public UnaryCallable<CreateAlertPolicyRequest, AlertPolicy> createAlertPolicyCallable() {
throw new UnsupportedOperationException("Not implemented: createAlertPolicyCallable()");
}
public UnaryCallable<DeleteAlertPolicyRequest, Empty> deleteAlertPolicyCallable() {
throw new UnsupportedOperationException("Not implemented: deleteAlertPolicyCallable()");
}
public UnaryCallable<UpdateAlertPolicyRequest, AlertPolicy> updateAlertPolicyCallable() {
throw new UnsupportedOperationException("Not implemented: updateAlertPolicyCallable()");
}
@Override
public abstract void close();
}
| apache-2.0 |
code4craft/webmagic | webmagic-core/src/main/java/us/codecraft/webmagic/selector/Html.java | 2329 | package us.codecraft.webmagic.selector;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
/**
* Selectable html.<br>
*
* @author code4crafter@gmail.com <br>
* @since 0.1.0
*/
public class Html extends HtmlNode {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* Disable jsoup html entity escape. It can be set just before any Html instance is created.
* @deprecated
*/
public static boolean DISABLE_HTML_ENTITY_ESCAPE = false;
/**
* Store parsed document for better performance when only one text exist.
*/
private Document document;
public Html(String text, String url) {
try {
this.document = Jsoup.parse(text, url);
} catch (Exception e) {
this.document = null;
logger.warn("parse document error ", e);
}
}
public Html(String text) {
try {
this.document = Jsoup.parse(text);
} catch (Exception e) {
this.document = null;
logger.warn("parse document error ", e);
}
}
public Html(Document document) {
this.document = document;
}
public Document getDocument() {
return document;
}
@Override
protected List<Element> getElements() {
return Collections.<Element>singletonList(getDocument());
}
/**
* @param selector selector
* @return result
*/
public String selectDocument(Selector selector) {
if (selector instanceof ElementSelector) {
ElementSelector elementSelector = (ElementSelector) selector;
return elementSelector.select(getDocument());
} else {
return selector.select(getFirstSourceText());
}
}
public List<String> selectDocumentForList(Selector selector) {
if (selector instanceof ElementSelector) {
ElementSelector elementSelector = (ElementSelector) selector;
return elementSelector.selectList(getDocument());
} else {
return selector.selectList(getFirstSourceText());
}
}
public static Html create(String text) {
return new Html(text);
}
}
| apache-2.0 |
yelshater/hadoop-2.3.0 | hadoop-yarn-server-resourcemanager-2.3.0-cdh5.1.0/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebAppFairScheduler.java | 4575 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.webapp;
import com.google.common.collect.Maps;
import com.google.inject.Binder;
import com.google.inject.Injector;
import com.google.inject.Module;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
import org.apache.hadoop.yarn.server.resourcemanager.RMContextImpl;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.MockRMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairSchedulerConfiguration;
import org.apache.hadoop.yarn.server.resourcemanager.security.ClientToAMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.resourcemanager.security.NMTokenSecretManagerInRM;
import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager;
import org.apache.hadoop.yarn.webapp.test.WebAppTests;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TestRMWebAppFairScheduler {
@Test
public void testFairSchedulerWebAppPage() {
List<RMAppState> appStates = Arrays.asList(RMAppState.NEW,
RMAppState.NEW_SAVING, RMAppState.SUBMITTED);
final RMContext rmContext = mockRMContext(appStates);
Injector injector = WebAppTests.createMockInjector(RMContext.class,
rmContext,
new Module() {
@Override
public void configure(Binder binder) {
try {
ResourceManager mockRmWithFairScheduler =
mockRm(rmContext);
binder.bind(ResourceManager.class).toInstance
(mockRmWithFairScheduler);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
});
FairSchedulerPage fsViewInstance = injector.getInstance(FairSchedulerPage
.class);
fsViewInstance.render();
WebAppTests.flushOutput(injector);
}
private static RMContext mockRMContext(List<RMAppState> states) {
final ConcurrentMap<ApplicationId, RMApp> applicationsMaps = Maps
.newConcurrentMap();
int i = 0;
for (RMAppState state : states) {
MockRMApp app = new MockRMApp(i, i, state);
applicationsMaps.put(app.getApplicationId(), app);
i++;
}
return new RMContextImpl(null, null, null, null,
null, null, null, null, null) {
@Override
public ConcurrentMap<ApplicationId, RMApp> getRMApps() {
return applicationsMaps;
}
};
}
private static ResourceManager mockRm(RMContext rmContext) throws
IOException {
ResourceManager rm = mock(ResourceManager.class);
ResourceScheduler rs = mockFairScheduler();
when(rm.getResourceScheduler()).thenReturn(rs);
when(rm.getRMContext()).thenReturn(rmContext);
return rm;
}
private static FairScheduler mockFairScheduler() throws IOException {
FairScheduler fs = new FairScheduler();
FairSchedulerConfiguration conf = new FairSchedulerConfiguration();
fs.reinitialize(conf, new RMContextImpl(null, null, null, null, null,
null, new RMContainerTokenSecretManager(conf),
new NMTokenSecretManagerInRM(conf),
new ClientToAMTokenSecretManagerInRM()));
return fs;
}
}
| apache-2.0 |
ProgrammingLife2016/PL1-2016 | src/test/java/io/github/programminglife2016/pl1_2016/parser/metadata/SpecimenParserTest.java | 5068 | package io.github.programminglife2016.pl1_2016.parser.metadata;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
//CHECKSTYLE.OFF: MagicNumber
/**
* Tests for SpecimenParser.
*/
public class SpecimenParserTest {
/**
* Parser to be used in each test.
*/
private SpecimenParser specimenParser;
/**
* Test string.
*/
String file = "Specimen ID,Age,Sex,hivStatus Status,Cohort,Date of Coltion,Study"
+ " Geographic District,Specimen Type,Microscopy Smear Status,DNA isolation: "
+ "single colony or non-single colony,Phenotypic DST Pattern,Capmycin (10ug/mL),"
+ "Ethambutol (7.5ug/mL),Ethide (10ug/mL),Isiazid (0.2ug/mL or 1ug/mL),cin "
+ "(6ug/mL),Pyrazinamide (Nicotinamide 500.0ug/mL or PZA-MGIT),Ofloxacin (2ug/mL),"
+ "Rifampin (1ug/mL),Streptomycin (2ug/mL),Digital Spoligotype,Lineage,Genotypic DST "
+ "pattern,Tugela Ferry vs. non-Tugela Ferry XDR\n"
+ "TKK-01-0001,unknown,Female,Positive,KZNSUR,1/16/2008,"
+ "eThekwini,sputum,Negative,single "
+ "colony,MDR,S,R,R,R,S,R,S,R,R,LAM4,LIN 4,MDR,n/a\n"
+ "TKK-01-0006,70,Male,Negative,KZNSUR,2/15/2008,eThekwini,sputum,Positive,single "
+ "colony,MDR,S,S,S,R,S,S,S,R,S,LAM4,LIN 4,MDR,n/a\n"
+ "TKK-01-0009,27,Female,unknown,KZNSUR,2/19/2008,eThekwini,sputum,Positive,single "
+ "colony,mono,S,S,S,S,S,S,S,R,S,T1,LIN 4,MDR,n/a\n"
+ "TKK-01-0011,32,Male,unknown,KZNSUR,2/20/2008,eThekwini,sputum,Positive,single colony"
+ ",MDR,S,S,S,R,S,S,S,R,S,LAM11-ZWE,LAM4,LIN 4,MDR,n/a\n"
+ "TKK-01-0012,23,Female,Negative,KZNSUR,2/25/2008,eThekwini,sputum,unknown,"
+ "single,MDR,S,R,S,R,S,R,S,R,R,LAM4,LIN 4,MDR,n/a\n"
+ "Specimen ID,35,Male,Positive,KZNSUR,2/26/2008,uThungulu,"
+ "sputum,Positive,single colony"
+ ",MDR,S,R,S,R,S,R,S,R,R,T1,LIN 4,MDR,n/a";
/**
* Setup the parser before each test.
*/
@Before
public void setup() {
specimenParser = new SpecimenParser();
}
/**
* Test the methods of the parser of specimen.
*
* @throws IOException thrown if test string contains wrong encoding.
*/
@Test
public void testSpecimenParsedCorrect() throws IOException {
InputStream stream = IOUtils.toInputStream(file, "UTF-8");
Map<String, Subject> specimenCollection = specimenParser.parse(stream);
assertEquals(70, specimenCollection.get("TKK_01_0006").getAge());
}
/**
* Test all getters for specimen.
*
* @throws IOException thrown if test string contains wrong encoding.
*/
@Test
public void testSpecimen() throws IOException {
InputStream stream = IOUtils.toInputStream(file, "UTF-8");
Map<String, Subject> specimenCollection = specimenParser.parse(stream);
assertEquals("TKK_01_0006", specimenCollection.get("TKK_01_0006").getNameId());
assertEquals(70, specimenCollection.get("TKK_01_0006").getAge());
assertEquals(true, specimenCollection.get("TKK_01_0006").isMale());
assertEquals(-1, specimenCollection.get("TKK_01_0006").getHivStatus());
assertEquals("KZNSUR", specimenCollection.get("TKK_01_0006").getCohort());
assertEquals("2/15/2008", specimenCollection.get("TKK_01_0006").getDate());
assertEquals("eThekwini", specimenCollection.get("TKK_01_0006").getDistrict());
assertEquals("sputum", specimenCollection.get("TKK_01_0006").getType());
assertEquals(1, specimenCollection.get("TKK_01_0006").getSmear());
assertEquals(true, specimenCollection.get("TKK_01_0006").isSingleColony());
assertEquals("MDR", specimenCollection.get("TKK_01_0006").getPdstpattern());
assertEquals("S", specimenCollection.get("TKK_01_0006").getCapreomycin());
assertEquals("S", specimenCollection.get("TKK_01_0006").getEthambutol());
assertEquals("S", specimenCollection.get("TKK_01_0006").getEthionamide());
assertEquals("R", specimenCollection.get("TKK_01_0006").getIsoniazid());
assertEquals("S", specimenCollection.get("TKK_01_0006").getKanamycin());
assertEquals("S", specimenCollection.get("TKK_01_0006").getPyrazinamide());
assertEquals("S", specimenCollection.get("TKK_01_0006").getOfloxacin());
assertEquals("R", specimenCollection.get("TKK_01_0006").getRifampin());
assertEquals("S", specimenCollection.get("TKK_01_0006").getStreptomycin());
assertEquals("LAM4", specimenCollection.get("TKK_01_0006").getSpoligotype());
assertEquals("LIN 4", specimenCollection.get("TKK_01_0006").getLineage());
assertEquals("MDR", specimenCollection.get("TKK_01_0006").getGdstPattern());
assertEquals("n/a", specimenCollection.get("TKK_01_0006").getXdr());
}
}
| apache-2.0 |
ppamorim/SlapBar | slapbar/src/main/java/com/github/ppamorim/layout/ButtonSlapBar.java | 2284 | package com.github.ppamorim.layout;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.TextView;
import com.github.ppamorim.Utils.ViewUtil;
import com.github.ppamorim.slapbar.R;
public class ButtonSlapBar extends AbstractSlapBar {
private TextView textView;
private Button button;
private ButtonCallback buttonCallback;
public ButtonSlapBar(Activity activity) {
super(activity);
}
public ButtonSlapBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ButtonSlapBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override protected int getLayoutId() {
return R.layout.button_slapbar;
}
public ButtonSlapBar config() {
textView = (TextView) getSlapBar().findViewById(R.id.text);
button = (Button) getSlapBar().findViewById(R.id.button);
return this;
}
public ButtonSlapBar backgroundColor(int colorId) {
getSlapBar().setBackgroundColor(colorId);
return this;
}
public ButtonSlapBar buttonColor(int colorId) {
button.setBackgroundColor(colorId);
return this;
}
public ButtonSlapBar textButtonColor(int colorId) {
button.setTextColor(getResources().getColor(colorId));
return this;
}
public ButtonSlapBar buttonText(String text) {
button.setText(text);
return this;
}
public ButtonSlapBar textPadding(int leftDp, int topDp, int rightDp, int bottomDp) {
textView.setPadding(ViewUtil.dpToPx(getResources(), leftDp),
ViewUtil.dpToPx(getResources(), topDp), ViewUtil.dpToPx(getResources(), rightDp),
ViewUtil.dpToPx(getResources(), bottomDp));
return this;
}
public ButtonSlapBar textGravity(int gravity) {
textView.setGravity(gravity);
return this;
}
public ButtonSlapBar textColor(int colorId) {
textView.setTextColor(getResources().getColor(colorId));
return this;
}
public ButtonSlapBar text(String text) {
textView.setText(text);
return this;
}
public ButtonSlapBar callback(ButtonCallback buttonCallback) {
this.buttonCallback = buttonCallback;
return this;
}
public interface ButtonCallback {
void onButtonClick();
}
}
| apache-2.0 |
mkhutornenko/incubator-aurora | src/main/java/org/apache/aurora/scheduler/thrift/ThriftModule.java | 1008 | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.aurora.scheduler.thrift;
import com.google.inject.AbstractModule;
import org.apache.aurora.gen.AuroraAdmin;
import org.apache.aurora.scheduler.thrift.aop.AopModule;
/**
* Binding module to configure a thrift server.
*/
public class ThriftModule extends AbstractModule {
@Override
protected void configure() {
bind(AuroraAdmin.Iface.class).to(SchedulerThriftInterface.class);
install(new AopModule());
}
}
| apache-2.0 |
ivankelly/bookkeeper | bookkeeper-stats-providers/twitter-finagle-provider/src/main/java/org/apache/bookkeeper/stats/twitter/finagle/FinagleStatsLoggerImpl.java | 3157 | /**
* 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.bookkeeper.stats.twitter.finagle;
import com.twitter.finagle.stats.StatsReceiver;
import com.twitter.util.Function0;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.bookkeeper.stats.Counter;
import org.apache.bookkeeper.stats.Gauge;
import org.apache.bookkeeper.stats.OpStatsLogger;
import org.apache.bookkeeper.stats.StatsLogger;
import scala.collection.Seq;
/**
* A <i>Finagle Stats</i> library based {@link StatsLogger} implementation.
*/
public class FinagleStatsLoggerImpl implements StatsLogger {
private final StatsReceiver stats;
// keep the references for finagle gauges. they are destroyed when the stats logger is destroyed.
final Map<Gauge, com.twitter.finagle.stats.Gauge> finagleGauges;
public FinagleStatsLoggerImpl(final StatsReceiver stats) {
this.stats = stats;
this.finagleGauges = new HashMap<Gauge, com.twitter.finagle.stats.Gauge>();
}
@Override
public OpStatsLogger getOpStatsLogger(final String name) {
return new OpStatsLoggerImpl(name, this.stats);
}
@Override
public Counter getCounter(final String name) {
return new CounterImpl(name, this.stats);
}
@Override
public <T extends Number> void registerGauge(final String name, final Gauge<T> gauge) {
// This is done to inter-op with Scala Seq
final Seq<String> gaugeName = scala.collection.JavaConversions.asScalaBuffer(Arrays.asList(name)).toList();
synchronized (finagleGauges) {
finagleGauges.put(gauge, this.stats.addGauge(gaugeName, gaugeProvider(gauge)));
}
}
@Override
public <T extends Number> void unregisterGauge(String name, Gauge<T> gauge) {
synchronized (finagleGauges) {
finagleGauges.remove(gauge);
}
}
private <T extends Number> Function0<Object> gaugeProvider(final Gauge<T> gauge) {
return new Function0<Object>() {
@Override
public Object apply() {
return gauge.getSample().floatValue();
}
};
}
@Override
public StatsLogger scope(String name) {
return new FinagleStatsLoggerImpl(this.stats.scope(name));
}
@Override
public void removeScope(String name, StatsLogger statsLogger) {
// no-op
}
}
| apache-2.0 |
dansiviter/cito | core/src/main/java/cito/server/AbstractEndpoint.java | 5372 | /*
* Copyright 2016-2017 Daniel Siviter
*
* 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 cito.server;
import static cito.server.Extension.webSocketContext;
import static java.lang.String.format;
import java.io.IOException;
import javax.enterprise.event.Event;
import javax.enterprise.inject.spi.BeanManager;
import javax.inject.Inject;
import javax.websocket.CloseReason;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.EncodeException;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import javax.ws.rs.core.MediaType;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import cito.QuietClosable;
import cito.annotation.FromClient;
import cito.event.ClientMessageProducer;
import cito.event.Message;
import cito.scope.WebSocketContext;
import cito.server.ws.WebSocketConfigurator;
import cito.stomp.Frame;
import cito.stomp.jms.Relay;
/**
*
* @author Daniel Siviter
* @since v1.0 [15 Jul 2016]
*/
public abstract class AbstractEndpoint extends Endpoint {
@Inject
protected Logger log;
@Inject
private BeanManager beanManager;
@Inject
private SessionRegistry registry;
@Inject
private Relay relay;
@Inject @FromClient
private Event<Message> messageEvent;
@Inject
private Event<Session> sessionEvent;
@Inject
private Event<Throwable> errorEvent;
@Inject
private RttService rttService;
@OnOpen
@Override
public void onOpen(Session session, EndpointConfig config) {
final String httpSessionId = session.getRequestParameterMap().get("httpSessionId").get(0);
this.log.info("WebSocket connection opened. [id={},httpSessionId={},principle={}]",
session.getId(),
httpSessionId,
session.getUserPrincipal());
final SecurityContext securityCtx = WebSocketConfigurator.removeSecurityContext(config.getUserProperties(), httpSessionId);
SecurityContextProducer.set(session, securityCtx);
try (QuietClosable c = webSocketContext(this.beanManager).activate(session)) {
this.registry.register(session);
this.sessionEvent.select(cito.annotation.OnOpen.Literal.onOpen()).fire(session);
}
this.rttService.start(session);
}
/**
*
* @param session
* @param msg
*/
@OnMessage
public void pong(Session session, PongMessage msg) {
try (QuietClosable c = webSocketContext(this.beanManager).activate(session)) {
this.rttService.pong(session, msg);
}
}
/**
*
* @param session
* @param frame
*/
@OnMessage
public void message(Session session, Frame frame) {
final String sessionId = session.getId();
this.log.debug("Received message from client. [id={},principle={},command={}]", sessionId, session.getUserPrincipal(), frame.command());
try (QuietClosable c = webSocketContext(this.beanManager).activate(session)) {
final Message event = new Message(sessionId, frame);
try (QuietClosable closable = ClientMessageProducer.set(event)) {
this.relay.fromClient(event); // due to no @Observe @Priority we need to ensure the relay gets this first
this.messageEvent.fire(event);
}
}
}
@OnError
@Override
public void onError(Session session, Throwable cause) {
final String errorId = RandomStringUtils.randomAlphanumeric(8).toUpperCase();
this.log.warn("WebSocket error. [id={},principle={},errorId={}]", session.getId(), session.getUserPrincipal(), errorId, cause);
try (QuietClosable c = webSocketContext(this.beanManager).activate(session)) {
this.errorEvent.select(cito.annotation.OnError.Literal.onError()).fire(cause);
final Frame errorFrame = Frame.error().body(MediaType.TEXT_PLAIN_TYPE, format("%s [errorId=%s]", cause.getMessage(), errorId)).build();
session.getBasicRemote().sendObject(errorFrame);
session.close(new CloseReason(CloseCodes.PROTOCOL_ERROR, format("See server log. [errorId=%s]", errorId)));
} catch (IOException | EncodeException e) {
this.log.error("Unable to send error frame! [id={},principle={}]", session.getId(), session.getUserPrincipal(), e);
}
}
@OnClose
@Override
public void onClose(Session session, CloseReason reason) {
this.log.info("WebSocket connection closed. [id={},principle={},code={},reason={}]", session.getId(), session.getUserPrincipal(), reason.getCloseCode(), reason.getReasonPhrase());
final WebSocketContext ctx = webSocketContext(this.beanManager);
try (QuietClosable c = ctx.activate(session)) {
this.registry.unregister(session);
this.sessionEvent.select(cito.annotation.OnClose.Literal.onClose()).fire(session);
}
ctx.dispose(session);
}
}
| apache-2.0 |
vlsi/mat-calcite-plugin | MatCalcitePlugin/src/com/github/vlsi/mat/calcite/editor/CalciteContentAssistantProcessor.java | 5489 | package com.github.vlsi.mat.calcite.editor;
import com.github.vlsi.mat.calcite.CalciteDataSource;
import org.apache.calcite.DataContext;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.jdbc.CalciteMetaImpl;
import org.apache.calcite.sql.advise.SqlAdvisor;
import org.apache.calcite.sql.validate.SqlMoniker;
import org.apache.calcite.sql.validate.SqlMonikerType;
import org.apache.calcite.util.Util;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.CompletionProposal;
import org.eclipse.jface.text.contentassist.ContextInformationValidator;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.mat.query.IQueryContext;
import org.eclipse.mat.snapshot.ISnapshot;
import org.eclipse.mat.ui.editor.MultiPaneEditor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class CalciteContentAssistantProcessor implements IContentAssistProcessor {
public static ISnapshot getSnapshot() {
IWorkbenchPage page = PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage();
IEditorPart part = page == null ? null : page.getActiveEditor();
if (!(part instanceof MultiPaneEditor)) {
return null;
}
IQueryContext queryContext = ((MultiPaneEditor) part).getQueryContext();
ISnapshot snapshot = (ISnapshot) queryContext.get(ISnapshot.class, null);
return snapshot;
}
@Override
public ICompletionProposal[] computeCompletionProposals(ITextViewer iTextViewer, int offset) {
ISnapshot snapshot = getSnapshot();
String sql = iTextViewer.getDocument().get();
try (Connection con = CalciteDataSource.getConnection(snapshot)) {
CalciteConnection ccon = con.unwrap(CalciteConnection.class);
if (false) {
// This is an official API
System.out.println("advisor: ");
try (PreparedStatement ps = con.prepareStatement("select id, names, type from table(getHints(?, ?)) as t")) {
ps.setString(1, sql);
ps.setInt(2, offset);
int cnt = 0;
try (ResultSet rs = ps.executeQuery()) {
System.out.println();
while (rs.next()) {
System.out.println("rs = " + rs.getString(1) + ", " + rs.getString(2) + ", " + rs.getString(3));
cnt++;
}
}
System.out.println(cnt + " items suggested");
}
}
// This is unofficial API, however it enables more methods of SqlAdvisor
final DataContext dataContext = CalciteMetaImpl.createDataContext(ccon);
SqlAdvisor advisor = DataContext.Variable.SQL_ADVISOR.get(dataContext);
String[] replaced = new String[1];
List<SqlMoniker> completionHints = advisor.getCompletionHints(sql, offset, replaced);
String replacement = replaced[0];
List<SqlMoniker> hints = new ArrayList<>(completionHints.size());
for (SqlMoniker hint : completionHints) {
if (Util.last(hint.toIdentifier().names).startsWith("$")) {
continue;
}
hints.add(hint);
}
hints.sort(new Comparator<SqlMoniker>() {
private int order(SqlMonikerType type) {
switch (type) {
case CATALOG:
return 0;
case SCHEMA:
return 1;
case TABLE:
return 2;
case VIEW:
return 3;
case COLUMN:
return 4;
case FUNCTION:
return 5;
case KEYWORD:
return 6;
case REPOSITORY:
return 7;
default:
return 10;
}
}
@Override
public int compare(SqlMoniker o1, SqlMoniker o2) {
int a = order(o1.getType());
int b = order(o2.getType());
if (a != b) {
return a < b ? -1 : 1;
}
return o1.id().compareTo(o2.id());
}
});
ICompletionProposal[] res = new ICompletionProposal[hints.size()];
for (int i = 0; i < hints.size(); i++) {
SqlMoniker hint = hints.get(i);
String hintStr = advisor.getReplacement(hint, replacement);
res[i] = new CompletionProposal(hintStr, offset - replacement.length(),
replacement.length(), hintStr.length(),
null, hintStr + ", " + hint.getType().name(), null, "");
}
return res;
} catch (SQLException e) {
return null;
}
}
@Override
public IContextInformation[] computeContextInformation(ITextViewer iTextViewer, int i) {
return new IContextInformation[0];
}
@Override
public char[] getCompletionProposalAutoActivationCharacters() {
return new char[]{'.', '"'};
}
@Override
public char[] getContextInformationAutoActivationCharacters() {
return new char[]{' ', '(', '.'};
}
@Override
public String getErrorMessage() {
return null;
}
@Override
public IContextInformationValidator getContextInformationValidator() {
return new ContextInformationValidator(this);
}
}
| apache-2.0 |
y1011/cas-server | cas-server-support-spnego/src/main/java/org/jasig/cas/support/spnego/authentication/principal/SpnegoCredential.java | 4705 | package org.jasig.cas.support.spnego.authentication.principal;
import com.google.common.io.ByteSource;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.jasig.cas.authentication.Credential;
import org.jasig.cas.authentication.principal.Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
/**
* Credential that are a holder for SPNEGO init token.
*
* @author Arnaud Lesueur
* @author Marc-Antoine Garrigue
* @since 3.1
*/
public final class SpnegoCredential implements Credential, Serializable {
/**
* Unique id for serialization.
*/
private static final long serialVersionUID = 84084596791289548L;
private static final int NTLM_TOKEN_MAX_LENGTH = 8;
private static final Byte CHAR_S_BYTE = Byte.valueOf((byte) 'S');
/** The ntlmssp signature. */
private static final Byte[] NTLMSSP_SIGNATURE = {Byte.valueOf((byte) 'N'),
Byte.valueOf((byte) 'T'), Byte.valueOf((byte) 'L'),
Byte.valueOf((byte) 'M'), CHAR_S_BYTE, CHAR_S_BYTE,
Byte.valueOf((byte) 'P'), Byte.valueOf((byte) 0)};
private final transient Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* The SPNEGO Init Token.
*/
private final ByteSource initToken;
/**
* The SPNEGO Next Token.
*/
private ByteSource nextToken;
/**
* The Principal.
*/
private Principal principal;
/**
* The authentication type should be Kerberos or NTLM.
*/
private final boolean isNtlm;
/**
* Instantiates a new SPNEGO credential.
*
* @param initToken the init token
*/
public SpnegoCredential(final byte[] initToken) {
Assert.notNull(initToken, "The initToken cannot be null.");
this.initToken = ByteSource.wrap(initToken);
this.isNtlm = isTokenNtlm(this.initToken);
}
public byte[] getInitToken() {
return consumeByteSourceOrNull(this.initToken);
}
public byte[] getNextToken() {
return consumeByteSourceOrNull(this.nextToken);
}
/**
* Sets next token.
*
* @param nextToken the next token
*/
public void setNextToken(final byte[] nextToken) {
this.nextToken = ByteSource.wrap(nextToken);
}
public Principal getPrincipal() {
return this.principal;
}
public void setPrincipal(final Principal principal) {
this.principal = principal;
}
public boolean isNtlm() {
return this.isNtlm;
}
@Override
public String getId() {
return this.principal != null ? this.principal.getId() : UNKNOWN_ID;
}
@Override
public String toString() {
return getId();
}
/**
* Checks if is token ntlm.
*
* @param tokenSource the token
* @return true, if token ntlm
*/
private boolean isTokenNtlm(final ByteSource tokenSource) {
final byte[] token = consumeByteSourceOrNull(tokenSource);
if (token == null || token.length < NTLM_TOKEN_MAX_LENGTH) {
return false;
}
for (int i = 0; i < NTLM_TOKEN_MAX_LENGTH; i++) {
if (NTLMSSP_SIGNATURE[i].byteValue() != token[i]) {
return false;
}
}
return true;
}
@Override
public boolean equals(final Object obj) {
if (obj == null || !obj.getClass().equals(this.getClass())) {
return false;
}
final SpnegoCredential c = (SpnegoCredential) obj;
return Arrays.equals(this.getInitToken(), c.getInitToken())
&& this.principal.equals(c.getPrincipal())
&& Arrays.equals(this.getNextToken(), c.getNextToken());
}
@Override
public int hashCode() {
int hash = super.hashCode();
if (this.principal != null) {
hash = this.principal.hashCode();
}
return new HashCodeBuilder().append(this.getInitToken())
.append(this.getNextToken())
.append(hash).toHashCode();
}
/**
* Read the contents of the source into a byte array.
* @param source the byte array source
* @return the byte[] read from the source or null
*/
private byte[] consumeByteSourceOrNull(final ByteSource source) {
try {
if (source == null || source.isEmpty()) {
return null;
}
return source.read();
} catch (final IOException e) {
logger.warn("Could not consume the byte array source", e);
return null;
}
}
}
| apache-2.0 |
joaocsousa/OAuth | app/src/main/java/com/tinycoolthings/oauthtest/info/twitter/network/UsersService.java | 510 | package com.tinycoolthings.oauthtest.info.twitter.network;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.models.User;
import retrofit.http.GET;
import retrofit.http.Query;
/**
* Created by joaosousa on 12/03/15.
*/
public interface UsersService {
@GET("/1.1/users/show.json")
void show(@Query("user_id") Long userId,
@Query("screen_name") String screenName,
@Query("include_entities") Boolean includeEntities,
Callback<User> cb);
}
| apache-2.0 |
srapisarda/ontop | quest-test/src/test/java/it/unibz/inf/ontop/ask/MySQLASKTest.java | 3132 | package it.unibz.inf.ontop.ask;
import it.unibz.inf.ontop.io.ModelIOManager;
import it.unibz.inf.ontop.model.OBDADataFactory;
import it.unibz.inf.ontop.model.OBDAModel;
import it.unibz.inf.ontop.model.impl.OBDADataFactoryImpl;
import it.unibz.inf.ontop.owlrefplatform.core.QuestConstants;
import it.unibz.inf.ontop.owlrefplatform.core.QuestPreferences;
import it.unibz.inf.ontop.owlrefplatform.owlapi.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLLiteral;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import static org.junit.Assert.assertTrue;
public class MySQLASKTest {
private OBDADataFactory fac;
private QuestOWLConnection conn;
Logger log = LoggerFactory.getLogger(this.getClass());
private OBDAModel obdaModel;
private OWLOntology ontology;
final String owlfile =
"src/main/resources/testcases-scenarios/virtual-mode/stockexchange/simplecq/stockexchange.owl";
final String obdafile =
"src/main/resources/testcases-scenarios/virtual-mode/stockexchange/simplecq/stockexchange-mysql.obda";
private QuestOWL reasoner;
@Before
public void setUp() throws Exception {
// Loading the OWL file
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
ontology = manager.loadOntologyFromOntologyDocument((new File(owlfile)));
// Loading the OBDA data
fac = OBDADataFactoryImpl.getInstance();
obdaModel = fac.getOBDAModel();
ModelIOManager ioManager = new ModelIOManager(obdaModel);
ioManager.load(obdafile);
QuestPreferences p = new QuestPreferences();
p.setCurrentValueOf(QuestPreferences.ABOX_MODE, QuestConstants.VIRTUAL);
p.setCurrentValueOf(QuestPreferences.OBTAIN_FULL_METADATA, QuestConstants.FALSE);
// Creating a new instance of the reasoner
QuestOWLFactory factory = new QuestOWLFactory();
QuestOWLConfiguration config = QuestOWLConfiguration.builder().obdaModel(obdaModel).preferences(p).build();
reasoner = factory.createReasoner(ontology, config);
// Now we are ready for querying
conn = reasoner.getConnection();
}
@After
public void tearDown() throws Exception {
reasoner.dispose();
}
private boolean runTests(String query) throws Exception {
QuestOWLStatement st = conn.createStatement();
boolean retval;
try {
QuestOWLResultSet rs = st.executeTuple(query);
assertTrue(rs.nextRow());
OWLLiteral ind1 = rs.getOWLLiteral("x") ;
retval = ind1.parseBoolean();
} catch (Exception e) {
throw e;
} finally {
try {
} catch (Exception e) {
st.close();
assertTrue(false);
}
conn.close();
reasoner.dispose();
}
return retval;
}
@Test
public void testTrue() throws Exception {
String query = "ASK { ?x <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.owl-ontologies.com/Ontology1207768242.owl#StockBroker> .}";
boolean val = runTests(query);
assertTrue(val);
}
} | apache-2.0 |
acehjm/solby-backend | xconfig/src/test/java/me/solby/xconfig/config/AsyncTaskTest.java | 733 | package me.solby.xconfig.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* me.solby.xconfig.config
*
* @author majhdk
* @date 2019-06-30
*/
@Component
public class AsyncTaskTest {
private static final Logger logger = LoggerFactory.getLogger(AsyncTaskTest.class);
@Async("xTaskExecutor")
public void test04() {
logger.info("进入test04方法");
logger.info("test04-在执行异步代码块之前结束");
}
@Async
public void test05() {
logger.info("进入test05方法");
logger.info("test05-在执行异步代码块之前结束");
}
}
| apache-2.0 |
nafae/developer | modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201402/cm/CampaignSharedSetError.java | 4277 | /**
* CampaignSharedSetError.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.adwords.axis.v201402.cm;
public class CampaignSharedSetError extends com.google.api.ads.adwords.axis.v201402.cm.ApiError implements java.io.Serializable {
private com.google.api.ads.adwords.axis.v201402.cm.CampaignSharedSetErrorReason reason;
public CampaignSharedSetError() {
}
public CampaignSharedSetError(
java.lang.String fieldPath,
java.lang.String trigger,
java.lang.String errorString,
java.lang.String apiErrorType,
com.google.api.ads.adwords.axis.v201402.cm.CampaignSharedSetErrorReason reason) {
super(
fieldPath,
trigger,
errorString,
apiErrorType);
this.reason = reason;
}
/**
* Gets the reason value for this CampaignSharedSetError.
*
* @return reason
*/
public com.google.api.ads.adwords.axis.v201402.cm.CampaignSharedSetErrorReason getReason() {
return reason;
}
/**
* Sets the reason value for this CampaignSharedSetError.
*
* @param reason
*/
public void setReason(com.google.api.ads.adwords.axis.v201402.cm.CampaignSharedSetErrorReason reason) {
this.reason = reason;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CampaignSharedSetError)) return false;
CampaignSharedSetError other = (CampaignSharedSetError) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.reason==null && other.getReason()==null) ||
(this.reason!=null &&
this.reason.equals(other.getReason())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getReason() != null) {
_hashCode += getReason().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CampaignSharedSetError.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201402", "CampaignSharedSetError"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("reason");
elemField.setXmlName(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201402", "reason"));
elemField.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201402", "CampaignSharedSetError.Reason"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
nafae/developer | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/cm/AdGroupServiceInterfacemutateResponse.java | 1591 |
package com.google.api.ads.adwords.jaxws.v201406.cm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for mutateResponse element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="mutateResponse">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="rval" type="{https://adwords.google.com/api/adwords/cm/v201406}AdGroupReturnValue" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"rval"
})
@XmlRootElement(name = "mutateResponse")
public class AdGroupServiceInterfacemutateResponse {
protected AdGroupReturnValue rval;
/**
* Gets the value of the rval property.
*
* @return
* possible object is
* {@link AdGroupReturnValue }
*
*/
public AdGroupReturnValue getRval() {
return rval;
}
/**
* Sets the value of the rval property.
*
* @param value
* allowed object is
* {@link AdGroupReturnValue }
*
*/
public void setRval(AdGroupReturnValue value) {
this.rval = value;
}
}
| apache-2.0 |
lsimons/phloc-schematron-standalone | phloc-commons/src/main/java/com/phloc/commons/typeconvert/rule/AbstractTypeConverterRuleFixedSourceAssignableDestination.java | 2328 | /**
* Copyright (C) 2006-2013 phloc systems
* http://www.phloc.com
* office[at]phloc[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 com.phloc.commons.typeconvert.rule;
import javax.annotation.Nonnull;
import com.phloc.commons.string.ToStringGenerator;
/**
* Abstract type converter than can convert from a base source class to a
* destination class. Example from String.class to specific Enum.class
*
* @author Philip Helger
*/
public abstract class AbstractTypeConverterRuleFixedSourceAssignableDestination extends AbstractTypeConverterRule
{
private final Class <?> m_aSrcClass;
private final Class <?> m_aDstClass;
public AbstractTypeConverterRuleFixedSourceAssignableDestination (@Nonnull final Class <?> aSrcClass,
@Nonnull final Class <?> aDstClass)
{
super (ESubType.FIXED_SRC_ASSIGNABLE_DST);
if (aSrcClass == null)
throw new NullPointerException ("srcClass");
if (aDstClass == null)
throw new NullPointerException ("dstClass");
m_aSrcClass = aSrcClass;
m_aDstClass = aDstClass;
}
public final boolean canConvert (@Nonnull final Class <?> aSrcClass, @Nonnull final Class <?> aDstClass)
{
return m_aSrcClass.equals (aSrcClass) && m_aDstClass.isAssignableFrom (aDstClass);
}
@Nonnull
public final Class <?> getSourceClass ()
{
return m_aSrcClass;
}
@Nonnull
public final Class <?> getDestinationClass ()
{
return m_aDstClass;
}
@Override
public String toString ()
{
return ToStringGenerator.getDerived (super.toString ())
.append ("srcClass", m_aSrcClass.getName ())
.append ("dstClass", m_aDstClass.getName ())
.toString ();
}
}
| apache-2.0 |
flapdoodle-oss/de.flapdoodle.embed.process | src/main/java/de/flapdoodle/embed/process/config/store/PackageResolver.java | 1049 | /**
* Copyright (C) 2011
* Michael Mosmann <michael@mosmann.de>
* Martin Jöhren <m.joehren@googlemail.com>
*
* with contributions from
* konstantin-ba@github,
Archimedes Trajano (trajano@github),
Kevin D. Keck (kdkeck@github),
Ben McCann (benmccann@github)
*
* 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.flapdoodle.embed.process.config.store;
import de.flapdoodle.embed.process.distribution.Distribution;
public interface PackageResolver {
DistributionPackage packageFor(Distribution distribution);
}
| apache-2.0 |
comeonc/weixin-java-tools | weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfSessionWaitCaseList.java | 1073 | package me.chanjar.weixin.mp.bean.kefu.result;
import java.io.Serializable;
import java.util.List;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
/**
* @author Binary Wang
*/
@Data
public class WxMpKfSessionWaitCaseList implements Serializable {
private static final long serialVersionUID = 2432132626631361922L;
/**
* count 未接入会话数量
*/
@SerializedName("count")
private Long count;
/**
* waitcaselist 未接入会话列表,最多返回100条数据
*/
@SerializedName("waitcaselist")
private List<WxMpKfSession> kfSessionWaitCaseList;
public static WxMpKfSessionWaitCaseList fromJson(String json) {
return WxMpGsonBuilder.INSTANCE.create().fromJson(json,
WxMpKfSessionWaitCaseList.class);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
| apache-2.0 |
nafae/developer | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201403/AssetCreativeTemplateVariableMimeType.java | 988 |
package com.google.api.ads.dfp.jaxws.v201403;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for AssetCreativeTemplateVariable.MimeType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="AssetCreativeTemplateVariable.MimeType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="JPG"/>
* <enumeration value="PNG"/>
* <enumeration value="GIF"/>
* <enumeration value="SWF"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "AssetCreativeTemplateVariable.MimeType")
@XmlEnum
public enum AssetCreativeTemplateVariableMimeType {
JPG,
PNG,
GIF,
SWF;
public String value() {
return name();
}
public static AssetCreativeTemplateVariableMimeType fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
AndroidKnife/Utils | basic/src/main/java/com/hwangjr/utils/basic/ObjectHelper.java | 4938 | package com.hwangjr.utils.basic;
import java.util.Collection;
import java.util.Map;
/**
* Compare object or convert some types
*/
public class ObjectHelper {
private ObjectHelper() {
throw new AssertionError();
}
/**
* compare two object
*
* @param actual
* @param expected
* @return <ul>
* <li>if both are null, return true</li>
* <li>return actual.{@link Object#equals(Object)}</li>
* </ul>
*/
public static boolean isEquals(Object actual, Object expected) {
return actual == expected || (actual == null ? expected == null : actual.equals(expected));
}
/**
* Object to string
* <p/>
* <pre>
* objectToString(null) = "";
* objectToString("") = "";
* objectToString("aa") = "aa";
* </pre>
*
* @param obj
* @return
*/
public static String objectToString(Object obj) {
return (obj == null ? "" : (obj instanceof String ? (String) obj : obj.toString()));
}
/**
* convert long array to Long array
*
* @param source
* @return
*/
public static Long[] transformLongArray(long[] source) {
Long[] dest = new Long[source.length];
for (int i = 0; i < source.length; i++) {
dest[i] = source[i];
}
return dest;
}
/**
* convert Long array to long array
*
* @param source
* @return
*/
public static long[] transformLongArray(Long[] source) {
long[] dest = new long[source.length];
for (int i = 0; i < source.length; i++) {
dest[i] = source[i];
}
return dest;
}
/**
* convert int array to Integer array
*
* @param source
* @return
*/
public static Integer[] transformIntArray(int[] source) {
Integer[] dest = new Integer[source.length];
for (int i = 0; i < source.length; i++) {
dest[i] = source[i];
}
return dest;
}
/**
* convert Integer array to int array
*
* @param source
* @return
*/
public static int[] transformIntArray(Integer[] source) {
int[] dest = new int[source.length];
for (int i = 0; i < source.length; i++) {
dest[i] = source[i];
}
return dest;
}
/**
* compare two object
* <ul>
* <strong>About result</strong>
* <li>if v1 > v2, return 1</li>
* <li>if v1 = v2, return 0</li>
* <li>if v1 < v2, return -1</li>
* </ul>
* <ul>
* <strong>About rule</strong>
* <li>if v1 is null, v2 is null, then return 0</li>
* <li>if v1 is null, v2 is not null, then return -1</li>
* <li>if v1 is not null, v2 is null, then return 1</li>
* <li>return v1.{@link Comparable#compareTo(Object)}</li>
* </ul>
*
* @param v1
* @param v2
* @return
*/
public static <V> int compare(V v1, V v2) {
return v1 == null ? (v2 == null ? 0 : -1) : (v2 == null ? 1 : ((Comparable) v1).compareTo(v2));
}
/**
* is null or its size is 0
* <p/>
* <pre>
* isEmpty(null) = true;
* isEmpty({}) = true;
* isEmpty({1}) = false;
* </pre>
*
* @param <V>
* @param collection
* @return if collection is null or its size is 0, return true, else return false.
*/
public static <V> boolean isEmpty(Collection<V> collection) {
return null == collection || collection.isEmpty();
}
/**
* is null or its size is 0
*
* @param map
* @param <K>
* @param <V>
* @return if map is null or its size is 0, return true, else return false.
*/
public static <K, V> boolean isEmpty(Map<K, V> map) {
return null == map || map.isEmpty();
}
/**
* is null or its size is 0
*
* @param objs
* @return if array is null or its size is 0, return true, else return false.
*/
public static boolean isEmpty(Object[] objs) {
return null == objs || objs.length <= 0;
}
/**
* is null or its size is 0
*
* @param objs
* @return if array is null or its size is 0, return true, else return false.
*/
public static boolean isEmpty(int[] objs) {
return null == objs || objs.length <= 0;
}
/**
* is null or its length is 0
*
* @param charSequence
* @return if char sequence is null or its length is 0, return true, else return false.
*/
public static boolean isEmpty(CharSequence charSequence) {
return null == charSequence || charSequence.length() <= 0;
}
/**
* is null
*
* @param obj
* @return if array is null or its size is 0, return true, else return false.
*/
public static boolean isEmpty(Object obj) {
return null == obj;
}
}
| apache-2.0 |
leafclick/intellij-community | plugins/devkit/devkit-core/src/build/PrepareAllToDeployAction.java | 2505 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.build;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ui.configuration.ChooseModulesDialog;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.devkit.DevKitBundle;
import org.jetbrains.idea.devkit.module.PluginModuleType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PrepareAllToDeployAction extends PrepareToDeployAction {
@Override
public void actionPerformed(@NotNull final AnActionEvent e) {
final Project project = e.getData(CommonDataKeys.PROJECT);
if (project == null) return;
List<Module> pluginModules = new ArrayList<>();
for (Module aModule : ModuleManager.getInstance(project).getModules()) {
if (PluginModuleType.isOfType(aModule)) {
pluginModules.add(aModule);
}
}
ChooseModulesDialog dialog = new ChooseModulesDialog(project,
pluginModules,
DevKitBundle.message("select.plugin.modules.title"),
DevKitBundle.message("select.plugin.modules.description"));
if (dialog.showAndGet()) {
doPrepare(dialog.getChosenElements(), project);
}
}
@Override
public void update(@NotNull AnActionEvent e) {
long moduleCount = 0;
final Project project = e.getData(CommonDataKeys.PROJECT);
if (project != null) {
moduleCount = Arrays.stream(ModuleManager.getInstance(project).getModules()).filter(PluginModuleType::isOfType)
.limit(2).count();
}
boolean enabled = false;
if (moduleCount > 1) {
enabled = true;
}
else if (moduleCount > 0) {
final Module module = e.getData(LangDataKeys.MODULE);
if (module == null || !(PluginModuleType.isOfType(module))) {
enabled = true;
}
}
e.getPresentation().setEnabledAndVisible(enabled);
if (enabled) {
e.getPresentation().setText(DevKitBundle.lazyMessage("prepare.for.deployment.all"));
}
}
} | apache-2.0 |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/SelectInChangesViewTarget.java | 2302 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes;
import com.intellij.ide.SelectInContext;
import com.intellij.ide.SelectInTarget;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import org.jetbrains.annotations.Nullable;
import static com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.LOCAL_CHANGES;
import static com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.getToolWindowFor;
import static com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager.getToolWindowIdFor;
public class SelectInChangesViewTarget implements SelectInTarget, DumbAware {
private final Project myProject;
public SelectInChangesViewTarget(final Project project) {
myProject = project;
}
public String toString() {
return LOCAL_CHANGES;
}
@Override
public boolean canSelect(final SelectInContext context) {
final VirtualFile file = context.getVirtualFile();
FileStatus fileStatus = ChangeListManager.getInstance(myProject).getStatus(file);
return ProjectLevelVcsManager.getInstance(myProject).getAllActiveVcss().length != 0 &&
!fileStatus.equals(FileStatus.NOT_CHANGED);
}
@Override
public void selectIn(final SelectInContext context, final boolean requestFocus) {
final VirtualFile file = context.getVirtualFile();
Runnable runnable = () -> {
ChangesViewContentManager.getInstance(myProject).selectContent(LOCAL_CHANGES);
ChangesViewManager.getInstance(myProject).selectFile(file);
};
if (requestFocus) {
ToolWindow toolWindow = getToolWindowFor(myProject, LOCAL_CHANGES);
if (toolWindow != null) toolWindow.activate(runnable);
}
else {
runnable.run();
}
}
@Nullable
@Override
public String getToolWindowId() {
return getToolWindowIdFor(myProject, LOCAL_CHANGES);
}
@Override
public float getWeight() {
return 9;
}
}
| apache-2.0 |
eolivelli/herddb | herddb-core/src/main/java/herddb/client/impl/MapListScanResultSet.java | 1999 | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. 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 herddb.client.impl;
import herddb.client.HDBException;
import herddb.client.ScanResultSet;
import herddb.client.ScanResultSetMetadata;
import herddb.utils.DataAccessor;
import herddb.utils.MapDataAccessor;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Simple wrapper for static data
*
* @author enrico.olivelli
*/
public class MapListScanResultSet extends ScanResultSet {
private final Iterator<DataAccessor> iterator;
private final ScanResultSetMetadata metadata;
public MapListScanResultSet(long transactionId, ScanResultSetMetadata metadata, String[] columns, List<Map<String, Object>> list) {
super(transactionId);
this.iterator = list.stream().map(m -> {
return (DataAccessor) new MapDataAccessor(m, columns);
}).collect(Collectors.toList()).iterator();
this.metadata = metadata;
}
@Override
public ScanResultSetMetadata getMetadata() {
return metadata;
}
@Override
public boolean hasNext() throws HDBException {
return iterator.hasNext();
}
@Override
public DataAccessor next() throws HDBException {
return iterator.next();
}
}
| apache-2.0 |
nafae/developer | modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201409/cm/StringLengthError.java | 1657 |
package com.google.api.ads.adwords.jaxws.v201409.cm;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* Errors associated with the length of the given string being
* out of bounds.
*
*
* <p>Java class for StringLengthError complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="StringLengthError">
* <complexContent>
* <extension base="{https://adwords.google.com/api/adwords/cm/v201409}ApiError">
* <sequence>
* <element name="reason" type="{https://adwords.google.com/api/adwords/cm/v201409}StringLengthError.Reason" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "StringLengthError", propOrder = {
"reason"
})
public class StringLengthError
extends ApiError
{
protected StringLengthErrorReason reason;
/**
* Gets the value of the reason property.
*
* @return
* possible object is
* {@link StringLengthErrorReason }
*
*/
public StringLengthErrorReason getReason() {
return reason;
}
/**
* Sets the value of the reason property.
*
* @param value
* allowed object is
* {@link StringLengthErrorReason }
*
*/
public void setReason(StringLengthErrorReason value) {
this.reason = value;
}
}
| apache-2.0 |
tntcrowd/ExoPlayer | library/ui/src/main/java/com/google/android/exoplayer2/ui/PlayerView.java | 48604 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.ui;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ControlDispatcher;
import com.google.android.exoplayer2.DefaultControlDispatcher;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.PlaybackPreparer;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Player.DiscontinuityReason;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.metadata.id3.ApicFrame;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.TextOutput;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout.ResizeMode;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.ErrorMessageProvider;
import com.google.android.exoplayer2.util.RepeatModeUtil;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoListener;
import java.util.List;
/**
* A high level view for {@link Player} media playbacks. It displays video, subtitles and album art
* during playback, and displays playback controls using a {@link PlayerControlView}.
*
* <p>A PlayerView can be customized by setting attributes (or calling corresponding methods),
* overriding the view's layout file or by specifying a custom view layout file, as outlined below.
*
* <h3>Attributes</h3>
*
* The following attributes can be set on a PlayerView when used in a layout XML file:
*
* <ul>
* <li><b>{@code use_artwork}</b> - Whether artwork is used if available in audio streams.
* <ul>
* <li>Corresponding method: {@link #setUseArtwork(boolean)}
* <li>Default: {@code true}
* </ul>
* <li><b>{@code default_artwork}</b> - Default artwork to use if no artwork available in audio
* streams.
* <ul>
* <li>Corresponding method: {@link #setDefaultArtwork(Bitmap)}
* <li>Default: {@code null}
* </ul>
* <li><b>{@code use_controller}</b> - Whether the playback controls can be shown.
* <ul>
* <li>Corresponding method: {@link #setUseController(boolean)}
* <li>Default: {@code true}
* </ul>
* <li><b>{@code hide_on_touch}</b> - Whether the playback controls are hidden by touch events.
* <ul>
* <li>Corresponding method: {@link #setControllerHideOnTouch(boolean)}
* <li>Default: {@code true}
* </ul>
* <li><b>{@code auto_show}</b> - Whether the playback controls are automatically shown when
* playback starts, pauses, ends, or fails. If set to false, the playback controls can be
* manually operated with {@link #showController()} and {@link #hideController()}.
* <ul>
* <li>Corresponding method: {@link #setControllerAutoShow(boolean)}
* <li>Default: {@code true}
* </ul>
* <li><b>{@code hide_during_ads}</b> - Whether the playback controls are hidden during ads.
* Controls are always shown during ads if they are enabled and the player is paused.
* <ul>
* <li>Corresponding method: {@link #setControllerHideDuringAds(boolean)}
* <li>Default: {@code true}
* </ul>
* <li><b>{@code show_buffering}</b> - Whether the buffering spinner is displayed when the player
* is buffering.
* <ul>
* <li>Corresponding method: {@link #setShowBuffering(boolean)}
* <li>Default: {@code false}
* </ul>
* <li><b>{@code resize_mode}</b> - Controls how video and album art is resized within the view.
* Valid values are {@code fit}, {@code fixed_width}, {@code fixed_height} and {@code fill}.
* <ul>
* <li>Corresponding method: {@link #setResizeMode(int)}
* <li>Default: {@code fit}
* </ul>
* <li><b>{@code surface_type}</b> - The type of surface view used for video playbacks. Valid
* values are {@code surface_view}, {@code texture_view} and {@code none}. Using {@code none}
* is recommended for audio only applications, since creating the surface can be expensive.
* Using {@code surface_view} is recommended for video applications. Note, TextureView can
* only be used in a hardware accelerated window. When rendered in software, TextureView will
* draw nothing.
* <ul>
* <li>Corresponding method: None
* <li>Default: {@code surface_view}
* </ul>
* <li><b>{@code shutter_background_color}</b> - The background color of the {@code exo_shutter}
* view.
* <ul>
* <li>Corresponding method: {@link #setShutterBackgroundColor(int)}
* <li>Default: {@code unset}
* </ul>
* <li><b>{@code keep_content_on_player_reset}</b> - Whether the currently displayed video frame
* or media artwork is kept visible when the player is reset.
* <ul>
* <li>Corresponding method: {@link #setKeepContentOnPlayerReset(boolean)}
* <li>Default: {@code false}
* </ul>
* <li><b>{@code player_layout_id}</b> - Specifies the id of the layout to be inflated. See below
* for more details.
* <ul>
* <li>Corresponding method: None
* <li>Default: {@code R.layout.exo_player_view}
* </ul>
* <li><b>{@code controller_layout_id}</b> - Specifies the id of the layout resource to be
* inflated by the child {@link PlayerControlView}. See below for more details.
* <ul>
* <li>Corresponding method: None
* <li>Default: {@code R.layout.exo_player_control_view}
* </ul>
* <li>All attributes that can be set on a {@link PlayerControlView} can also be set on a
* PlayerView, and will be propagated to the inflated {@link PlayerControlView} unless the
* layout is overridden to specify a custom {@code exo_controller} (see below).
* </ul>
*
* <h3>Overriding the layout file</h3>
*
* To customize the layout of PlayerView throughout your app, or just for certain configurations,
* you can define {@code exo_player_view.xml} layout files in your application {@code res/layout*}
* directories. These layouts will override the one provided by the ExoPlayer library, and will be
* inflated for use by PlayerView. The view identifies and binds its children by looking for the
* following ids:
*
* <p>
*
* <ul>
* <li><b>{@code exo_content_frame}</b> - A frame whose aspect ratio is resized based on the video
* or album art of the media being played, and the configured {@code resize_mode}. The video
* surface view is inflated into this frame as its first child.
* <ul>
* <li>Type: {@link AspectRatioFrameLayout}
* </ul>
* <li><b>{@code exo_shutter}</b> - A view that's made visible when video should be hidden. This
* view is typically an opaque view that covers the video surface view, thereby obscuring it
* when visible.
* <ul>
* <li>Type: {@link View}
* </ul>
* <li><b>{@code exo_buffering}</b> - A view that's made visible when the player is buffering.
* This view typically displays a buffering spinner or animation.
* <ul>
* <li>Type: {@link View}
* </ul>
* <li><b>{@code exo_subtitles}</b> - Displays subtitles.
* <ul>
* <li>Type: {@link SubtitleView}
* </ul>
* <li><b>{@code exo_artwork}</b> - Displays album art.
* <ul>
* <li>Type: {@link ImageView}
* </ul>
* <li><b>{@code exo_error_message}</b> - Displays an error message to the user if playback fails.
* <ul>
* <li>Type: {@link TextView}
* </ul>
* <li><b>{@code exo_controller_placeholder}</b> - A placeholder that's replaced with the inflated
* {@link PlayerControlView}. Ignored if an {@code exo_controller} view exists.
* <ul>
* <li>Type: {@link View}
* </ul>
* <li><b>{@code exo_controller}</b> - An already inflated {@link PlayerControlView}. Allows use
* of a custom extension of {@link PlayerControlView}. Note that attributes such as {@code
* rewind_increment} will not be automatically propagated through to this instance. If a view
* exists with this id, any {@code exo_controller_placeholder} view will be ignored.
* <ul>
* <li>Type: {@link PlayerControlView}
* </ul>
* <li><b>{@code exo_overlay}</b> - A {@link FrameLayout} positioned on top of the player which
* the app can access via {@link #getOverlayFrameLayout()}, provided for convenience.
* <ul>
* <li>Type: {@link FrameLayout}
* </ul>
* </ul>
*
* <p>All child views are optional and so can be omitted if not required, however where defined they
* must be of the expected type.
*
* <h3>Specifying a custom layout file</h3>
*
* Defining your own {@code exo_player_view.xml} is useful to customize the layout of PlayerView
* throughout your application. It's also possible to customize the layout for a single instance in
* a layout file. This is achieved by setting the {@code player_layout_id} attribute on a
* PlayerView. This will cause the specified layout to be inflated instead of {@code
* exo_player_view.xml} for only the instance on which the attribute is set.
*/
public class PlayerView extends FrameLayout {
private static final int SURFACE_TYPE_NONE = 0;
private static final int SURFACE_TYPE_SURFACE_VIEW = 1;
private static final int SURFACE_TYPE_TEXTURE_VIEW = 2;
private final AspectRatioFrameLayout contentFrame;
private final View shutterView;
private final View surfaceView;
private final ImageView artworkView;
private final SubtitleView subtitleView;
private final @Nullable View bufferingView;
private final @Nullable TextView errorMessageView;
private final PlayerControlView controller;
private final ComponentListener componentListener;
private final FrameLayout overlayFrameLayout;
private Player player;
private boolean useController;
private boolean useArtwork;
private Bitmap defaultArtwork;
private boolean showBuffering;
private boolean keepContentOnPlayerReset;
private @Nullable ErrorMessageProvider<? super ExoPlaybackException> errorMessageProvider;
private @Nullable CharSequence customErrorMessage;
private int controllerShowTimeoutMs;
private boolean controllerAutoShow;
private boolean controllerHideDuringAds;
private boolean controllerHideOnTouch;
private int textureViewRotation;
public PlayerView(Context context) {
this(context, null);
}
public PlayerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (isInEditMode()) {
contentFrame = null;
shutterView = null;
surfaceView = null;
artworkView = null;
subtitleView = null;
bufferingView = null;
errorMessageView = null;
controller = null;
componentListener = null;
overlayFrameLayout = null;
ImageView logo = new ImageView(context);
if (Util.SDK_INT >= 23) {
configureEditModeLogoV23(getResources(), logo);
} else {
configureEditModeLogo(getResources(), logo);
}
addView(logo);
return;
}
boolean shutterColorSet = false;
int shutterColor = 0;
int playerLayoutId = R.layout.exo_player_view;
boolean useArtwork = true;
int defaultArtworkId = 0;
boolean useController = true;
int surfaceType = SURFACE_TYPE_SURFACE_VIEW;
int resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT;
int controllerShowTimeoutMs = PlayerControlView.DEFAULT_SHOW_TIMEOUT_MS;
boolean controllerHideOnTouch = true;
boolean controllerAutoShow = true;
boolean controllerHideDuringAds = true;
boolean showBuffering = false;
if (attrs != null) {
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.PlayerView, 0, 0);
try {
shutterColorSet = a.hasValue(R.styleable.PlayerView_shutter_background_color);
shutterColor = a.getColor(R.styleable.PlayerView_shutter_background_color, shutterColor);
playerLayoutId = a.getResourceId(R.styleable.PlayerView_player_layout_id, playerLayoutId);
useArtwork = a.getBoolean(R.styleable.PlayerView_use_artwork, useArtwork);
defaultArtworkId =
a.getResourceId(R.styleable.PlayerView_default_artwork, defaultArtworkId);
useController = a.getBoolean(R.styleable.PlayerView_use_controller, useController);
surfaceType = a.getInt(R.styleable.PlayerView_surface_type, surfaceType);
resizeMode = a.getInt(R.styleable.PlayerView_resize_mode, resizeMode);
controllerShowTimeoutMs =
a.getInt(R.styleable.PlayerView_show_timeout, controllerShowTimeoutMs);
controllerHideOnTouch =
a.getBoolean(R.styleable.PlayerView_hide_on_touch, controllerHideOnTouch);
controllerAutoShow = a.getBoolean(R.styleable.PlayerView_auto_show, controllerAutoShow);
showBuffering = a.getBoolean(R.styleable.PlayerView_show_buffering, showBuffering);
keepContentOnPlayerReset =
a.getBoolean(
R.styleable.PlayerView_keep_content_on_player_reset, keepContentOnPlayerReset);
controllerHideDuringAds =
a.getBoolean(R.styleable.PlayerView_hide_during_ads, controllerHideDuringAds);
} finally {
a.recycle();
}
}
LayoutInflater.from(context).inflate(playerLayoutId, this);
componentListener = new ComponentListener();
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
// Content frame.
contentFrame = findViewById(R.id.exo_content_frame);
if (contentFrame != null) {
setResizeModeRaw(contentFrame, resizeMode);
}
// Shutter view.
shutterView = findViewById(R.id.exo_shutter);
if (shutterView != null && shutterColorSet) {
shutterView.setBackgroundColor(shutterColor);
}
// Create a surface view and insert it into the content frame, if there is one.
if (contentFrame != null && surfaceType != SURFACE_TYPE_NONE) {
ViewGroup.LayoutParams params =
new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
surfaceView =
surfaceType == SURFACE_TYPE_TEXTURE_VIEW
? new TextureView(context)
: new SurfaceView(context);
surfaceView.setLayoutParams(params);
contentFrame.addView(surfaceView, 0);
} else {
surfaceView = null;
}
// Overlay frame layout.
overlayFrameLayout = findViewById(R.id.exo_overlay);
// Artwork view.
artworkView = findViewById(R.id.exo_artwork);
this.useArtwork = useArtwork && artworkView != null;
if (defaultArtworkId != 0) {
defaultArtwork = BitmapFactory.decodeResource(context.getResources(), defaultArtworkId);
}
// Subtitle view.
subtitleView = findViewById(R.id.exo_subtitles);
if (subtitleView != null) {
subtitleView.setUserDefaultStyle();
subtitleView.setUserDefaultTextSize();
}
// Buffering view.
bufferingView = findViewById(R.id.exo_buffering);
if (bufferingView != null) {
bufferingView.setVisibility(View.GONE);
}
this.showBuffering = showBuffering;
// Error message view.
errorMessageView = findViewById(R.id.exo_error_message);
if (errorMessageView != null) {
errorMessageView.setVisibility(View.GONE);
}
// Playback control view.
PlayerControlView customController = findViewById(R.id.exo_controller);
View controllerPlaceholder = findViewById(R.id.exo_controller_placeholder);
if (customController != null) {
this.controller = customController;
} else if (controllerPlaceholder != null) {
// Propagate attrs as playbackAttrs so that PlayerControlView's custom attributes are
// transferred, but standard FrameLayout attributes (e.g. background) are not.
this.controller = new PlayerControlView(context, null, 0, attrs);
controller.setLayoutParams(controllerPlaceholder.getLayoutParams());
ViewGroup parent = ((ViewGroup) controllerPlaceholder.getParent());
int controllerIndex = parent.indexOfChild(controllerPlaceholder);
parent.removeView(controllerPlaceholder);
parent.addView(controller, controllerIndex);
} else {
this.controller = null;
}
this.controllerShowTimeoutMs = controller != null ? controllerShowTimeoutMs : 0;
this.controllerHideOnTouch = controllerHideOnTouch;
this.controllerAutoShow = controllerAutoShow;
this.controllerHideDuringAds = controllerHideDuringAds;
this.useController = useController && controller != null;
hideController();
}
/**
* Switches the view targeted by a given {@link Player}.
*
* @param player The player whose target view is being switched.
* @param oldPlayerView The old view to detach from the player.
* @param newPlayerView The new view to attach to the player.
*/
public static void switchTargetView(
@NonNull Player player,
@Nullable PlayerView oldPlayerView,
@Nullable PlayerView newPlayerView) {
if (oldPlayerView == newPlayerView) {
return;
}
// We attach the new view before detaching the old one because this ordering allows the player
// to swap directly from one surface to another, without transitioning through a state where no
// surface is attached. This is significantly more efficient and achieves a more seamless
// transition when using platform provided video decoders.
if (newPlayerView != null) {
newPlayerView.setPlayer(player);
}
if (oldPlayerView != null) {
oldPlayerView.setPlayer(null);
}
}
/** Returns the player currently set on this view, or null if no player is set. */
public Player getPlayer() {
return player;
}
/**
* Set the {@link Player} to use.
*
* <p>To transition a {@link Player} from targeting one view to another, it's recommended to use
* {@link #switchTargetView(Player, PlayerView, PlayerView)} rather than this method. If you do
* wish to use this method directly, be sure to attach the player to the new view <em>before</em>
* calling {@code setPlayer(null)} to detach it from the old one. This ordering is significantly
* more efficient and may allow for more seamless transitions.
*
* @param player The {@link Player} to use.
*/
public void setPlayer(Player player) {
if (this.player == player) {
return;
}
if (this.player != null) {
this.player.removeListener(componentListener);
Player.VideoComponent oldVideoComponent = this.player.getVideoComponent();
if (oldVideoComponent != null) {
oldVideoComponent.removeVideoListener(componentListener);
if (surfaceView instanceof TextureView) {
oldVideoComponent.clearVideoTextureView((TextureView) surfaceView);
} else if (surfaceView instanceof SurfaceView) {
oldVideoComponent.clearVideoSurfaceView((SurfaceView) surfaceView);
}
}
Player.TextComponent oldTextComponent = this.player.getTextComponent();
if (oldTextComponent != null) {
oldTextComponent.removeTextOutput(componentListener);
}
}
this.player = player;
if (useController) {
controller.setPlayer(player);
}
if (subtitleView != null) {
subtitleView.setCues(null);
}
updateBuffering();
updateErrorMessage();
updateForCurrentTrackSelections(/* isNewPlayer= */ true);
if (player != null) {
Player.VideoComponent newVideoComponent = player.getVideoComponent();
if (newVideoComponent != null) {
if (surfaceView instanceof TextureView) {
newVideoComponent.setVideoTextureView((TextureView) surfaceView);
} else if (surfaceView instanceof SurfaceView) {
newVideoComponent.setVideoSurfaceView((SurfaceView) surfaceView);
}
newVideoComponent.addVideoListener(componentListener);
}
Player.TextComponent newTextComponent = player.getTextComponent();
if (newTextComponent != null) {
newTextComponent.addTextOutput(componentListener);
}
player.addListener(componentListener);
maybeShowController(false);
} else {
hideController();
}
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
if (surfaceView instanceof SurfaceView) {
// Work around https://github.com/google/ExoPlayer/issues/3160.
surfaceView.setVisibility(visibility);
}
}
/**
* Sets the resize mode.
*
* @param resizeMode The resize mode.
*/
public void setResizeMode(@ResizeMode int resizeMode) {
Assertions.checkState(contentFrame != null);
contentFrame.setResizeMode(resizeMode);
}
/** Returns the resize mode. */
public @ResizeMode int getResizeMode() {
Assertions.checkState(contentFrame != null);
return contentFrame.getResizeMode();
}
/** Returns whether artwork is displayed if present in the media. */
public boolean getUseArtwork() {
return useArtwork;
}
/**
* Sets whether artwork is displayed if present in the media.
*
* @param useArtwork Whether artwork is displayed.
*/
public void setUseArtwork(boolean useArtwork) {
Assertions.checkState(!useArtwork || artworkView != null);
if (this.useArtwork != useArtwork) {
this.useArtwork = useArtwork;
updateForCurrentTrackSelections(/* isNewPlayer= */ false);
}
}
/** Returns the default artwork to display. */
public Bitmap getDefaultArtwork() {
return defaultArtwork;
}
/**
* Sets the default artwork to display if {@code useArtwork} is {@code true} and no artwork is
* present in the media.
*
* @param defaultArtwork the default artwork to display.
*/
public void setDefaultArtwork(Bitmap defaultArtwork) {
if (this.defaultArtwork != defaultArtwork) {
this.defaultArtwork = defaultArtwork;
updateForCurrentTrackSelections(/* isNewPlayer= */ false);
}
}
/** Returns whether the playback controls can be shown. */
public boolean getUseController() {
return useController;
}
/**
* Sets whether the playback controls can be shown. If set to {@code false} the playback controls
* are never visible and are disconnected from the player.
*
* @param useController Whether the playback controls can be shown.
*/
public void setUseController(boolean useController) {
Assertions.checkState(!useController || controller != null);
if (this.useController == useController) {
return;
}
this.useController = useController;
if (useController) {
controller.setPlayer(player);
} else if (controller != null) {
controller.hide();
controller.setPlayer(null);
}
}
/**
* Sets the background color of the {@code exo_shutter} view.
*
* @param color The background color.
*/
public void setShutterBackgroundColor(int color) {
if (shutterView != null) {
shutterView.setBackgroundColor(color);
}
}
/**
* Sets whether the currently displayed video frame or media artwork is kept visible when the
* player is reset. A player reset is defined to mean the player being re-prepared with different
* media, {@link Player#stop(boolean)} being called with {@code reset=true}, or the player being
* replaced or cleared by calling {@link #setPlayer(Player)}.
*
* <p>If enabled, the currently displayed video frame or media artwork will be kept visible until
* the player set on the view has been successfully prepared with new media and loaded enough of
* it to have determined the available tracks. Hence enabling this option allows transitioning
* from playing one piece of media to another, or from using one player instance to another,
* without clearing the view's content.
*
* <p>If disabled, the currently displayed video frame or media artwork will be hidden as soon as
* the player is reset. Note that the video frame is hidden by making {@code exo_shutter} visible.
* Hence the video frame will not be hidden if using a custom layout that omits this view.
*
* @param keepContentOnPlayerReset Whether the currently displayed video frame or media artwork is
* kept visible when the player is reset.
*/
public void setKeepContentOnPlayerReset(boolean keepContentOnPlayerReset) {
if (this.keepContentOnPlayerReset != keepContentOnPlayerReset) {
this.keepContentOnPlayerReset = keepContentOnPlayerReset;
updateForCurrentTrackSelections(/* isNewPlayer= */ false);
}
}
/**
* Sets whether a buffering spinner is displayed when the player is in the buffering state. The
* buffering spinner is not displayed by default.
*
* @param showBuffering Whether the buffering icon is displayer
*/
public void setShowBuffering(boolean showBuffering) {
if (this.showBuffering != showBuffering) {
this.showBuffering = showBuffering;
updateBuffering();
}
}
/**
* Sets the optional {@link ErrorMessageProvider}.
*
* @param errorMessageProvider The error message provider.
*/
public void setErrorMessageProvider(
@Nullable ErrorMessageProvider<? super ExoPlaybackException> errorMessageProvider) {
if (this.errorMessageProvider != errorMessageProvider) {
this.errorMessageProvider = errorMessageProvider;
updateErrorMessage();
}
}
/**
* Sets a custom error message to be displayed by the view. The error message will be displayed
* permanently, unless it is cleared by passing {@code null} to this method.
*
* @param message The message to display, or {@code null} to clear a previously set message.
*/
public void setCustomErrorMessage(@Nullable CharSequence message) {
Assertions.checkState(errorMessageView != null);
customErrorMessage = message;
updateErrorMessage();
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (player != null && player.isPlayingAd()) {
// Focus any overlay UI now, in case it's provided by a WebView whose contents may update
// dynamically. This is needed to make the "Skip ad" button focused on Android TV when using
// IMA [Internal: b/62371030].
overlayFrameLayout.requestFocus();
return super.dispatchKeyEvent(event);
}
boolean isDpadWhenControlHidden =
isDpadKey(event.getKeyCode()) && useController && !controller.isVisible();
boolean handled =
isDpadWhenControlHidden || dispatchMediaKeyEvent(event) || super.dispatchKeyEvent(event);
if (handled) {
maybeShowController(true);
}
return handled;
}
/**
* Called to process media key events. Any {@link KeyEvent} can be passed but only media key
* events will be handled. Does nothing if playback controls are disabled.
*
* @param event A key event.
* @return Whether the key event was handled.
*/
public boolean dispatchMediaKeyEvent(KeyEvent event) {
return useController && controller.dispatchMediaKeyEvent(event);
}
/** Returns whether the controller is currently visible. */
public boolean isControllerVisible() {
return controller != null && controller.isVisible();
}
/**
* Shows the playback controls. Does nothing if playback controls are disabled.
*
* <p>The playback controls are automatically hidden during playback after {{@link
* #getControllerShowTimeoutMs()}}. They are shown indefinitely when playback has not started yet,
* is paused, has ended or failed.
*/
public void showController() {
showController(shouldShowControllerIndefinitely());
}
/** Hides the playback controls. Does nothing if playback controls are disabled. */
public void hideController() {
if (controller != null) {
controller.hide();
}
}
/**
* Returns the playback controls timeout. The playback controls are automatically hidden after
* this duration of time has elapsed without user input and with playback or buffering in
* progress.
*
* @return The timeout in milliseconds. A non-positive value will cause the controller to remain
* visible indefinitely.
*/
public int getControllerShowTimeoutMs() {
return controllerShowTimeoutMs;
}
/**
* Sets the playback controls timeout. The playback controls are automatically hidden after this
* duration of time has elapsed without user input and with playback or buffering in progress.
*
* @param controllerShowTimeoutMs The timeout in milliseconds. A non-positive value will cause the
* controller to remain visible indefinitely.
*/
public void setControllerShowTimeoutMs(int controllerShowTimeoutMs) {
Assertions.checkState(controller != null);
this.controllerShowTimeoutMs = controllerShowTimeoutMs;
if (controller.isVisible()) {
// Update the controller's timeout if necessary.
showController();
}
}
/** Returns whether the playback controls are hidden by touch events. */
public boolean getControllerHideOnTouch() {
return controllerHideOnTouch;
}
/**
* Sets whether the playback controls are hidden by touch events.
*
* @param controllerHideOnTouch Whether the playback controls are hidden by touch events.
*/
public void setControllerHideOnTouch(boolean controllerHideOnTouch) {
Assertions.checkState(controller != null);
this.controllerHideOnTouch = controllerHideOnTouch;
}
/**
* Returns whether the playback controls are automatically shown when playback starts, pauses,
* ends, or fails. If set to false, the playback controls can be manually operated with {@link
* #showController()} and {@link #hideController()}.
*/
public boolean getControllerAutoShow() {
return controllerAutoShow;
}
/**
* Sets whether the playback controls are automatically shown when playback starts, pauses, ends,
* or fails. If set to false, the playback controls can be manually operated with {@link
* #showController()} and {@link #hideController()}.
*
* @param controllerAutoShow Whether the playback controls are allowed to show automatically.
*/
public void setControllerAutoShow(boolean controllerAutoShow) {
this.controllerAutoShow = controllerAutoShow;
}
/**
* Sets whether the playback controls are hidden when ads are playing. Controls are always shown
* during ads if they are enabled and the player is paused.
*
* @param controllerHideDuringAds Whether the playback controls are hidden when ads are playing.
*/
public void setControllerHideDuringAds(boolean controllerHideDuringAds) {
this.controllerHideDuringAds = controllerHideDuringAds;
}
/**
* Set the {@link PlayerControlView.VisibilityListener}.
*
* @param listener The listener to be notified about visibility changes.
*/
public void setControllerVisibilityListener(PlayerControlView.VisibilityListener listener) {
Assertions.checkState(controller != null);
controller.setVisibilityListener(listener);
}
/**
* Sets the {@link PlaybackPreparer}.
*
* @param playbackPreparer The {@link PlaybackPreparer}.
*/
public void setPlaybackPreparer(@Nullable PlaybackPreparer playbackPreparer) {
Assertions.checkState(controller != null);
controller.setPlaybackPreparer(playbackPreparer);
}
/**
* Sets the {@link ControlDispatcher}.
*
* @param controlDispatcher The {@link ControlDispatcher}, or null to use {@link
* DefaultControlDispatcher}.
*/
public void setControlDispatcher(@Nullable ControlDispatcher controlDispatcher) {
Assertions.checkState(controller != null);
controller.setControlDispatcher(controlDispatcher);
}
/**
* Sets the rewind increment in milliseconds.
*
* @param rewindMs The rewind increment in milliseconds. A non-positive value will cause the
* rewind button to be disabled.
*/
public void setRewindIncrementMs(int rewindMs) {
Assertions.checkState(controller != null);
controller.setRewindIncrementMs(rewindMs);
}
/**
* Sets the fast forward increment in milliseconds.
*
* @param fastForwardMs The fast forward increment in milliseconds. A non-positive value will
* cause the fast forward button to be disabled.
*/
public void setFastForwardIncrementMs(int fastForwardMs) {
Assertions.checkState(controller != null);
controller.setFastForwardIncrementMs(fastForwardMs);
}
/**
* Sets which repeat toggle modes are enabled.
*
* @param repeatToggleModes A set of {@link RepeatModeUtil.RepeatToggleModes}.
*/
public void setRepeatToggleModes(@RepeatModeUtil.RepeatToggleModes int repeatToggleModes) {
Assertions.checkState(controller != null);
controller.setRepeatToggleModes(repeatToggleModes);
}
/**
* Sets whether the shuffle button is shown.
*
* @param showShuffleButton Whether the shuffle button is shown.
*/
public void setShowShuffleButton(boolean showShuffleButton) {
Assertions.checkState(controller != null);
controller.setShowShuffleButton(showShuffleButton);
}
/**
* Sets whether the time bar should show all windows, as opposed to just the current one.
*
* @param showMultiWindowTimeBar Whether to show all windows.
*/
public void setShowMultiWindowTimeBar(boolean showMultiWindowTimeBar) {
Assertions.checkState(controller != null);
controller.setShowMultiWindowTimeBar(showMultiWindowTimeBar);
}
/**
* Sets the millisecond positions of extra ad markers relative to the start of the window (or
* timeline, if in multi-window mode) and whether each extra ad has been played or not. The
* markers are shown in addition to any ad markers for ads in the player's timeline.
*
* @param extraAdGroupTimesMs The millisecond timestamps of the extra ad markers to show, or
* {@code null} to show no extra ad markers.
* @param extraPlayedAdGroups Whether each ad has been played, or {@code null} to show no extra ad
* markers.
*/
public void setExtraAdGroupMarkers(
@Nullable long[] extraAdGroupTimesMs, @Nullable boolean[] extraPlayedAdGroups) {
Assertions.checkState(controller != null);
controller.setExtraAdGroupMarkers(extraAdGroupTimesMs, extraPlayedAdGroups);
}
/**
* Set the {@link AspectRatioFrameLayout.AspectRatioListener}.
*
* @param listener The listener to be notified about aspect ratios changes of the video content or
* the content frame.
*/
public void setAspectRatioListener(AspectRatioFrameLayout.AspectRatioListener listener) {
Assertions.checkState(contentFrame != null);
contentFrame.setAspectRatioListener(listener);
}
/**
* Gets the view onto which video is rendered. This is a:
*
* <ul>
* <li>{@link SurfaceView} by default, or if the {@code surface_type} attribute is set to {@code
* surface_view}.
* <li>{@link TextureView} if {@code surface_type} is {@code texture_view}.
* <li>{@code null} if {@code surface_type} is {@code none}.
* </ul>
*
* @return The {@link SurfaceView}, {@link TextureView} or {@code null}.
*/
public View getVideoSurfaceView() {
return surfaceView;
}
/**
* Gets the overlay {@link FrameLayout}, which can be populated with UI elements to show on top of
* the player.
*
* @return The overlay {@link FrameLayout}, or {@code null} if the layout has been customized and
* the overlay is not present.
*/
public FrameLayout getOverlayFrameLayout() {
return overlayFrameLayout;
}
/**
* Gets the {@link SubtitleView}.
*
* @return The {@link SubtitleView}, or {@code null} if the layout has been customized and the
* subtitle view is not present.
*/
public SubtitleView getSubtitleView() {
return subtitleView;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (!useController || player == null || ev.getActionMasked() != MotionEvent.ACTION_DOWN) {
return false;
}
if (!controller.isVisible()) {
maybeShowController(true);
} else if (controllerHideOnTouch) {
controller.hide();
}
return true;
}
@Override
public boolean onTrackballEvent(MotionEvent ev) {
if (!useController || player == null) {
return false;
}
maybeShowController(true);
return true;
}
/** Shows the playback controls, but only if forced or shown indefinitely. */
private void maybeShowController(boolean isForced) {
if (isPlayingAd() && controllerHideDuringAds) {
return;
}
if (useController) {
boolean wasShowingIndefinitely = controller.isVisible() && controller.getShowTimeoutMs() <= 0;
boolean shouldShowIndefinitely = shouldShowControllerIndefinitely();
if (isForced || wasShowingIndefinitely || shouldShowIndefinitely) {
showController(shouldShowIndefinitely);
}
}
}
private boolean shouldShowControllerIndefinitely() {
if (player == null) {
return true;
}
int playbackState = player.getPlaybackState();
return controllerAutoShow
&& (playbackState == Player.STATE_IDLE
|| playbackState == Player.STATE_ENDED
|| !player.getPlayWhenReady());
}
private void showController(boolean showIndefinitely) {
if (!useController) {
return;
}
controller.setShowTimeoutMs(showIndefinitely ? 0 : controllerShowTimeoutMs);
controller.show();
}
private boolean isPlayingAd() {
return player != null && player.isPlayingAd() && player.getPlayWhenReady();
}
private void updateForCurrentTrackSelections(boolean isNewPlayer) {
if (player == null || player.getCurrentTrackGroups().isEmpty()) {
if (!keepContentOnPlayerReset) {
hideArtwork();
closeShutter();
}
return;
}
if (isNewPlayer && !keepContentOnPlayerReset) {
// Hide any video from the previous player.
closeShutter();
}
TrackSelectionArray selections = player.getCurrentTrackSelections();
for (int i = 0; i < selections.length; i++) {
if (player.getRendererType(i) == C.TRACK_TYPE_VIDEO && selections.get(i) != null) {
// Video enabled so artwork must be hidden. If the shutter is closed, it will be opened in
// onRenderedFirstFrame().
hideArtwork();
return;
}
}
// Video disabled so the shutter must be closed.
closeShutter();
// Display artwork if enabled and available, else hide it.
if (useArtwork) {
for (int i = 0; i < selections.length; i++) {
TrackSelection selection = selections.get(i);
if (selection != null) {
for (int j = 0; j < selection.length(); j++) {
Metadata metadata = selection.getFormat(j).metadata;
if (metadata != null && setArtworkFromMetadata(metadata)) {
return;
}
}
}
}
if (setArtworkFromBitmap(defaultArtwork)) {
return;
}
}
// Artwork disabled or unavailable.
hideArtwork();
}
private boolean setArtworkFromMetadata(Metadata metadata) {
for (int i = 0; i < metadata.length(); i++) {
Metadata.Entry metadataEntry = metadata.get(i);
if (metadataEntry instanceof ApicFrame) {
byte[] bitmapData = ((ApicFrame) metadataEntry).pictureData;
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);
return setArtworkFromBitmap(bitmap);
}
}
return false;
}
private boolean setArtworkFromBitmap(Bitmap bitmap) {
if (bitmap != null) {
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
if (bitmapWidth > 0 && bitmapHeight > 0) {
if (contentFrame != null) {
contentFrame.setAspectRatio((float) bitmapWidth / bitmapHeight);
}
artworkView.setImageBitmap(bitmap);
artworkView.setVisibility(VISIBLE);
return true;
}
}
return false;
}
private void hideArtwork() {
if (artworkView != null) {
artworkView.setImageResource(android.R.color.transparent); // Clears any bitmap reference.
artworkView.setVisibility(INVISIBLE);
}
}
private void closeShutter() {
if (shutterView != null) {
shutterView.setVisibility(View.VISIBLE);
}
}
private void updateBuffering() {
if (bufferingView != null) {
boolean showBufferingSpinner =
showBuffering
&& player != null
&& player.getPlaybackState() == Player.STATE_BUFFERING
&& player.getPlayWhenReady();
bufferingView.setVisibility(showBufferingSpinner ? View.VISIBLE : View.GONE);
}
}
private void updateErrorMessage() {
if (errorMessageView != null) {
if (customErrorMessage != null) {
errorMessageView.setText(customErrorMessage);
errorMessageView.setVisibility(View.VISIBLE);
return;
}
ExoPlaybackException error = null;
if (player != null
&& player.getPlaybackState() == Player.STATE_IDLE
&& errorMessageProvider != null) {
error = player.getPlaybackError();
}
if (error != null) {
CharSequence errorMessage = errorMessageProvider.getErrorMessage(error).second;
errorMessageView.setText(errorMessage);
errorMessageView.setVisibility(View.VISIBLE);
} else {
errorMessageView.setVisibility(View.GONE);
}
}
}
@TargetApi(23)
private static void configureEditModeLogoV23(Resources resources, ImageView logo) {
logo.setImageDrawable(resources.getDrawable(R.drawable.exo_edit_mode_logo, null));
logo.setBackgroundColor(resources.getColor(R.color.exo_edit_mode_background_color, null));
}
@SuppressWarnings("deprecation")
private static void configureEditModeLogo(Resources resources, ImageView logo) {
logo.setImageDrawable(resources.getDrawable(R.drawable.exo_edit_mode_logo));
logo.setBackgroundColor(resources.getColor(R.color.exo_edit_mode_background_color));
}
@SuppressWarnings("ResourceType")
private static void setResizeModeRaw(AspectRatioFrameLayout aspectRatioFrame, int resizeMode) {
aspectRatioFrame.setResizeMode(resizeMode);
}
/** Applies a texture rotation to a {@link TextureView}. */
private static void applyTextureViewRotation(TextureView textureView, int textureViewRotation) {
float textureViewWidth = textureView.getWidth();
float textureViewHeight = textureView.getHeight();
if (textureViewWidth == 0 || textureViewHeight == 0 || textureViewRotation == 0) {
textureView.setTransform(null);
} else {
Matrix transformMatrix = new Matrix();
float pivotX = textureViewWidth / 2;
float pivotY = textureViewHeight / 2;
transformMatrix.postRotate(textureViewRotation, pivotX, pivotY);
// After rotation, scale the rotated texture to fit the TextureView size.
RectF originalTextureRect = new RectF(0, 0, textureViewWidth, textureViewHeight);
RectF rotatedTextureRect = new RectF();
transformMatrix.mapRect(rotatedTextureRect, originalTextureRect);
transformMatrix.postScale(
textureViewWidth / rotatedTextureRect.width(),
textureViewHeight / rotatedTextureRect.height(),
pivotX,
pivotY);
textureView.setTransform(transformMatrix);
}
}
@SuppressLint("InlinedApi")
private boolean isDpadKey(int keyCode) {
return keyCode == KeyEvent.KEYCODE_DPAD_UP
|| keyCode == KeyEvent.KEYCODE_DPAD_UP_RIGHT
|| keyCode == KeyEvent.KEYCODE_DPAD_RIGHT
|| keyCode == KeyEvent.KEYCODE_DPAD_DOWN_RIGHT
|| keyCode == KeyEvent.KEYCODE_DPAD_DOWN
|| keyCode == KeyEvent.KEYCODE_DPAD_DOWN_LEFT
|| keyCode == KeyEvent.KEYCODE_DPAD_LEFT
|| keyCode == KeyEvent.KEYCODE_DPAD_UP_LEFT
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER;
}
private final class ComponentListener
implements Player.EventListener, TextOutput, VideoListener, OnLayoutChangeListener {
// TextOutput implementation
@Override
public void onCues(List<Cue> cues) {
if (subtitleView != null) {
subtitleView.onCues(cues);
}
}
// VideoListener implementation
@Override
public void onVideoSizeChanged(
int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
if (contentFrame == null) {
return;
}
float videoAspectRatio =
(height == 0 || width == 0) ? 1 : (width * pixelWidthHeightRatio) / height;
if (surfaceView instanceof TextureView) {
// Try to apply rotation transformation when our surface is a TextureView.
if (unappliedRotationDegrees == 90 || unappliedRotationDegrees == 270) {
// We will apply a rotation 90/270 degree to the output texture of the TextureView.
// In this case, the output video's width and height will be swapped.
videoAspectRatio = 1 / videoAspectRatio;
}
if (textureViewRotation != 0) {
surfaceView.removeOnLayoutChangeListener(this);
}
textureViewRotation = unappliedRotationDegrees;
if (textureViewRotation != 0) {
// The texture view's dimensions might be changed after layout step.
// So add an OnLayoutChangeListener to apply rotation after layout step.
surfaceView.addOnLayoutChangeListener(this);
}
applyTextureViewRotation((TextureView) surfaceView, textureViewRotation);
}
contentFrame.setAspectRatio(videoAspectRatio);
}
@Override
public void onRenderedFirstFrame() {
if (shutterView != null) {
shutterView.setVisibility(INVISIBLE);
}
}
@Override
public void onTracksChanged(TrackGroupArray tracks, TrackSelectionArray selections) {
updateForCurrentTrackSelections(/* isNewPlayer= */ false);
}
// Player.EventListener implementation
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
updateBuffering();
updateErrorMessage();
if (isPlayingAd() && controllerHideDuringAds) {
hideController();
} else {
maybeShowController(false);
}
}
@Override
public void onPositionDiscontinuity(@DiscontinuityReason int reason) {
if (isPlayingAd() && controllerHideDuringAds) {
hideController();
}
}
// OnLayoutChangeListener implementation
@Override
public void onLayoutChange(
View view,
int left,
int top,
int right,
int bottom,
int oldLeft,
int oldTop,
int oldRight,
int oldBottom) {
applyTextureViewRotation((TextureView) view, textureViewRotation);
}
}
}
| apache-2.0 |
jtrfid/Gallery-ImageLoader | app/src/main/java/com/yetwish/horizatalscrollviewdemo/MainActivity.java | 2327 | package com.yetwish.horizatalscrollviewdemo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.ImageView;
import com.yetwish.horizatalscrollviewdemo.widget.MyHorizontalScrollView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity {
//实现滑动监听的HorizontalScrollView
private MyHorizontalScrollView mSlideGallery;
//实现点击监听的HorizontalScrollView
private MyHorizontalScrollView mClickGallery;
//用于展示当前选中的图片
private ImageView mImg;
//图片资源文件数组
private List<Integer> mData = new ArrayList<Integer>(Arrays.asList(
R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d,
R.drawable.e, R.drawable.f, R.drawable.g, R.drawable.h,
R.drawable.i, R.drawable.j, R.drawable.k));
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImg = (ImageView) findViewById(R.id.id_content);
mSlideGallery = (MyHorizontalScrollView) findViewById(R.id.slide_gallery);
mClickGallery = (MyHorizontalScrollView) findViewById(R.id.click_gallery);
//添加滚动回调
mSlideGallery.setCurrentImageChangedListener(
new MyHorizontalScrollView.CurrentImageChangedListener() {
@Override
public void onCurrentImgChanged(int position, View viewIndicator) {
mImg.setImageResource(mData.get(position));
viewIndicator.setAlpha(1f);
}
});
//初始化,配置adapter
mSlideGallery.initData(new HorizontalScrollViewAdapter(this, mData));
//添加点击回调
mClickGallery.setOnItemClickListener(
new MyHorizontalScrollView.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
mImg.setImageResource(mData.get(position));
}
});
//初始化,配置adapter
mClickGallery.initData(new HorizontalScrollViewAdapter(this, mData));
}
}
| apache-2.0 |
anuj1708/hawkular-android-client | mobile/src/androidTest/java/org/hawkular/client/android/adapter/ResourcesAdapterTester.java | 2729 | /*
* Copyright 2015-2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.client.android.adapter;
import java.util.ArrayList;
import java.util.List;
import org.assertj.android.api.Assertions;
import org.hawkular.client.android.backend.model.Resource;
import org.hawkular.client.android.backend.model.ResourceProperties;
import org.hawkular.client.android.backend.model.ResourceType;
import org.hawkular.client.android.util.Randomizer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
@RunWith(AndroidJUnit4.class)
public final class ResourcesAdapterTester {
private Context context;
@Before
public void setUp() {
context = InstrumentationRegistry.getTargetContext();
}
@Test
public void count() {
List<Resource> resources = generateResources();
ResourcesAdapter resourcesAdapter = new ResourcesAdapter(context, resources);
Assertions.assertThat(resourcesAdapter).hasCount(resources.size() * resourcesAdapter.getViewTypeCount());
}
@Test
public void item() {
Resource resource = generateResource();
List<Resource> resources = new ArrayList<>();
resources.add(resource);
resources.addAll(generateResources());
ResourcesAdapter resourcesAdapter = new ResourcesAdapter(context, resources);
Assertions.assertThat(resourcesAdapter).hasItem(resource, 0);
}
private List<Resource> generateResources() {
List<Resource> resources = new ArrayList<>();
for (int resourcePosition = 0; resourcePosition < Randomizer.generateNumber(); resourcePosition++) {
resources.add(generateResource());
}
return resources;
}
private Resource generateResource() {
return new Resource(
Randomizer.generateString(),
new ResourceType(Randomizer.generateString()),
new ResourceProperties(Randomizer.generateString()));
}
}
| apache-2.0 |
nafae/developer | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201403/LineItemOperationErrorReason.java | 3440 |
package com.google.api.ads.dfp.jaxws.v201403;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for LineItemOperationError.Reason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="LineItemOperationError.Reason">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="NOT_ALLOWED"/>
* <enumeration value="NOT_APPLICABLE"/>
* <enumeration value="HAS_COMPLETED"/>
* <enumeration value="HAS_NO_ACTIVE_CREATIVES"/>
* <enumeration value="CANNOT_ACTIVATE_LEGACY_DFP_LINE_ITEM"/>
* <enumeration value="CANNOT_DELETE_DELIVERED_LINE_ITEM"/>
* <enumeration value="CANNOT_RESERVE_COMPANY_CREDIT_STATUS_NOT_ACTIVE"/>
* <enumeration value="CANNOT_ACTIVATE_INVALID_COMPANY_CREDIT_STATUS"/>
* <enumeration value="UNKNOWN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "LineItemOperationError.Reason")
@XmlEnum
public enum LineItemOperationErrorReason {
/**
*
* The operation is not allowed due to lack of permissions.
*
*
*/
NOT_ALLOWED,
/**
*
* The operation is not applicable for the current state of the
* {@link LineItem}.
*
*
*/
NOT_APPLICABLE,
/**
*
* The {@link LineItem} is completed. A {@link LineItemAction} cannot
* be applied to a line item that is completed.
*
*
*/
HAS_COMPLETED,
/**
*
* The {@link LineItem} has no active creatives. A line item cannot be
* activated with no active creatives.
*
*
*/
HAS_NO_ACTIVE_CREATIVES,
/**
*
* A {@link LineItem} of type {@link LineItemType#LEGACY_DFP} cannot be
* Activated.
*
*
*/
CANNOT_ACTIVATE_LEGACY_DFP_LINE_ITEM,
/**
*
* Deleting an {@link LineItem} that has delivered is not allowed
*
*
*/
CANNOT_DELETE_DELIVERED_LINE_ITEM,
/**
*
* Reservation cannot be made for line item because the
* {@link LineItem#advertiserId} it is associated with has
* {@link Company#creditStatus} that is not {@code ACTIVE}
* or {@code ON_HOLD}.
*
*
*/
CANNOT_RESERVE_COMPANY_CREDIT_STATUS_NOT_ACTIVE,
/**
*
* Cannot activate line item because the {@link LineItem#advertiserId}
* it is associated with has {@link Company#creditStatus} that is not
* {@code ACTIVE}, {@code INACTIVE}, or {@code ON_HOLD}.
*
*
*/
CANNOT_ACTIVATE_INVALID_COMPANY_CREDIT_STATUS,
/**
*
* The value returned if the actual value is not exposed by the requested API version.
*
*
*/
UNKNOWN;
public String value() {
return name();
}
public static LineItemOperationErrorReason fromValue(String v) {
return valueOf(v);
}
}
| apache-2.0 |
whitesource/fs-agent | src/test/java/org/whitesource/agent/dependency/resolver/npm/YarnDependencyCollectorTest.java | 1089 | package org.whitesource.agent.dependency.resolver.npm;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.whitesource.agent.Constants;
import org.whitesource.agent.api.model.AgentProjectInfo;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.stream.Collectors;
public class YarnDependencyCollectorTest {
private YarnDependencyCollector yarnDependencyCollector;
@Before
public void setup() {
yarnDependencyCollector = new YarnDependencyCollector(false, 10000, true, true);
}
@Ignore
@Test
public void collectDependencies() {
String folderPath = Paths.get(Constants.DOT).toAbsolutePath().normalize().toString() + TestHelper.getOsRelativePath("\\src\\test\\resources\\resolver\\yarn\\");
Collection<AgentProjectInfo> agentProjectInfos = yarnDependencyCollector.collectDependencies(folderPath);
Assert.assertTrue(agentProjectInfos.stream().flatMap(project -> project.getDependencies().stream()).collect(Collectors.toList()).size() == 4);
}
} | apache-2.0 |
nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201311/AssetCreativeTemplateVariable.java | 6058 | /**
* AssetCreativeTemplateVariable.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201311;
/**
* Represents a file asset variable defined in a creative template.
* <p>
* Use {@link AssetCreativeTemplateVariableValue} to specify
* the value
* for this variable when creating {@link TemplateCreative}
* from the {@link TemplateCreative}.
*/
public class AssetCreativeTemplateVariable extends com.google.api.ads.dfp.axis.v201311.CreativeTemplateVariable implements java.io.Serializable {
/* A set of supported mime types. This set can be empty or null
* if there's no
* constraint, meaning files of any mime types are
* allowed. */
private com.google.api.ads.dfp.axis.v201311.AssetCreativeTemplateVariableMimeType[] mimeTypes;
public AssetCreativeTemplateVariable() {
}
public AssetCreativeTemplateVariable(
java.lang.String label,
java.lang.String uniqueName,
java.lang.String description,
java.lang.Boolean isRequired,
java.lang.String creativeTemplateVariableType,
com.google.api.ads.dfp.axis.v201311.AssetCreativeTemplateVariableMimeType[] mimeTypes) {
super(
label,
uniqueName,
description,
isRequired,
creativeTemplateVariableType);
this.mimeTypes = mimeTypes;
}
/**
* Gets the mimeTypes value for this AssetCreativeTemplateVariable.
*
* @return mimeTypes * A set of supported mime types. This set can be empty or null
* if there's no
* constraint, meaning files of any mime types are
* allowed.
*/
public com.google.api.ads.dfp.axis.v201311.AssetCreativeTemplateVariableMimeType[] getMimeTypes() {
return mimeTypes;
}
/**
* Sets the mimeTypes value for this AssetCreativeTemplateVariable.
*
* @param mimeTypes * A set of supported mime types. This set can be empty or null
* if there's no
* constraint, meaning files of any mime types are
* allowed.
*/
public void setMimeTypes(com.google.api.ads.dfp.axis.v201311.AssetCreativeTemplateVariableMimeType[] mimeTypes) {
this.mimeTypes = mimeTypes;
}
public com.google.api.ads.dfp.axis.v201311.AssetCreativeTemplateVariableMimeType getMimeTypes(int i) {
return this.mimeTypes[i];
}
public void setMimeTypes(int i, com.google.api.ads.dfp.axis.v201311.AssetCreativeTemplateVariableMimeType _value) {
this.mimeTypes[i] = _value;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof AssetCreativeTemplateVariable)) return false;
AssetCreativeTemplateVariable other = (AssetCreativeTemplateVariable) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.mimeTypes==null && other.getMimeTypes()==null) ||
(this.mimeTypes!=null &&
java.util.Arrays.equals(this.mimeTypes, other.getMimeTypes())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getMimeTypes() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getMimeTypes());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getMimeTypes(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(AssetCreativeTemplateVariable.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "AssetCreativeTemplateVariable"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("mimeTypes");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "mimeTypes"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201311", "AssetCreativeTemplateVariable.MimeType"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
leafclick/intellij-community | platform/lang-api/src/com/intellij/refactoring/changeSignature/ChangeSignatureHandler.java | 1293 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.changeSignature;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author Maxim.Medvedev
*/
public interface ChangeSignatureHandler extends RefactoringActionHandler {
String REFACTORING_NAME = RefactoringBundle.message("changeSignature.refactoring.name");
@Nullable
default PsiElement findTargetMember(@NotNull PsiFile file, @NotNull Editor editor) {
PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
return element != null ? findTargetMember(element) : null;
}
@Nullable
PsiElement findTargetMember(@NotNull PsiElement element);
@Override
void invoke(@NotNull Project project, PsiElement @NotNull [] elements, @Nullable DataContext dataContext);
@Nullable
String getTargetNotFoundMessage();
}
| apache-2.0 |
AndroidConsulting/maventa-java-client | src/main/java/com/maventa/secure/v11/FileAttachment.java | 6138 | /**
* FileAttachment.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.maventa.secure.v11;
public class FileAttachment implements java.io.Serializable {
private byte[] file;
private java.lang.String filename;
private java.lang.String attachment_type;
public FileAttachment() {
}
public FileAttachment(
byte[] file,
java.lang.String filename,
java.lang.String attachment_type) {
this.file = file;
this.filename = filename;
this.attachment_type = attachment_type;
}
/**
* Gets the file value for this FileAttachment.
*
* @return file
*/
public byte[] getFile() {
return file;
}
/**
* Sets the file value for this FileAttachment.
*
* @param file
*/
public void setFile(byte[] file) {
this.file = file;
}
/**
* Gets the filename value for this FileAttachment.
*
* @return filename
*/
public java.lang.String getFilename() {
return filename;
}
/**
* Sets the filename value for this FileAttachment.
*
* @param filename
*/
public void setFilename(java.lang.String filename) {
this.filename = filename;
}
/**
* Gets the attachment_type value for this FileAttachment.
*
* @return attachment_type
*/
public java.lang.String getAttachment_type() {
return attachment_type;
}
/**
* Sets the attachment_type value for this FileAttachment.
*
* @param attachment_type
*/
public void setAttachment_type(java.lang.String attachment_type) {
this.attachment_type = attachment_type;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof FileAttachment)) return false;
FileAttachment other = (FileAttachment) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.file==null && other.getFile()==null) ||
(this.file!=null &&
java.util.Arrays.equals(this.file, other.getFile()))) &&
((this.filename==null && other.getFilename()==null) ||
(this.filename!=null &&
this.filename.equals(other.getFilename()))) &&
((this.attachment_type==null && other.getAttachment_type()==null) ||
(this.attachment_type!=null &&
this.attachment_type.equals(other.getAttachment_type())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getFile() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getFile());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getFile(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getFilename() != null) {
_hashCode += getFilename().hashCode();
}
if (getAttachment_type() != null) {
_hashCode += getAttachment_type().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(FileAttachment.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://secure.maventa.com/", "FileAttachment"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("file");
elemField.setXmlName(new javax.xml.namespace.QName("", "file"));
elemField.setXmlType(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/encoding/", "base64"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("filename");
elemField.setXmlName(new javax.xml.namespace.QName("", "filename"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("attachment_type");
elemField.setXmlName(new javax.xml.namespace.QName("", "attachment_type"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
paplorinc/intellij-community | platform/lang-impl/src/com/intellij/ide/projectView/impl/AsyncProjectViewSupport.java | 12023 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.projectView.impl;
import com.intellij.ide.CopyPasteUtil;
import com.intellij.ide.bookmarks.Bookmark;
import com.intellij.ide.bookmarks.BookmarksListener;
import com.intellij.ide.projectView.ProjectViewPsiTreeChangeListener;
import com.intellij.ide.projectView.impl.ProjectViewPaneSelectionHelper.SelectionDescriptor;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.ide.util.treeView.AbstractTreeStructure;
import com.intellij.ide.util.treeView.AbstractTreeUpdater;
import com.intellij.ide.util.treeView.NodeDescriptor;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vcs.FileStatusListener;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.problems.ProblemListener;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.tree.*;
import com.intellij.ui.tree.project.ProjectFileNodeUpdater;
import com.intellij.util.SmartList;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.tree.TreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.concurrency.Promise;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import static com.intellij.ide.util.treeView.TreeState.expand;
import static com.intellij.ui.tree.project.ProjectFileNode.findArea;
class AsyncProjectViewSupport {
private static final Logger LOG = Logger.getInstance(AsyncProjectViewSupport.class);
private final ProjectFileNodeUpdater myNodeUpdater;
private final StructureTreeModel myStructureTreeModel;
private final AsyncTreeModel myAsyncTreeModel;
AsyncProjectViewSupport(@NotNull Disposable parent,
@NotNull Project project,
@NotNull JTree tree,
@NotNull AbstractTreeStructure structure,
@NotNull Comparator<NodeDescriptor> comparator) {
myStructureTreeModel = new StructureTreeModel<>(structure, comparator);
myAsyncTreeModel = new AsyncTreeModel(myStructureTreeModel, parent);
myAsyncTreeModel.setRootImmediately(myStructureTreeModel.getRootImmediately());
myNodeUpdater = new ProjectFileNodeUpdater(project, myStructureTreeModel.getInvoker()) {
@Override
protected void updateStructure(boolean fromRoot, @NotNull Set<? extends VirtualFile> updatedFiles) {
if (fromRoot) {
updateAll(null);
}
else {
long time = System.currentTimeMillis();
LOG.debug("found ", updatedFiles.size(), " changed files");
TreeCollector<VirtualFile> collector = TreeCollector.createFileRootsCollector();
for (VirtualFile file : updatedFiles) {
if (!file.isDirectory()) file = file.getParent();
if (file != null && findArea(file, project) != null) collector.add(file);
}
List<VirtualFile> roots = collector.get();
LOG.debug("found ", roots.size(), " roots in ", System.currentTimeMillis() - time, "ms");
myStructureTreeModel.getInvoker().runOrInvokeLater(() -> roots.forEach(root -> updateByFile(root, true)));
}
}
};
setModel(tree, myAsyncTreeModel);
MessageBusConnection connection = project.getMessageBus().connect(parent);
connection.subscribe(BookmarksListener.TOPIC, new BookmarksListener() {
@Override
public void bookmarkAdded(@NotNull Bookmark bookmark) {
updateByFile(bookmark.getFile(), false);
}
@Override
public void bookmarkRemoved(@NotNull Bookmark bookmark) {
updateByFile(bookmark.getFile(), false);
}
@Override
public void bookmarkChanged(@NotNull Bookmark bookmark) {
updateByFile(bookmark.getFile(), false);
}
});
PsiManager.getInstance(project).addPsiTreeChangeListener(new ProjectViewPsiTreeChangeListener(project) {
@Override
protected boolean isFlattenPackages() {
return structure instanceof AbstractProjectTreeStructure && ((AbstractProjectTreeStructure)structure).isFlattenPackages();
}
@Override
protected AbstractTreeUpdater getUpdater() {
return null;
}
@Override
protected DefaultMutableTreeNode getRootNode() {
return null;
}
@Override
protected void addSubtreeToUpdateByRoot() {
myNodeUpdater.updateFromRoot();
}
@Override
protected boolean addSubtreeToUpdateByElement(@NotNull PsiElement element) {
VirtualFile file = PsiUtilCore.getVirtualFile(element);
if (file != null) {
myNodeUpdater.updateFromFile(file);
}
else {
updateByElement(element, true);
}
return true;
}
}, parent);
FileStatusManager.getInstance(project).addFileStatusListener(new FileStatusListener() {
@Override
public void fileStatusesChanged() {
updateAllPresentations();
}
@Override
public void fileStatusChanged(@NotNull VirtualFile file) {
updateByFile(file, false);
}
}, parent);
CopyPasteUtil.addDefaultListener(parent, element -> updateByElement(element, false));
project.getMessageBus().connect(parent).subscribe(ProblemListener.TOPIC, new ProblemListener() {
@Override
public void problemsAppeared(@NotNull VirtualFile file) {
updatePresentationsFromRootTo(file);
}
@Override
public void problemsDisappeared(@NotNull VirtualFile file) {
updatePresentationsFromRootTo(file);
}
});
}
public void setComparator(@NotNull Comparator<? super NodeDescriptor> comparator) {
myStructureTreeModel.setComparator(comparator);
}
public void select(JTree tree, Object object, VirtualFile file) {
if (object instanceof AbstractTreeNode) {
AbstractTreeNode node = (AbstractTreeNode)object;
object = node.getValue();
LOG.debug("select AbstractTreeNode");
}
PsiElement element = object instanceof PsiElement ? (PsiElement)object : null;
LOG.debug("select object: ", object, " in file: ", file);
SmartList<TreePath> pathsToSelect = new SmartList<>();
TreeVisitor visitor = AbstractProjectViewPane.createVisitor(element, file, pathsToSelect);
if (visitor != null) {
//noinspection CodeBlock2Expr
myNodeUpdater.updateImmediately(() -> expand(tree, promise -> {
myAsyncTreeModel
.accept(visitor)
.onProcessed(path -> {
if (selectPaths(tree, pathsToSelect, visitor) ||
element == null ||
file == null ||
Registry.is("async.project.view.support.extra.select.disabled")) {
promise.setResult(null);
}
else {
// try to search the specified file instead of element,
// because Kotlin files cannot represent containing functions
pathsToSelect.clear();
TreeVisitor fileVisitor = AbstractProjectViewPane.createVisitor(null, file, pathsToSelect);
myAsyncTreeModel
.accept(fileVisitor)
.onProcessed(path2 -> {
selectPaths(tree, pathsToSelect, fileVisitor);
promise.setResult(null);
});
}
});
}));
}
}
private static boolean selectPaths(@NotNull JTree tree, @NotNull List<TreePath> paths, @NotNull TreeVisitor visitor) {
if (paths.isEmpty()) return false;
if (paths.size() > 1) {
if (visitor instanceof ProjectViewNodeVisitor) {
ProjectViewNodeVisitor nodeVisitor = (ProjectViewNodeVisitor)visitor;
return selectPaths(tree, new SelectionDescriptor(nodeVisitor.getElement(), nodeVisitor.getFile(), paths));
}
if (visitor instanceof ProjectViewFileVisitor) {
ProjectViewFileVisitor fileVisitor = (ProjectViewFileVisitor)visitor;
return selectPaths(tree, new SelectionDescriptor(null, fileVisitor.getElement(), paths));
}
}
TreePath path = paths.get(0);
tree.expandPath(path); // request to expand found path
TreeUtil.selectPath(tree, path); // select and scroll to center
return true;
}
private static boolean selectPaths(@NotNull JTree tree, @NotNull SelectionDescriptor selectionDescriptor) {
List<? extends TreePath> adjustedPaths = ProjectViewPaneSelectionHelper.getAdjustedPaths(selectionDescriptor);
adjustedPaths.forEach(it -> tree.expandPath(it));
TreeUtil.selectPaths(tree, adjustedPaths);
return true;
}
public void updateAll(Runnable onDone) {
LOG.debug(new RuntimeException("reload a whole tree"));
Promise<?> promise = myStructureTreeModel.invalidate();
if (onDone != null) promise.onSuccess(res -> myAsyncTreeModel.onValidThread(onDone));
}
public void update(@NotNull TreePath path, boolean structure) {
myStructureTreeModel.invalidate(path, structure);
}
public void update(@NotNull List<? extends TreePath> list, boolean structure) {
for (TreePath path : list) update(path, structure);
}
public void updateByFile(@NotNull VirtualFile file, boolean structure) {
LOG.debug(structure ? "updateChildrenByFile: " : "updatePresentationByFile: ", file);
update(null, file, structure);
}
public void updateByElement(@NotNull PsiElement element, boolean structure) {
LOG.debug(structure ? "updateChildrenByElement: " : "updatePresentationByElement: ", element);
update(element, null, structure);
}
private void update(PsiElement element, VirtualFile file, boolean structure) {
SmartList<TreePath> list = new SmartList<>();
TreeVisitor visitor = AbstractProjectViewPane.createVisitor(element, file, list);
if (visitor != null) acceptAndUpdate(visitor, list, structure);
}
private void acceptAndUpdate(@NotNull TreeVisitor visitor, List<? extends TreePath> list, boolean structure) {
myAsyncTreeModel.accept(visitor, false).onSuccess(path -> update(list, structure));
}
private void updatePresentationsFromRootTo(@NotNull VirtualFile file) {
// find first valid parent for removed file
while (!file.isValid()) {
file = file.getParent();
if (file == null) return;
}
SmartList<TreePath> structures = new SmartList<>();
SmartList<TreePath> presentations = new SmartList<>();
myAsyncTreeModel.accept(new ProjectViewFileVisitor(file, structures::add) {
@NotNull
@Override
protected Action visit(@NotNull TreePath path, @NotNull AbstractTreeNode node, @NotNull VirtualFile element) {
Action action = super.visit(path, node, element);
if (action == Action.CONTINUE) presentations.add(path);
return action;
}
}, false).onSuccess(path -> {
update(presentations, false);
update(structures, true);
});
}
private void updateAllPresentations() {
SmartList<TreePath> list = new SmartList<>();
acceptAndUpdate(new TreeVisitor() {
@NotNull
@Override
public Action visit(@NotNull TreePath path) {
list.add(path);
return Action.CONTINUE;
}
}, list, false);
}
private static void setModel(@NotNull JTree tree, @NotNull AsyncTreeModel model) {
RestoreSelectionListener listener = new RestoreSelectionListener();
tree.addTreeSelectionListener(listener);
tree.setModel(model);
Disposer.register(model, () -> {
tree.setModel(null);
tree.removeTreeSelectionListener(listener);
});
}
} | apache-2.0 |
ryandcarter/hybris-connector | src/main/java/org/mule/modules/hybris/model/PrincipalDTO.java | 71810 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.11.29 at 12:35:53 PM GMT
//
package org.mule.modules.hybris.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for principalDTO complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="principalDTO">
* <complexContent>
* <extension base="{}itemDTO">
* <sequence>
* <element name="accessibleCategories" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}category" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="allGroups" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="principalGroup" type="{}principalGroupDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="allSearchRestrictions" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="searchRestriction" type="{}searchRestrictionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="CN" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="cockpitUIConfigurations" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitUIComponentConfiguration" type="{}cockpitUIComponentConfigurationDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="DN" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="displayName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="groups" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="principalGroup" type="{}principalGroupDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="ldapsearchbase" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="profilePicture" type="{}mediaDTO" minOccurs="0"/>
* <element name="readAbstractLinkEntry" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="abstractLinkEntry" type="{}abstractLinkEntryDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="readCollections" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitObjectAbstractCollection" type="{}cockpitObjectAbstractCollectionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="readPublication" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}publication" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="readPublicationComponent" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="publicationComponent" type="{}publicationComponentDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="readSavedQueries" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitSavedQuery" type="{}cockpitSavedQueryDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="readableCatalogVersions" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="catalogVersion" type="{}catalogVersionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="readableCockpitUIComponents" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitUIComponentAccessRight" type="{}cockpitUIComponentAccessRightDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="searchRestrictions" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="searchRestriction" type="{}searchRestrictionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="syncJobs" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="syncItemJob" type="{}syncItemJobDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="visibleTemplates" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="workflowTemplate" type="{}workflowTemplateDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="watchedComments" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}comment" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="writableCatalogVersions" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="catalogVersion" type="{}catalogVersionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="writableCockpitUIComponents" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitUIComponentAccessRight" type="{}cockpitUIComponentAccessRightDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="writeCollections" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitObjectAbstractCollection" type="{}cockpitObjectAbstractCollectionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="writePublication" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}publication" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="writePublicationComponent" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="publicationComponent" type="{}publicationComponentDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="uid" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "principalDTO", propOrder = {
"accessibleCategories",
"allGroups",
"allSearchRestrictions",
"cn",
"cockpitUIConfigurations",
"dn",
"description",
"displayName",
"groups",
"ldapsearchbase",
"name",
"profilePicture",
"readAbstractLinkEntry",
"readCollections",
"readPublication",
"readPublicationComponent",
"readSavedQueries",
"readableCatalogVersions",
"readableCockpitUIComponents",
"searchRestrictions",
"syncJobs",
"visibleTemplates",
"watchedComments",
"writableCatalogVersions",
"writableCockpitUIComponents",
"writeCollections",
"writePublication",
"writePublicationComponent"
})
@XmlSeeAlso({
UserDTO.class,
PrincipalGroupDTO.class
})
public class PrincipalDTO
extends ItemDTO
{
protected PrincipalDTO.AccessibleCategories accessibleCategories;
protected PrincipalDTO.AllGroups allGroups;
protected PrincipalDTO.AllSearchRestrictions allSearchRestrictions;
@XmlElement(name = "CN")
protected String cn;
protected PrincipalDTO.CockpitUIConfigurations cockpitUIConfigurations;
@XmlElement(name = "DN")
protected String dn;
protected String description;
protected String displayName;
protected PrincipalDTO.Groups groups;
protected String ldapsearchbase;
protected String name;
protected MediaDTO profilePicture;
protected PrincipalDTO.ReadAbstractLinkEntry readAbstractLinkEntry;
protected PrincipalDTO.ReadCollections readCollections;
protected PrincipalDTO.ReadPublication readPublication;
protected PrincipalDTO.ReadPublicationComponent readPublicationComponent;
protected PrincipalDTO.ReadSavedQueries readSavedQueries;
protected PrincipalDTO.ReadableCatalogVersions readableCatalogVersions;
protected PrincipalDTO.ReadableCockpitUIComponents readableCockpitUIComponents;
protected PrincipalDTO.SearchRestrictions searchRestrictions;
protected PrincipalDTO.SyncJobs syncJobs;
protected PrincipalDTO.VisibleTemplates visibleTemplates;
protected PrincipalDTO.WatchedComments watchedComments;
protected PrincipalDTO.WritableCatalogVersions writableCatalogVersions;
protected PrincipalDTO.WritableCockpitUIComponents writableCockpitUIComponents;
protected PrincipalDTO.WriteCollections writeCollections;
protected PrincipalDTO.WritePublication writePublication;
protected PrincipalDTO.WritePublicationComponent writePublicationComponent;
@XmlAttribute(name = "uid")
protected String uid;
/**
* Gets the value of the accessibleCategories property.
*
* @return
* possible object is
* {@link PrincipalDTO.AccessibleCategories }
*
*/
public PrincipalDTO.AccessibleCategories getAccessibleCategories() {
return accessibleCategories;
}
/**
* Sets the value of the accessibleCategories property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.AccessibleCategories }
*
*/
public void setAccessibleCategories(PrincipalDTO.AccessibleCategories value) {
this.accessibleCategories = value;
}
/**
* Gets the value of the allGroups property.
*
* @return
* possible object is
* {@link PrincipalDTO.AllGroups }
*
*/
public PrincipalDTO.AllGroups getAllGroups() {
return allGroups;
}
/**
* Sets the value of the allGroups property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.AllGroups }
*
*/
public void setAllGroups(PrincipalDTO.AllGroups value) {
this.allGroups = value;
}
/**
* Gets the value of the allSearchRestrictions property.
*
* @return
* possible object is
* {@link PrincipalDTO.AllSearchRestrictions }
*
*/
public PrincipalDTO.AllSearchRestrictions getAllSearchRestrictions() {
return allSearchRestrictions;
}
/**
* Sets the value of the allSearchRestrictions property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.AllSearchRestrictions }
*
*/
public void setAllSearchRestrictions(PrincipalDTO.AllSearchRestrictions value) {
this.allSearchRestrictions = value;
}
/**
* Gets the value of the cn property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCN() {
return cn;
}
/**
* Sets the value of the cn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCN(String value) {
this.cn = value;
}
/**
* Gets the value of the cockpitUIConfigurations property.
*
* @return
* possible object is
* {@link PrincipalDTO.CockpitUIConfigurations }
*
*/
public PrincipalDTO.CockpitUIConfigurations getCockpitUIConfigurations() {
return cockpitUIConfigurations;
}
/**
* Sets the value of the cockpitUIConfigurations property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.CockpitUIConfigurations }
*
*/
public void setCockpitUIConfigurations(PrincipalDTO.CockpitUIConfigurations value) {
this.cockpitUIConfigurations = value;
}
/**
* Gets the value of the dn property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDN() {
return dn;
}
/**
* Sets the value of the dn property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDN(String value) {
this.dn = value;
}
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
/**
* Gets the value of the displayName property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDisplayName() {
return displayName;
}
/**
* Sets the value of the displayName property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDisplayName(String value) {
this.displayName = value;
}
/**
* Gets the value of the groups property.
*
* @return
* possible object is
* {@link PrincipalDTO.Groups }
*
*/
public PrincipalDTO.Groups getGroups() {
return groups;
}
/**
* Sets the value of the groups property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.Groups }
*
*/
public void setGroups(PrincipalDTO.Groups value) {
this.groups = value;
}
/**
* Gets the value of the ldapsearchbase property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLdapsearchbase() {
return ldapsearchbase;
}
/**
* Sets the value of the ldapsearchbase property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLdapsearchbase(String value) {
this.ldapsearchbase = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the profilePicture property.
*
* @return
* possible object is
* {@link MediaDTO }
*
*/
public MediaDTO getProfilePicture() {
return profilePicture;
}
/**
* Sets the value of the profilePicture property.
*
* @param value
* allowed object is
* {@link MediaDTO }
*
*/
public void setProfilePicture(MediaDTO value) {
this.profilePicture = value;
}
/**
* Gets the value of the readAbstractLinkEntry property.
*
* @return
* possible object is
* {@link PrincipalDTO.ReadAbstractLinkEntry }
*
*/
public PrincipalDTO.ReadAbstractLinkEntry getReadAbstractLinkEntry() {
return readAbstractLinkEntry;
}
/**
* Sets the value of the readAbstractLinkEntry property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.ReadAbstractLinkEntry }
*
*/
public void setReadAbstractLinkEntry(PrincipalDTO.ReadAbstractLinkEntry value) {
this.readAbstractLinkEntry = value;
}
/**
* Gets the value of the readCollections property.
*
* @return
* possible object is
* {@link PrincipalDTO.ReadCollections }
*
*/
public PrincipalDTO.ReadCollections getReadCollections() {
return readCollections;
}
/**
* Sets the value of the readCollections property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.ReadCollections }
*
*/
public void setReadCollections(PrincipalDTO.ReadCollections value) {
this.readCollections = value;
}
/**
* Gets the value of the readPublication property.
*
* @return
* possible object is
* {@link PrincipalDTO.ReadPublication }
*
*/
public PrincipalDTO.ReadPublication getReadPublication() {
return readPublication;
}
/**
* Sets the value of the readPublication property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.ReadPublication }
*
*/
public void setReadPublication(PrincipalDTO.ReadPublication value) {
this.readPublication = value;
}
/**
* Gets the value of the readPublicationComponent property.
*
* @return
* possible object is
* {@link PrincipalDTO.ReadPublicationComponent }
*
*/
public PrincipalDTO.ReadPublicationComponent getReadPublicationComponent() {
return readPublicationComponent;
}
/**
* Sets the value of the readPublicationComponent property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.ReadPublicationComponent }
*
*/
public void setReadPublicationComponent(PrincipalDTO.ReadPublicationComponent value) {
this.readPublicationComponent = value;
}
/**
* Gets the value of the readSavedQueries property.
*
* @return
* possible object is
* {@link PrincipalDTO.ReadSavedQueries }
*
*/
public PrincipalDTO.ReadSavedQueries getReadSavedQueries() {
return readSavedQueries;
}
/**
* Sets the value of the readSavedQueries property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.ReadSavedQueries }
*
*/
public void setReadSavedQueries(PrincipalDTO.ReadSavedQueries value) {
this.readSavedQueries = value;
}
/**
* Gets the value of the readableCatalogVersions property.
*
* @return
* possible object is
* {@link PrincipalDTO.ReadableCatalogVersions }
*
*/
public PrincipalDTO.ReadableCatalogVersions getReadableCatalogVersions() {
return readableCatalogVersions;
}
/**
* Sets the value of the readableCatalogVersions property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.ReadableCatalogVersions }
*
*/
public void setReadableCatalogVersions(PrincipalDTO.ReadableCatalogVersions value) {
this.readableCatalogVersions = value;
}
/**
* Gets the value of the readableCockpitUIComponents property.
*
* @return
* possible object is
* {@link PrincipalDTO.ReadableCockpitUIComponents }
*
*/
public PrincipalDTO.ReadableCockpitUIComponents getReadableCockpitUIComponents() {
return readableCockpitUIComponents;
}
/**
* Sets the value of the readableCockpitUIComponents property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.ReadableCockpitUIComponents }
*
*/
public void setReadableCockpitUIComponents(PrincipalDTO.ReadableCockpitUIComponents value) {
this.readableCockpitUIComponents = value;
}
/**
* Gets the value of the searchRestrictions property.
*
* @return
* possible object is
* {@link PrincipalDTO.SearchRestrictions }
*
*/
public PrincipalDTO.SearchRestrictions getSearchRestrictions() {
return searchRestrictions;
}
/**
* Sets the value of the searchRestrictions property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.SearchRestrictions }
*
*/
public void setSearchRestrictions(PrincipalDTO.SearchRestrictions value) {
this.searchRestrictions = value;
}
/**
* Gets the value of the syncJobs property.
*
* @return
* possible object is
* {@link PrincipalDTO.SyncJobs }
*
*/
public PrincipalDTO.SyncJobs getSyncJobs() {
return syncJobs;
}
/**
* Sets the value of the syncJobs property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.SyncJobs }
*
*/
public void setSyncJobs(PrincipalDTO.SyncJobs value) {
this.syncJobs = value;
}
/**
* Gets the value of the visibleTemplates property.
*
* @return
* possible object is
* {@link PrincipalDTO.VisibleTemplates }
*
*/
public PrincipalDTO.VisibleTemplates getVisibleTemplates() {
return visibleTemplates;
}
/**
* Sets the value of the visibleTemplates property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.VisibleTemplates }
*
*/
public void setVisibleTemplates(PrincipalDTO.VisibleTemplates value) {
this.visibleTemplates = value;
}
/**
* Gets the value of the watchedComments property.
*
* @return
* possible object is
* {@link PrincipalDTO.WatchedComments }
*
*/
public PrincipalDTO.WatchedComments getWatchedComments() {
return watchedComments;
}
/**
* Sets the value of the watchedComments property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.WatchedComments }
*
*/
public void setWatchedComments(PrincipalDTO.WatchedComments value) {
this.watchedComments = value;
}
/**
* Gets the value of the writableCatalogVersions property.
*
* @return
* possible object is
* {@link PrincipalDTO.WritableCatalogVersions }
*
*/
public PrincipalDTO.WritableCatalogVersions getWritableCatalogVersions() {
return writableCatalogVersions;
}
/**
* Sets the value of the writableCatalogVersions property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.WritableCatalogVersions }
*
*/
public void setWritableCatalogVersions(PrincipalDTO.WritableCatalogVersions value) {
this.writableCatalogVersions = value;
}
/**
* Gets the value of the writableCockpitUIComponents property.
*
* @return
* possible object is
* {@link PrincipalDTO.WritableCockpitUIComponents }
*
*/
public PrincipalDTO.WritableCockpitUIComponents getWritableCockpitUIComponents() {
return writableCockpitUIComponents;
}
/**
* Sets the value of the writableCockpitUIComponents property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.WritableCockpitUIComponents }
*
*/
public void setWritableCockpitUIComponents(PrincipalDTO.WritableCockpitUIComponents value) {
this.writableCockpitUIComponents = value;
}
/**
* Gets the value of the writeCollections property.
*
* @return
* possible object is
* {@link PrincipalDTO.WriteCollections }
*
*/
public PrincipalDTO.WriteCollections getWriteCollections() {
return writeCollections;
}
/**
* Sets the value of the writeCollections property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.WriteCollections }
*
*/
public void setWriteCollections(PrincipalDTO.WriteCollections value) {
this.writeCollections = value;
}
/**
* Gets the value of the writePublication property.
*
* @return
* possible object is
* {@link PrincipalDTO.WritePublication }
*
*/
public PrincipalDTO.WritePublication getWritePublication() {
return writePublication;
}
/**
* Sets the value of the writePublication property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.WritePublication }
*
*/
public void setWritePublication(PrincipalDTO.WritePublication value) {
this.writePublication = value;
}
/**
* Gets the value of the writePublicationComponent property.
*
* @return
* possible object is
* {@link PrincipalDTO.WritePublicationComponent }
*
*/
public PrincipalDTO.WritePublicationComponent getWritePublicationComponent() {
return writePublicationComponent;
}
/**
* Sets the value of the writePublicationComponent property.
*
* @param value
* allowed object is
* {@link PrincipalDTO.WritePublicationComponent }
*
*/
public void setWritePublicationComponent(PrincipalDTO.WritePublicationComponent value) {
this.writePublicationComponent = value;
}
/**
* Gets the value of the uid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUid() {
return uid;
}
/**
* Sets the value of the uid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUid(String value) {
this.uid = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}category" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"category"
})
public static class AccessibleCategories {
protected List<CategoryDTO> category;
/**
* Gets the value of the category property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the category property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCategory().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CategoryDTO }
*
*
*/
public List<CategoryDTO> getCategory() {
if (category == null) {
category = new ArrayList<CategoryDTO>();
}
return this.category;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="principalGroup" type="{}principalGroupDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"principalGroup"
})
public static class AllGroups {
protected List<PrincipalGroupDTO> principalGroup;
/**
* Gets the value of the principalGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the principalGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrincipalGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PrincipalGroupDTO }
*
*
*/
public List<PrincipalGroupDTO> getPrincipalGroup() {
if (principalGroup == null) {
principalGroup = new ArrayList<PrincipalGroupDTO>();
}
return this.principalGroup;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="searchRestriction" type="{}searchRestrictionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"searchRestriction"
})
public static class AllSearchRestrictions {
protected List<SearchRestrictionDTO> searchRestriction;
/**
* Gets the value of the searchRestriction property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the searchRestriction property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSearchRestriction().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SearchRestrictionDTO }
*
*
*/
public List<SearchRestrictionDTO> getSearchRestriction() {
if (searchRestriction == null) {
searchRestriction = new ArrayList<SearchRestrictionDTO>();
}
return this.searchRestriction;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitUIComponentConfiguration" type="{}cockpitUIComponentConfigurationDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"cockpitUIComponentConfiguration"
})
public static class CockpitUIConfigurations {
protected List<CockpitUIComponentConfigurationDTO> cockpitUIComponentConfiguration;
/**
* Gets the value of the cockpitUIComponentConfiguration property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cockpitUIComponentConfiguration property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCockpitUIComponentConfiguration().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CockpitUIComponentConfigurationDTO }
*
*
*/
public List<CockpitUIComponentConfigurationDTO> getCockpitUIComponentConfiguration() {
if (cockpitUIComponentConfiguration == null) {
cockpitUIComponentConfiguration = new ArrayList<CockpitUIComponentConfigurationDTO>();
}
return this.cockpitUIComponentConfiguration;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="principalGroup" type="{}principalGroupDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"principalGroup"
})
public static class Groups {
protected List<PrincipalGroupDTO> principalGroup;
/**
* Gets the value of the principalGroup property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the principalGroup property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrincipalGroup().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PrincipalGroupDTO }
*
*
*/
public List<PrincipalGroupDTO> getPrincipalGroup() {
if (principalGroup == null) {
principalGroup = new ArrayList<PrincipalGroupDTO>();
}
return this.principalGroup;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="catalogVersion" type="{}catalogVersionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"catalogVersion"
})
public static class ReadableCatalogVersions {
protected List<CatalogVersionDTO> catalogVersion;
/**
* Gets the value of the catalogVersion property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the catalogVersion property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCatalogVersion().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CatalogVersionDTO }
*
*
*/
public List<CatalogVersionDTO> getCatalogVersion() {
if (catalogVersion == null) {
catalogVersion = new ArrayList<CatalogVersionDTO>();
}
return this.catalogVersion;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitUIComponentAccessRight" type="{}cockpitUIComponentAccessRightDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"cockpitUIComponentAccessRight"
})
public static class ReadableCockpitUIComponents {
protected List<CockpitUIComponentAccessRightDTO> cockpitUIComponentAccessRight;
/**
* Gets the value of the cockpitUIComponentAccessRight property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cockpitUIComponentAccessRight property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCockpitUIComponentAccessRight().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CockpitUIComponentAccessRightDTO }
*
*
*/
public List<CockpitUIComponentAccessRightDTO> getCockpitUIComponentAccessRight() {
if (cockpitUIComponentAccessRight == null) {
cockpitUIComponentAccessRight = new ArrayList<CockpitUIComponentAccessRightDTO>();
}
return this.cockpitUIComponentAccessRight;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="abstractLinkEntry" type="{}abstractLinkEntryDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"abstractLinkEntry"
})
public static class ReadAbstractLinkEntry {
protected List<AbstractLinkEntryDTO> abstractLinkEntry;
/**
* Gets the value of the abstractLinkEntry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the abstractLinkEntry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAbstractLinkEntry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AbstractLinkEntryDTO }
*
*
*/
public List<AbstractLinkEntryDTO> getAbstractLinkEntry() {
if (abstractLinkEntry == null) {
abstractLinkEntry = new ArrayList<AbstractLinkEntryDTO>();
}
return this.abstractLinkEntry;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitObjectAbstractCollection" type="{}cockpitObjectAbstractCollectionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"cockpitObjectAbstractCollection"
})
public static class ReadCollections {
protected List<CockpitObjectAbstractCollectionDTO> cockpitObjectAbstractCollection;
/**
* Gets the value of the cockpitObjectAbstractCollection property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cockpitObjectAbstractCollection property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCockpitObjectAbstractCollection().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CockpitObjectAbstractCollectionDTO }
*
*
*/
public List<CockpitObjectAbstractCollectionDTO> getCockpitObjectAbstractCollection() {
if (cockpitObjectAbstractCollection == null) {
cockpitObjectAbstractCollection = new ArrayList<CockpitObjectAbstractCollectionDTO>();
}
return this.cockpitObjectAbstractCollection;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}publication" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"publication"
})
public static class ReadPublication {
protected List<PublicationDTO> publication;
/**
* Gets the value of the publication property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the publication property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPublication().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PublicationDTO }
*
*
*/
public List<PublicationDTO> getPublication() {
if (publication == null) {
publication = new ArrayList<PublicationDTO>();
}
return this.publication;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="publicationComponent" type="{}publicationComponentDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"publicationComponent"
})
public static class ReadPublicationComponent {
protected List<PublicationComponentDTO> publicationComponent;
/**
* Gets the value of the publicationComponent property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the publicationComponent property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPublicationComponent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PublicationComponentDTO }
*
*
*/
public List<PublicationComponentDTO> getPublicationComponent() {
if (publicationComponent == null) {
publicationComponent = new ArrayList<PublicationComponentDTO>();
}
return this.publicationComponent;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitSavedQuery" type="{}cockpitSavedQueryDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"cockpitSavedQuery"
})
public static class ReadSavedQueries {
protected List<CockpitSavedQueryDTO> cockpitSavedQuery;
/**
* Gets the value of the cockpitSavedQuery property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cockpitSavedQuery property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCockpitSavedQuery().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CockpitSavedQueryDTO }
*
*
*/
public List<CockpitSavedQueryDTO> getCockpitSavedQuery() {
if (cockpitSavedQuery == null) {
cockpitSavedQuery = new ArrayList<CockpitSavedQueryDTO>();
}
return this.cockpitSavedQuery;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="searchRestriction" type="{}searchRestrictionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"searchRestriction"
})
public static class SearchRestrictions {
protected List<SearchRestrictionDTO> searchRestriction;
/**
* Gets the value of the searchRestriction property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the searchRestriction property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSearchRestriction().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SearchRestrictionDTO }
*
*
*/
public List<SearchRestrictionDTO> getSearchRestriction() {
if (searchRestriction == null) {
searchRestriction = new ArrayList<SearchRestrictionDTO>();
}
return this.searchRestriction;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="syncItemJob" type="{}syncItemJobDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"syncItemJob"
})
public static class SyncJobs {
protected List<SyncItemJobDTO> syncItemJob;
/**
* Gets the value of the syncItemJob property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the syncItemJob property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSyncItemJob().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SyncItemJobDTO }
*
*
*/
public List<SyncItemJobDTO> getSyncItemJob() {
if (syncItemJob == null) {
syncItemJob = new ArrayList<SyncItemJobDTO>();
}
return this.syncItemJob;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="workflowTemplate" type="{}workflowTemplateDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"workflowTemplate"
})
public static class VisibleTemplates {
protected List<WorkflowTemplateDTO> workflowTemplate;
/**
* Gets the value of the workflowTemplate property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the workflowTemplate property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getWorkflowTemplate().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link WorkflowTemplateDTO }
*
*
*/
public List<WorkflowTemplateDTO> getWorkflowTemplate() {
if (workflowTemplate == null) {
workflowTemplate = new ArrayList<WorkflowTemplateDTO>();
}
return this.workflowTemplate;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}comment" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"comment"
})
public static class WatchedComments {
protected List<CommentDTO> comment;
/**
* Gets the value of the comment property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the comment property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getComment().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CommentDTO }
*
*
*/
public List<CommentDTO> getComment() {
if (comment == null) {
comment = new ArrayList<CommentDTO>();
}
return this.comment;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="catalogVersion" type="{}catalogVersionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"catalogVersion"
})
public static class WritableCatalogVersions {
protected List<CatalogVersionDTO> catalogVersion;
/**
* Gets the value of the catalogVersion property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the catalogVersion property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCatalogVersion().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CatalogVersionDTO }
*
*
*/
public List<CatalogVersionDTO> getCatalogVersion() {
if (catalogVersion == null) {
catalogVersion = new ArrayList<CatalogVersionDTO>();
}
return this.catalogVersion;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitUIComponentAccessRight" type="{}cockpitUIComponentAccessRightDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"cockpitUIComponentAccessRight"
})
public static class WritableCockpitUIComponents {
protected List<CockpitUIComponentAccessRightDTO> cockpitUIComponentAccessRight;
/**
* Gets the value of the cockpitUIComponentAccessRight property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cockpitUIComponentAccessRight property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCockpitUIComponentAccessRight().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CockpitUIComponentAccessRightDTO }
*
*
*/
public List<CockpitUIComponentAccessRightDTO> getCockpitUIComponentAccessRight() {
if (cockpitUIComponentAccessRight == null) {
cockpitUIComponentAccessRight = new ArrayList<CockpitUIComponentAccessRightDTO>();
}
return this.cockpitUIComponentAccessRight;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cockpitObjectAbstractCollection" type="{}cockpitObjectAbstractCollectionDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"cockpitObjectAbstractCollection"
})
public static class WriteCollections {
protected List<CockpitObjectAbstractCollectionDTO> cockpitObjectAbstractCollection;
/**
* Gets the value of the cockpitObjectAbstractCollection property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cockpitObjectAbstractCollection property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCockpitObjectAbstractCollection().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CockpitObjectAbstractCollectionDTO }
*
*
*/
public List<CockpitObjectAbstractCollectionDTO> getCockpitObjectAbstractCollection() {
if (cockpitObjectAbstractCollection == null) {
cockpitObjectAbstractCollection = new ArrayList<CockpitObjectAbstractCollectionDTO>();
}
return this.cockpitObjectAbstractCollection;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}publication" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"publication"
})
public static class WritePublication {
protected List<PublicationDTO> publication;
/**
* Gets the value of the publication property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the publication property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPublication().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PublicationDTO }
*
*
*/
public List<PublicationDTO> getPublication() {
if (publication == null) {
publication = new ArrayList<PublicationDTO>();
}
return this.publication;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="publicationComponent" type="{}publicationComponentDTO" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"publicationComponent"
})
public static class WritePublicationComponent {
protected List<PublicationComponentDTO> publicationComponent;
/**
* Gets the value of the publicationComponent property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the publicationComponent property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPublicationComponent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link PublicationComponentDTO }
*
*
*/
public List<PublicationComponentDTO> getPublicationComponent() {
if (publicationComponent == null) {
publicationComponent = new ArrayList<PublicationComponentDTO>();
}
return this.publicationComponent;
}
}
}
| apache-2.0 |
sakai-mirror/k2 | agnostic/shared/src/main/java/org/sakaiproject/kernel/util/StringUtils.java | 3503 | /*
* Licensed to the Sakai Foundation (SF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF 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.sakaiproject.kernel.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
*
*/
public class StringUtils {
private static final char[] TOHEX = "0123456789abcdef".toCharArray();
public static final String UTF8 = "UTF8";
public static String sha1Hash(String tohash)
throws UnsupportedEncodingException, NoSuchAlgorithmException {
byte[] b = tohash.getBytes("UTF-8");
MessageDigest sha1 = MessageDigest.getInstance("SHA");
b = sha1.digest(b);
return byteToHex(b);
}
public static String byteToHex(byte[] base) {
char[] c = new char[base.length * 2];
int i = 0;
for (byte b : base) {
int j = b;
j = j + 128;
c[i++] = TOHEX[j / 0x10];
c[i++] = TOHEX[j % 0x10];
}
return new String(c);
}
/**
* @param owners
* @param owner
* @return
*/
public static String[] addString(String[] a, String v) {
for (String o : a) {
if (v.equals(o)) {
return a;
}
}
String[] na = new String[a.length + 1];
for (int i = 0; i < a.length; i++) {
na[i] = a[i];
}
na[na.length - 1] = v;
return na;
}
/**
* Removes a <code>String</code> from a <code>String</code> array.
*
* @param a
* Array to search and remove from if String found
* @param v
* String to search for.
* @return
*/
public static String[] removeString(String[] a, String v) {
int i = 0;
for (String o : a) {
if (!v.equals(o)) {
i++;
}
}
if (i == a.length) {
return a;
}
String[] na = new String[i];
i = 0;
for (String o : a) {
if (!v.equals(o)) {
na[i++] = o;
}
}
return na;
}
/**
* Convenience method for calling join with a variable length argument rather
* than an array.
*
* @param elements
* the elements to build the string from
* @param i
* the starting index.
* @param c
* the separator character
* @return a joined string starting with the separator.
*/
public static String join(char c, String... elements) {
return org.apache.commons.lang.StringUtils.join(elements, c);
}
/**
* @param query
* @return
*/
public static String escapeJCRSQL(String query) {
StringBuilder sb = new StringBuilder();
char[] ca = query.toCharArray();
for (char c : ca) {
switch (c) {
case '\'':
sb.append("''");
break;
case '\"':
sb.append("\\\"");
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
}
| apache-2.0 |
jmaassen/AetherStackingLRMC | src/nl/esciencecenter/aether/impl/stacking/lrmc/LRMCSendPortIdentifier.java | 573 | package nl.esciencecenter.aether.impl.stacking.lrmc;
import nl.esciencecenter.aether.AetherIdentifier;
import nl.esciencecenter.aether.SendPortIdentifier;
class LRMCSendPortIdentifier implements SendPortIdentifier {
private static final long serialVersionUID = 1L;
AetherIdentifier ibis;
String name;
LRMCSendPortIdentifier(AetherIdentifier ibis, String name) {
this.ibis = ibis;
this.name = name;
}
public AetherIdentifier ibisIdentifier() {
return ibis;
}
public String name() {
return name;
}
}
| apache-2.0 |
google-ar/sceneform-android-sdk | sceneformsrc/sceneform/src/main/java/com/google/ar/sceneform/AnchorNode.java | 6541 | package com.google.ar.sceneform;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.ar.core.Anchor;
import com.google.ar.core.Pose;
import com.google.ar.core.TrackingState;
import com.google.ar.sceneform.math.MathHelper;
import com.google.ar.sceneform.math.Quaternion;
import com.google.ar.sceneform.math.Vector3;
import java.util.List;
/**
* Node that is automatically positioned in world space based on an ARCore Anchor.
*
* <p>When the Anchor isn't tracking, all children of this node are disabled.
*/
public class AnchorNode extends Node {
private static final String TAG = AnchorNode.class.getSimpleName();
// The anchor that the node is following.
@Nullable private Anchor anchor;
// Determines if the movement between the node's current position and the anchor position should
// be smoothed over time or immediate.
private boolean isSmoothed = true;
private boolean wasTracking;
private static final float SMOOTH_FACTOR = 12.0f;
/** Create an AnchorNode with no anchor. */
public AnchorNode() {}
/**
* Create an AnchorNode with the specified anchor.
*
* @param anchor the ARCore anchor that this node will automatically position itself to.
*/
@SuppressWarnings("initialization") // Suppress @UnderInitialization warning.
public AnchorNode(Anchor anchor) {
setAnchor(anchor);
}
/**
* Set an ARCore anchor and force the position of this node to be updated immediately.
*
* @param anchor the ARCore anchor that this node will automatically position itself to.
*/
public void setAnchor(@Nullable Anchor anchor) {
this.anchor = anchor;
if (this.anchor != null) {
// Force the anchored position to be updated immediately.
updateTrackedPose(0.0f, true);
}
// Make sure children are enabled based on the initial state of the anchor.
// This is particularly important for Hosted Anchors, which aren't tracking when created.
wasTracking = isTracking();
setChildrenEnabled(wasTracking || anchor == null);
}
/** Returns the ARCore anchor if it exists or null otherwise. */
@Nullable
public Anchor getAnchor() {
return anchor;
}
/**
* Set true to smooth the transition between the node’s current position and the anchor position.
* Set false to apply transformations immediately. Smoothing is true by default.
*
* @param smoothed Whether the transformations are interpolated.
*/
public void setSmoothed(boolean smoothed) {
this.isSmoothed = smoothed;
}
/**
* Returns true if the transformations are interpolated or false if they are applied immediately.
*/
public boolean isSmoothed() {
return isSmoothed;
}
/** Returns true if the ARCore anchor’s tracking state is TRACKING. */
public boolean isTracking() {
if (anchor == null || anchor.getTrackingState() != TrackingState.TRACKING) {
return false;
}
return true;
}
/**
* AnchorNode overrides this to update the node's position to match the ARCore Anchor's position.
*
* @param frameTime provides time information for the current frame
*/
@Override
public void onUpdate(FrameTime frameTime) {
updateTrackedPose(frameTime.getDeltaSeconds(), false);
}
/**
* Set the local-space position of this node if it is not anchored. If the node is anchored, this
* call does nothing.
*
* @param position The position to apply.
*/
@Override
public void setLocalPosition(Vector3 position) {
if (anchor != null) {
Log.w(TAG, "Cannot call setLocalPosition on AnchorNode while it is anchored.");
return;
}
super.setLocalPosition(position);
}
/**
* Set the world-space position of this node if it is not anchored. If the node is anchored, this
* call does nothing.
*
* @param position The position to apply.
*/
@Override
public void setWorldPosition(Vector3 position) {
if (anchor != null) {
Log.w(TAG, "Cannot call setWorldPosition on AnchorNode while it is anchored.");
return;
}
super.setWorldPosition(position);
}
/**
* Set the local-space rotation of this node if it is not anchored. If the node is anchored, this
* call does nothing.
*
* @param rotation The rotation to apply.
*/
@Override
public void setLocalRotation(Quaternion rotation) {
if (anchor != null) {
Log.w(TAG, "Cannot call setLocalRotation on AnchorNode while it is anchored.");
return;
}
super.setLocalRotation(rotation);
}
/**
* Set the world-space rotation of this node if it is not anchored. If the node is anchored, this
* call does nothing.
*
* @param rotation The rotation to apply.
*/
@Override
public void setWorldRotation(Quaternion rotation) {
if (anchor != null) {
Log.w(TAG, "Cannot call setWorldRotation on AnchorNode while it is anchored.");
return;
}
super.setWorldRotation(rotation);
}
private void updateTrackedPose(float deltaSeconds, boolean forceImmediate) {
boolean isTracking = isTracking();
// Hide the children if the anchor isn't currently tracking.
if (isTracking != wasTracking) {
// The children should be enabled if there is no anchor, even though we aren't tracking in
// that case.
setChildrenEnabled(isTracking || anchor == null);
}
// isTracking already checks if the anchor is null, but we need the anchor null check for
// static analysis.
if (anchor == null || !isTracking) {
wasTracking = isTracking;
return;
}
Pose pose = anchor.getPose();
Vector3 desiredPosition = ArHelpers.extractPositionFromPose(pose);
Quaternion desiredRotation = ArHelpers.extractRotationFromPose(pose);
if (isSmoothed && !forceImmediate) {
Vector3 position = getWorldPosition();
float lerpFactor = MathHelper.clamp(deltaSeconds * SMOOTH_FACTOR, 0, 1);
position.set(Vector3.lerp(position, desiredPosition, lerpFactor));
super.setWorldPosition(position);
Quaternion rotation = Quaternion.slerp(getWorldRotation(), desiredRotation, lerpFactor);
super.setWorldRotation(rotation);
} else {
super.setWorldPosition(desiredPosition);
super.setWorldRotation(desiredRotation);
}
wasTracking = isTracking;
}
private void setChildrenEnabled(boolean enabled) {
List<Node> children = getChildren();
for (int i = 0; i < children.size(); i++) {
Node child = children.get(i);
child.setEnabled(enabled);
}
}
}
| apache-2.0 |
jpaulm/javafbp | src/main/java/com/jpaulmorrison/fbp/core/engine/SubIn.java | 2774 | /*
* JavaFBP - A Java Implementation of Flow-Based Programming (FBP)
* Copyright (C) 2009, 2016 J. Paul Morrison
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, see the GNU Library General Public License v3
* at https://www.gnu.org/licenses/lgpl-3.0.en.html for more details.
*/
package com.jpaulmorrison.fbp.core.engine;
import com.jpaulmorrison.fbp.core.engine.Component;
import com.jpaulmorrison.fbp.core.engine.InPort;
import com.jpaulmorrison.fbp.core.engine.InputPort;
import com.jpaulmorrison.fbp.core.engine.OutPort;
import com.jpaulmorrison.fbp.core.engine.OutputPort;
import com.jpaulmorrison.fbp.core.engine.Packet;
/**
* Look after input to subnet - added for subnet support
*/
@InPort("NAME")
@OutPort("OUT")
public class SubIn extends Component {
private InputPort inport, nameport;
private OutputPort outport;
@Override
protected void execute() {
Packet<?> np = nameport.receive();
if (np == null) {
return;
}
nameport.close();
String pname = (String) np.getContent();
drop(np);
if (outport.isClosed) {
return;
}
inport = mother.getInports().get(pname);
mother.traceFuncs(getName() + ": Accessing input port: " + inport.getName());
Packet<?> p;
// I think this works!
Component oldReceiver;
if (inport instanceof InitializationConnection) {
InitializationConnection iico = (InitializationConnection) inport;
oldReceiver = iico.getReceiver();
InitializationConnection iic = new InitializationConnection(iico.content, this);
iic.name = iico.name;
//iic.network = iico.network;
p = iic.receive();
p.setOwner(this);
outport.send(p);
iic.close();
} else {
oldReceiver = ((Connection) inport).getReceiver();
((Connection) inport).setReceiver(this);
//Connection c = (Connection) inport;
while ((p = inport.receive()) != null) {
p.setOwner(this);
outport.send(p);
}
}
// inport.close();
mother.traceFuncs(getName() + ": Releasing input port: " + inport.getName());
inport.setReceiver(oldReceiver);
}
@Override
protected void openPorts() {
nameport = openInput("NAME");
outport = openOutput("OUT");
}
}
| artistic-2.0 |
Seven-and-Nine/example-code-for-nine | Java/normal code/Java II/Lab11/TokenSequence.java | 966 | public class TokenSequence implements Incrementable, Comparable<TokenSequence>
{
private String[] tokens;
private int count;
public TokenSequence(String[] input)
{
tokens = input;
count = 1;
}
public String[] getTokens()
{
return tokens;
}
public void increment()
{
count++;
}
public void decrement()
{
count--;
}
public int getCount()
{
return count;
}
public void setCount(int i)
{
count = i;
}
public int compareTo(TokenSequence t)
{
String[] s = t.getTokens();
int l = s.length;
for(int i=0;i<tokens.length;i++)
{
if( i==l)
return 1;
int value = tokens[i].compareTo(s[i]);
if(value != 0)
return value;
}
if(l>tokens.length)
return -1;
return 0;
}
public String toString()
{
String output = count+": ";
for(int i=0;i<tokens.length;i++)
output += tokens[i]+" ";
return output;
}
} | artistic-2.0 |
BlackburnCollege/cs212-lecture-sp16 | edu/blackburn/cs/cs212sp16/polymorphicmeasurement/Volume.java | 412 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.blackburn.cs.cs212sp16.polymorphicmeasurement;
/**
*
* @author joshua.gross
*/
public class Volume extends Measurement {
public Volume (String unit, double value) {
super(unit, value);
}
}
| artistic-2.0 |
C07770/dynaform-java | src/main/java/org/dynaform/xml/Factory.java | 156 | package org.dynaform.xml;
/**
* Factory.
*
* @author Rein Raudjärv
* @param <E> the result type.
*/
public interface Factory<E> {
E create();
}
| artistic-2.0 |
pm4j/org.pm4j | pm4j-deprecated/src/main/java/org/pm4j/deprecated/core/pm/DeprPmAttrPmRef.java | 1045 | package org.pm4j.deprecated.core.pm;
import org.pm4j.core.pm.PmAttr;
import org.pm4j.core.pm.PmBean;
import org.pm4j.core.pm.annotation.PmFactoryCfg;
/**
* Presentation model for references to other bean that is represented by a PM.
* <p>
* The PM for the referenced bean will be created according to the
* {@link PmFactoryCfg}. That configuration may also be inherited by its parent
* context.
*
* @author olaf boede
*
* @deprecated Please use {@link PmBean} instead.
*/
@Deprecated
public interface DeprPmAttrPmRef<T_REFED_PM extends PmBean<?>> extends PmAttr<T_REFED_PM> {
/**
* Sets the reference using a bean.
*
* @param bean A bean to reference.
* @return The presentation model for the given bean.
*/
T_REFED_PM setValueAsBean(Object bean);
/**
* @return The bean behind the referenced model.
*/
Object getValueAsBean();
/**
* Repeated base class signature. Allows reflection based frameworks (such as
* EL) to identify the referenced type.
*/
@Override
T_REFED_PM getValue();
}
| bsd-2-clause |
AntoniusW/Alpha | src/main/java/at/ac/tuwien/kr/alpha/common/rule/BasicRule.java | 2281 | /**
* Copyright (c) 2019, the Alpha Team.
* All rights reserved.
*
* Additional changes made by Siemens.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1) Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package at.ac.tuwien.kr.alpha.common.rule;
import java.util.ArrayList;
import java.util.List;
import at.ac.tuwien.kr.alpha.common.atoms.Literal;
import at.ac.tuwien.kr.alpha.common.rule.head.Head;
/**
* Represents a non-ground rule or a constraint. A @{link BasicRule} has a general {@link Head}, meaning both choice
* heads and disjunctive heads are permissible.
* This implementation represents a rule after being parsed from a given ASP program, but before being transformed into
* a @{link NormalRule}.
*/
public class BasicRule extends AbstractRule<Head> {
public BasicRule(Head head, List<Literal> body) {
super(head, body);
}
public static BasicRule getInstance(Head head, Literal... body) {
List<Literal> bodyLst = new ArrayList<>();
for (Literal lit : body) {
bodyLst.add(lit);
}
return new BasicRule(head, bodyLst);
}
}
| bsd-2-clause |
dmurph/protobee | gnutella6/src/main/java/org/protobee/gnutella/messages/MessageHeader.java | 4052 | package org.protobee.gnutella.messages;
import java.util.Arrays;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
public class MessageHeader {
public static interface Factory {
MessageHeader create(byte[] guid, @Assisted("payloadType") byte payloadType,
@Assisted("ttl") byte ttl, @Assisted("hops") byte hops, int payloadLength);
MessageHeader create(byte[] guid, @Assisted("payloadType") byte payloadType,
@Assisted("ttl") byte ttl);
MessageHeader create(@Assisted byte[] guid, @Assisted("payloadType") byte payloadType,
@Assisted("ttl") byte ttl, @Assisted("hops") byte hops);
}
public static final int UNKNOWN_PAYLOAD_LENGTH = -1;
public static final int MESSAGE_HEADER_LENGTH = 23;
public static final byte F_PING = (byte) 0x0;
public static final byte F_PING_REPLY = (byte) 0x1;
public static final byte F_PUSH = (byte) 0x40;
public static final byte F_QUERY = (byte) 0x80;
public static final byte F_QUERY_REPLY = (byte) 0x81;
public static final byte F_ROUTE_TABLE_UPDATE = (byte) 0x30;
public static final byte F_VENDOR_MESSAGE = (byte) 0x31;
public static final byte F_VENDOR_MESSAGE_STABLE = (byte) 0x32;
public static final byte F_UDP_CONNECTION = (byte) 0x41;
private final byte[] guid;
private final byte payloadType;
private final byte ttl;
private final byte hops;
private int payloadLength;
@AssistedInject
public MessageHeader(@Assisted byte[] guid, @Assisted("payloadType") byte payloadType,
@Assisted("ttl") byte ttl, @Assisted("hops") byte hops, @Assisted int payloadLength) {
this.guid = guid;
this.payloadType = payloadType;
this.ttl = ttl;
this.hops = hops;
this.payloadLength = payloadLength;
}
@AssistedInject
public MessageHeader(@Assisted byte[] guid, @Assisted("payloadType") byte payloadType,
@Assisted("ttl") byte ttl, @Assisted("hops") byte hops) {
this.guid = guid;
this.payloadType = payloadType;
this.ttl = ttl;
this.hops = hops;
this.payloadLength = UNKNOWN_PAYLOAD_LENGTH;
}
@AssistedInject
public MessageHeader(@Assisted byte[] guid, @Assisted("payloadType") byte payloadType,
@Assisted("ttl") byte ttl) {
this.guid = guid;
this.payloadType = payloadType;
this.ttl = ttl;
this.hops = 0;
this.payloadLength = UNKNOWN_PAYLOAD_LENGTH;
}
public byte getTtl() {
return ttl;
}
public byte getHops() {
return hops;
}
public int getPayloadLength() {
return payloadLength;
}
public void setPayloadLength(int payloadLength) {
this.payloadLength = payloadLength;
}
public boolean isPayloadLengthUnknown() {
return payloadLength == UNKNOWN_PAYLOAD_LENGTH;
}
public byte[] getGuid() {
return guid;
}
public byte getPayloadType() {
return payloadType;
}
@Override
public String toString() {
return "{ guid: " + guid + ", hops: " + hops + ", ttl: " + ttl + ", payloadType: "
+ payloadType + ", payloadLength: " + payloadLength + "}";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(guid);
result = prime * result + hops;
result = prime * result + payloadLength;
result = prime * result + payloadType;
result = prime * result + ttl;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
MessageHeader other = (MessageHeader) obj;
if (!Arrays.equals(guid, other.guid)) return false;
if (hops != other.hops) return false;
if (payloadLength != other.payloadLength) return false;
if (payloadType != other.payloadType) return false;
if (ttl != other.ttl) return false;
return true;
}
}
| bsd-2-clause |
fjakop/ngcalsync | src/test/java/de/jakop/ngcalsync/util/file/DefaultFileAccessorTest.java | 2467 | /**
* Copyright © 2012, Frank Jakop
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.jakop.ngcalsync.util.file;
import static org.junit.Assert.assertEquals;
import java.io.File;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import de.jakop.ngcalsync.Constants;
/**
*
* @author fjakop
*
*/
@SuppressWarnings("nls")
public class DefaultFileAccessorTest {
private TempFileManager manager;
/** */
@Before
public void before() {
manager = new TempFileManager();
manager.setUserHomeToTempDir();
}
/** */
@After
public void after() {
manager.deleteTempDir();
}
/**
*
* @throws Exception
*/
@Test
public void testGetSettingsDir_CreateDirs() throws Exception {
final File expected = new File(System.getProperty("user.home") + File.separator + Constants.FILENAME_SETTINGS_DIR, "foo");
final DefaultFileAccessor accessor = new DefaultFileAccessor();
assertEquals(expected, accessor.getFile("foo"));
}
}
| bsd-2-clause |
EIDSS/EIDSS-Legacy | EIDSS v6.1/Android/app/src/main/java/com/bv/eidss/web/VectorBaseReferenceRaw.java | 2674 | package com.bv.eidss.web;
import com.bv.eidss.model.BaseReferenceType;
import java.util.ArrayList;
@SuppressWarnings("serial")
public class VectorBaseReferenceRaw extends ArrayList<BaseReferenceRaw> {
public ArrayList<Long> brTypes = new ArrayList<>();
public VectorBaseReferenceRaw(ArrayList<Long> ffTypes){
//full list of resources
brTypes.add(BaseReferenceType.rftDiagnosis);
brTypes.add(BaseReferenceType.rftAnimalAgeList);
brTypes.add(BaseReferenceType.rftAnimalCondition);
brTypes.add(BaseReferenceType.rftAnimalSex);
brTypes.add(BaseReferenceType.rftSampleType);
brTypes.add(BaseReferenceType.rftSampleTypeForDiagnosis);
brTypes.add(BaseReferenceType.rftHumanAgeType);
brTypes.add(BaseReferenceType.rftHumanGender);
brTypes.add(BaseReferenceType.rftFinalState);
brTypes.add(BaseReferenceType.rftHospStatus);
brTypes.add(BaseReferenceType.rftInstitutionName);
brTypes.add(BaseReferenceType.rftCaseClassification);
brTypes.add(BaseReferenceType.rftYesNoValue);
brTypes.add(BaseReferenceType.rftNationality);
brTypes.add(BaseReferenceType.rftPersonIDType);
brTypes.add(BaseReferenceType.rftOutcome);
brTypes.add(BaseReferenceType.rftNotCollectedReason);
brTypes.add(BaseReferenceType.rftCaseType);
brTypes.add(BaseReferenceType.rftCaseReportType);
brTypes.add(BaseReferenceType.rftSpeciesList);
brTypes.add(BaseReferenceType.rftFFRuleMessage);
brTypes.add(BaseReferenceType.rftFFTemplate);
brTypes.add(BaseReferenceType.rftFFType);
brTypes.add(BaseReferenceType.rftParameter);
brTypes.add(BaseReferenceType.rftParametersFixedPresetValue);
brTypes.add(BaseReferenceType.rftCampaignType);
brTypes.add(BaseReferenceType.rftMonitoringSessionStatus);
//FF
brTypes.add(BaseReferenceType.rftParameterTooltip);
brTypes.add(BaseReferenceType.rftSection);
brTypes.add(BaseReferenceType.rftFlexibleFormLabelText);
if(ffTypes != null) {
for (long r: ffTypes) {
if (!brTypes.contains(r)) brTypes.add(r);
}
}
for(long tp : brTypes){
AddRefType(tp);
}
}
public void AddRefType(long type) {
BaseReferenceRaw r = new BaseReferenceRaw();
r.idfsBaseReference = 0L;
r.idfsReferenceType = type;
r.intHACode = 482;
r.strDefault = "";
r.intFeature1 = 0L;
r.intFeature2 = 0L;
this.add(r);
}
}
| bsd-2-clause |
BurnyDaKath/OMGPI | omgpi-main/src/main/tk/omgpi/events/player/OMGDeathEvent.java | 934 | package tk.omgpi.events.player;
import org.bukkit.entity.Entity;
import org.bukkit.event.Cancellable;
import tk.omgpi.OMGPI;
import tk.omgpi.events.OMGEvent;
import tk.omgpi.game.OMGPlayer;
public class OMGDeathEvent extends OMGEvent implements Cancellable {
public boolean cancel;
public OMGDamageEvent damageEvent;
public OMGPlayer damaged;
public Entity damager;
public OMGDeathEvent(OMGDamageEvent e) {
super(e.bukkit);
cancel = false;
this.damageEvent = e;
this.damaged = e.damaged;
this.damager = e.damager;
OMGPI.g.event_player_death(this);
}
public boolean isCancelled() {
return cancel;
}
public void setCancelled(boolean b) {
cancel = b;
}
/**
* Send kill message to all players.
*/
public void sendDeathMessage() {
OMGPI.g.broadcast(damageEvent.reason.getDeathMessage(damaged));
}
}
| bsd-2-clause |
m-entrup/EFTEMj | EFTEMj-lib/src/main/java/de/m_entrup/EFTEMj_lib/lma/FunctionList.java | 3123 | /**
* EFTEMj - Processing of Energy Filtering TEM images with ImageJ
*
* Copyright (c) 2016, Michael Entrup b. Epping
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. 2. Redistributions in
* binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package de.m_entrup.EFTEMj_lib.lma;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
/**
* @author Michael Entrup b. Epping
*/
public class FunctionList {
private final HashMap<String, EELS_BackgroundFunction> functions;
public FunctionList() {
functions = new HashMap<>();
final Reflections reflections = new Reflections("de.m_entrup.EFTEMj_lib.lma", new SubTypesScanner(false));
final Set<Class<? extends EELS_BackgroundFunction>> allClasses = reflections
.getSubTypesOf(EELS_BackgroundFunction.class);
final Iterator<Class<? extends EELS_BackgroundFunction>> iter = allClasses.iterator();
while (iter.hasNext()) {
final Class<? extends EELS_BackgroundFunction> function = iter.next();
try {
final EELS_BackgroundFunction functionInstance = function.newInstance();
functions.put(functionInstance.getFunctionName(), functionInstance);
} catch (final InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (final IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public HashMap<String, EELS_BackgroundFunction> getFunctions() {
return functions;
}
public String[] getKeys() {
final Set<String> set = functions.keySet();
final String[] keys = new String[functions.size()];
final Iterator<String> iter = set.iterator();
int index = 0;
while (iter.hasNext()) {
keys[index] = iter.next();
index++;
}
return keys;
}
}
| bsd-2-clause |
fritzprix/ez-bluetooth | src/test/java/com/example/ezbluetooth/ExampleUnitTest.java | 401 | package com.example.ezbluetooth;
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);
}
} | bsd-2-clause |
RealTimeGenomics/rtg-tools | test/com/rtg/graph/DataBundleTest.java | 3904 | /*
* Copyright (c) 2014. Real Time Genomics Limited.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rtg.graph;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.reeltwo.plot.Datum2D;
import com.reeltwo.plot.Graph2D;
import com.reeltwo.plot.PointPlot2D;
import com.reeltwo.plot.TextPoint2D;
import com.rtg.vcf.eval.RocPoint;
import junit.framework.TestCase;
/**
*/
public class DataBundleTest extends TestCase {
public void test() {
final List<RocPoint<String>> points = new ArrayList<>();
points.add(new RocPoint<>("5.0", 5.0f, 4.0f, 0));
points.add(new RocPoint<>("9.0", 200.0f, 100.0f, 0));
final DataBundle db = new DataBundle(300, points);
db.setGraphType(DataBundle.GraphType.ROC);
db.setTitle("Monkey");
db.setScoreName("age");
assertEquals(300, db.getTotalVariants());
assertEquals(100.0, db.getPlot(1, 1).getHi(Graph2D.X), 1e-9);
assertEquals(200.0, db.getPlot(1, 1).getHi(Graph2D.Y), 1e-9);
assertEquals(4.0, db.getPlot(1, 1).getLo(Graph2D.X), 1e-9);
assertEquals(5.0, db.getPlot(1, 1).getLo(Graph2D.Y), 1e-9);
assertEquals("Monkey", db.getTitle());
assertEquals(2, db.getPlot(1, 1).getData().length);
}
public void testAutoName() {
assertEquals("monkey age", DataBundle.autoName(new File("vcfeval-monkey", "weighted_roc.tsv"), "age"));
assertEquals("monkey age", DataBundle.autoName(new File("vcfeval_monkey.vcfeval", "weighted_roc.tsv"), "age"));
assertEquals("monkey age", DataBundle.autoName(new File("eval.monkey-eval", "weighted_roc.tsv"), "age"));
assertEquals("monkey_vcfeval.repeat snp age", DataBundle.autoName(new File("monkey_vcfeval.repeat", "snp_roc.tsv"), "age"));
}
public void testScoreLabels() {
final ArrayList<RocPoint<String>> points = new ArrayList<>();
for (int i = 0; i < 100; ++i) {
final String label = i == 99 ? "None" : String.format("%.3g", (float) (100 - i));
points.add(new RocPoint<>(label, i, i, 0));
}
final DataBundle db = new DataBundle(300, points);
db.setTitle("Monkey");
db.setGraphType(DataBundle.GraphType.ROC);
db.setScoreMax(1.0f);
final PointPlot2D scorePoints = db.getScorePoints(1, 1);
final String[] exp = {"100", "90.0", "80.0", "70.0", "60.0", "50.0", "40.0", "30.0", "20.0", "10.0", "None"};
final Datum2D[] data = scorePoints.getData();
for (int i = 0; i < data.length; ++i) {
final Datum2D d = data[i];
assertTrue(d instanceof TextPoint2D);
final TextPoint2D p = (TextPoint2D) d;
assertEquals(exp[i], p.getText());
}
}
}
| bsd-2-clause |
bonej-org/BoneJ2 | Modern/ops/src/test/java/org/bonej/ops/ellipsoid/EllipsoidPointsTest.java | 5463 | /*-
* #%L
* Ops created for BoneJ2
* %%
* Copyright (C) 2015 - 2020 Michael Doube, BoneJ developers
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
/*
BSD 2-Clause License
Copyright (c) 2018, Michael Doube, Richard Domander, Alessandro Felder
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.bonej.ops.ellipsoid;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.function.BiFunction;
import java.util.function.Function;
import net.imagej.ImageJ;
import org.joml.Vector3d;
import org.junit.AfterClass;
import org.junit.Test;
/**
* Tests for {@link EllipsoidPoints}.
*
* @author Richard Domander
*/
public class EllipsoidPointsTest {
private static ImageJ IMAGE_J = new ImageJ();
@Test
public void testEllipsoidEquation() {
final double a = 1.0;
final double b = 2.0;
final double c = 3.0;
final Function<Vector3d, Double> eq = p -> {
final BiFunction<Double, Double, Double> g = (x, r) -> (x * x) / (r * r);
return g.apply(p.x, a) + g.apply(p.y, b) + g.apply(p.z, c);
};
@SuppressWarnings("unchecked")
final Collection<Vector3d> points = (Collection<Vector3d>) IMAGE_J.op().run(
EllipsoidPoints.class, new double[] { b, a, c }, 1000);
points.forEach(p -> assertEquals("Point not on the ellipsoid surface", 1.0,
eq.apply(p), 1e-10));
assertTrue(points.stream().allMatch(p -> Math.abs(p.x) <= a));
assertTrue(points.stream().allMatch(p -> Math.abs(p.y) <= b));
assertTrue(points.stream().allMatch(p -> Math.abs(p.z) <= c));
}
@Test(expected = IllegalArgumentException.class)
public void testMatchingFailsWithInfiniteRadii() {
IMAGE_J.op().run(EllipsoidPoints.class, new double[] {
Double.POSITIVE_INFINITY, 1, 1 }, 1_000);
}
@Test(expected = IllegalArgumentException.class)
public void testMatchingFailsWithNanRadii() {
IMAGE_J.op().run(EllipsoidPoints.class, new double[] { 1, 1, Double.NaN },
1_000);
}
@Test(expected = IllegalArgumentException.class)
public void testMatchingFailsWithNegativeN() {
IMAGE_J.op().run(EllipsoidPoints.class, new double[] { 1, 1, 1 }, -1);
}
@Test(expected = IllegalArgumentException.class)
public void testMatchingFailsWithNegativeRadii() {
IMAGE_J.op().run(EllipsoidPoints.class, new double[] { 1, 1, -1 }, 1_000);
}
@Test(expected = IllegalArgumentException.class)
public void testMatchingFailsWithTooFewRadii() {
IMAGE_J.op().run(EllipsoidPoints.class, new double[] { 1, 1 }, 1_000);
}
@Test(expected = IllegalArgumentException.class)
public void testMatchingFailsWithTooManyRadii() {
IMAGE_J.op().run(EllipsoidPoints.class, new double[] { 1, 1, 1, 1 }, 1_000);
}
@Test(expected = IllegalArgumentException.class)
public void testMatchingFailsWithZeroRadii() {
IMAGE_J.op().run(EllipsoidPoints.class, new double[] { 1, 0, 1 }, 1_000);
}
@AfterClass
public static void oneTimeTearDown() {
IMAGE_J.context().dispose();
IMAGE_J = null;
}
}
| bsd-2-clause |
em7/SmashKah | desktop/src/main/java/com/github/em7/smashkah/desktop/GameScreenRender.java | 4886 | package com.github.em7.smashkah.desktop;
import java.awt.Graphics2D;
import java.util.List;
import com.github.em7.smashkah.model_interfaces.GameScreen;
import com.github.em7.smashkah.model_interfaces.ScreenCharacter;
import com.github.em7.smashkah.model_interfaces.ScreenMessage;
/**
* A render operation for the main game screen.
*/
public class GameScreenRender {
private final int BORDER_W_H;
private final int charW;
private final int charH;
private final int ascentH;
private final FpsCountToConsole fpsCounter = new FpsCountToConsole("GameScreenRender");
public GameScreenRender(int bORDER_W_H, int charW, int charH, int ascentH) {
BORDER_W_H = bORDER_W_H;
this.charW = charW;
this.charH = charH;
this.ascentH = ascentH;
}
public void render(GameScreen gameScreen, Graphics2D g) {
gameScreen.setDimensionsOfGameMap(32, 17);
//Game map
for (int y = 0; y < 17; y++) {
for (int x = 0; x < 32; x++) {
ScreenCharacter mapCharacter = gameScreen.getGameMapCharacter(x, y);
g.drawString(String.format("%c", mapCharacter.getChar()),
BORDER_W_H + (x * charW),
BORDER_W_H + (y * charH) + ascentH);
}
}
//Info area
//ln1 name, then empty
g.drawString(String.format("%s the %s", "PLAYER", "Publican"),
BORDER_W_H + (33 * charW),
BORDER_W_H + (0 * charH) + ascentH);
int maxHealth = gameScreen.getCharacterStats().getMaxHealth();
int health = gameScreen.getCharacterStats().getHealth();
int maxHealthBars = 35;
int numOfHealthBars = (int) (((double)health / (double)maxHealth) * maxHealthBars);
char[] chHealthBars = new char[maxHealthBars];
for (int i = 0; i < maxHealthBars; i++) {
if (i < numOfHealthBars) {
chHealthBars[i] = '=';
} else {
chHealthBars[i] = '.';
}
}
String healthBars = new String(chHealthBars);
g.drawString(String.format("HP %3d/%3d %s", health, maxHealth, healthBars),
BORDER_W_H + (33 * charW),
BORDER_W_H + (2 * charH) + ascentH);
int armor = gameScreen.getCharacterStats().getArmor();
int res = gameScreen.getCharacterStats().getResistance();
g.drawString(String.format("Armor %3d", armor),
BORDER_W_H + (33 * charW),
BORDER_W_H + (3 * charH) + ascentH);
g.drawString(String.format("Resistance %3d", res),
BORDER_W_H + (57 * charW),
BORDER_W_H + (3 * charH) + ascentH);
int mel = gameScreen.getCharacterStats().getMeleeAttack();
int rng = gameScreen.getCharacterStats().getRangedAttack();
g.drawString(String.format("Melee %3d", mel),
BORDER_W_H + (33 * charW),
BORDER_W_H + (4 * charH) + ascentH);
g.drawString(String.format("Ranged %3d", rng),
BORDER_W_H + (57 * charW),
BORDER_W_H + (4 * charH) + ascentH);
StringBuilder statLineBldr = new StringBuilder();
int statLineLength = 0;
int maxStatLineLength = 43;
for (String ef : gameScreen.getCharacterStats().getEffects()) {
if ((statLineLength + ef.length()) > maxStatLineLength) {
statLineBldr.append("..."); //indicate that there are more
break;
}
statLineLength += ef.length() + 1; //add a space behind
statLineBldr.append(ef);
statLineBldr.append(' ');
}
g.drawString(statLineBldr.toString(),
BORDER_W_H + (33 * charW),
BORDER_W_H + (6 * charH) + ascentH);
// Space for 9 enemies
int enemyLineLen = 43;
List<String> enemies = gameScreen.getCharacterStats().getEnemies(9, enemyLineLen);
int numEnemiesToRender = enemies.size() > 9 ? 9 : enemies.size();
int numCurrentEnemy = 0;
for (String enemy : enemies) {
if (numCurrentEnemy >= numEnemiesToRender) {
break;
}
String enemyLine;
if (enemy.length() > enemyLineLen) {
enemyLine = enemy.substring(0, enemyLineLen - 1) + "...";
} else {
enemyLine = enemy;
}
g.drawString(enemyLine,
BORDER_W_H + (33 * charW),
BORDER_W_H + ((8 + numCurrentEnemy) * charH) + ascentH);
numCurrentEnemy++;
}
//Message area
List<ScreenMessage> messages = gameScreen.getMessages(7, 79);
int numMsg = 0;
for (ScreenMessage message : messages) {
//maximum of 7 message, can be less
int y = ((18 + numMsg) * charH) + ascentH;
g.drawString(message.getText(), BORDER_W_H, BORDER_W_H + y);
numMsg++;
}
//fpsCounter.countFps();
}
}
| bsd-2-clause |