repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
ZubovVP/ZubovVP | chapter_010/src/main/java/ru/job4j/supermarket/strorage/Trash.java | 819 | package ru.job4j.supermarket.strorage;
import ru.job4j.supermarket.foods.Food;
import java.time.LocalDate;
import java.util.List;
/**
* Created by Intellij IDEA.
* User: Vitaly Zubov.
* Email: Zubov.VP@yandex.ru.
* Version: $Id$.
* Date: 22.11.2019.
*/
public class Trash extends AbstractStorage {
public Trash() {
}
public Trash(List<Food> foods) {
super(foods);
}
/**
* Check food.
* If expiry date < now, that true.
* If expiry date > now, that false.
*
* @param food - food.
* @return - result.
*/
@Override
public boolean accept(Food food) {
boolean result = false;
if (food.getExpiryDate().isBefore(LocalDate.now())) {
this.add(food);
result = true;
}
return result;
}
}
| apache-2.0 |
Claudenw/junit-contracts | junit/src/main/java/org/xenei/junit/contract/info/DynamicSuiteInfo.java | 2314 | /*
* 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.xenei.junit.contract.info;
import java.lang.reflect.Method;
import org.xenei.junit.contract.Contract;
import org.xenei.junit.contract.ContractImpl;
import org.xenei.junit.contract.Dynamic;
import org.xenei.junit.contract.MethodUtils;
/**
* Handles dynamic suites.
*
* When executing a dynamic suite the dynamic.inject method should be called to
* retrieve the instance to inject then the Contract.inject should be called to
* inject it into the test.
*
*/
public class DynamicSuiteInfo extends SuiteInfo {
private final Method dynamicInjector;
/**
* Constructor
*
* @param dynamic
* The class under test.
* @param impl
* The ContractImpl annotation for the class
*/
public DynamicSuiteInfo(final Class<? extends Dynamic> dynamic, final ContractImpl impl) {
super( dynamic, impl, MethodUtils.findAnnotatedGetter( impl.value(), Contract.Inject.class ) );
dynamicInjector = MethodUtils.findAnnotatedGetter( dynamic, Dynamic.Inject.class );
if (getMethod() == null) {
addError( new IllegalArgumentException( "Classes that extends Dynamic [" + dynamic
+ "] must contain a getter method annotated with @Dynamic.Inject" ) );
}
}
/**
* Get the method that returns the Dynamic IProducer.
*
* @return the method that returns the Dynamic IProducer.
*/
public Method getDynamicInjector() {
return dynamicInjector;
}
} | apache-2.0 |
piotrporzucek/vocab | src/main/java/pl/egalit/vocab/client/courseDetails/NewWordsView.java | 514 | package pl.egalit.vocab.client.courseDetails;
import pl.egalit.vocab.client.core.mvp.VocabView;
import pl.egalit.vocab.client.courseDetails.CourseDetailsView.Presenter;
import pl.egalit.vocab.client.requestfactory.WordProxy;
public interface NewWordsView extends VocabView, TabChangedListener {
void hideForm();
void showConfirmation();
void showError(ErrorCode errorCode);
void markWithError(WordProxy rootBean, String message);
void setPresenter(Presenter presenter);
void hide();
void show();
}
| apache-2.0 |
grusso14/eprot | src/it/finsiel/siged/mvc/presentation/action/amministrazione/firmadigitale/ListaCAAction.java | 2749 | package it.finsiel.siged.mvc.presentation.action.amministrazione.firmadigitale;
import it.finsiel.siged.exception.DataException;
import it.finsiel.siged.mvc.business.FirmaDigitaleDelegate;
import it.finsiel.siged.mvc.presentation.actionform.amministrazione.firmadigitale.ListaCAForm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
/**
* Implementation of <strong>Action </strong> to create a new E-Photo Utente.
*
* @author Almaviva sud.
*
*/
public class ListaCAAction extends Action {
// ----------------------------------------------------- Instance Variables
/**
* The <code>Log</code> instance for this application.
*/
static Logger logger = Logger.getLogger(ListaCAAction.class.getName());
// --------------------------------------------------------- Public Methods
/**
* Process the specified HTTP request, and create the corresponding HTTP
* response (or forward to another web component that will create it).
* Return an <code>ActionForward</code> instance describing where and how
* control should be forwarded, or <code>null</code> if the response has
* already been completed.
*
* @param mapping
* The ActionMapping used to select this instance
* @param form
* The optional ActionForm bean for this request (if any)
* @param request
* The HTTP request we are processing
* @param response
* The HTTP response we are creating
*
* @exception Exception
* if business logic throws an exception
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages errors = new ActionMessages();
ListaCAForm caForm = (ListaCAForm) form;
if (form == null) {
caForm = new ListaCAForm();
request.setAttribute(mapping.getAttribute(), caForm);
}
try {
caForm.setListaCa(FirmaDigitaleDelegate.getInstance().getAllCA());
} catch (DataException e) {
errors.add("generale", new ActionMessage("database.cannot.load"));
}
request.setAttribute(mapping.getAttribute(), caForm);
saveErrors(request, errors);
return (mapping.findForward("input"));
}
}
| apache-2.0 |
aws/aws-sdk-java-v2 | codegen/src/main/java/software/amazon/awssdk/codegen/poet/model/ResponseMetadataSpec.java | 5616 | /*
* Copyright 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 software.amazon.awssdk.codegen.poet.model;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.lang.model.element.Modifier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.awscore.AwsResponseMetadata;
import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel;
import software.amazon.awssdk.codegen.poet.ClassSpec;
import software.amazon.awssdk.codegen.poet.PoetExtensions;
import software.amazon.awssdk.codegen.poet.PoetUtils;
import software.amazon.awssdk.utils.CollectionUtils;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.internal.CodegenNamingUtils;
/**
* Generate ResponseMetadata class
*/
public class ResponseMetadataSpec implements ClassSpec {
private PoetExtensions poetExtensions;
private Map<String, String> headerMetadata = new HashMap<>();
public ResponseMetadataSpec(IntermediateModel model) {
if (!CollectionUtils.isNullOrEmpty(model.getCustomizationConfig().getCustomResponseMetadata())) {
this.headerMetadata.putAll(model.getCustomizationConfig().getCustomResponseMetadata());
}
this.poetExtensions = new PoetExtensions(model);
}
@Override
public TypeSpec poetSpec() {
TypeSpec.Builder specBuilder = TypeSpec.classBuilder(className())
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(PoetUtils.generatedAnnotation())
.addAnnotation(SdkPublicApi.class)
.superclass(AwsResponseMetadata.class)
.addMethod(constructor())
.addMethod(staticFactoryMethod())
.addMethods(metadataMethods());
List<FieldSpec> fields = headerMetadata.entrySet().stream().map(e ->
FieldSpec.builder(String.class, e.getKey())
.addModifiers(Modifier.PRIVATE, Modifier.STATIC,
Modifier.FINAL)
.initializer("$S", e.getValue())
.build()
).collect(Collectors.toList());
specBuilder.addFields(fields);
return specBuilder.build();
}
private MethodSpec constructor() {
return MethodSpec.constructorBuilder()
.addModifiers(Modifier.PRIVATE)
.addParameter(AwsResponseMetadata.class, "responseMetadata")
.addStatement("super(responseMetadata)")
.build();
}
private MethodSpec staticFactoryMethod() {
return MethodSpec.methodBuilder("create")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameter(AwsResponseMetadata.class, "responseMetadata")
.addStatement("return new $T(responseMetadata)", className())
.returns(className())
.build();
}
private List<MethodSpec> metadataMethods() {
return headerMetadata.keySet()
.stream()
.map(key -> {
String methodName = convertMethodName(key);
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName)
.addModifiers(Modifier.PUBLIC)
.addStatement("return getValue($L)", key)
.returns(String.class);
if (methodName.equals("requestId")) {
methodBuilder.addAnnotation(Override.class);
}
return methodBuilder.build();
}).collect(Collectors.toList());
}
/**
* Convert key (UPPER_CASE) to method name.
*/
private String convertMethodName(String key) {
String pascalCase = CodegenNamingUtils.pascalCase(key);
return StringUtils.uncapitalize(pascalCase);
}
@Override
public ClassName className() {
return poetExtensions.getResponseMetadataClass();
}
}
| apache-2.0 |
WANdisco/gerrit | java/com/google/gerrit/acceptance/testsuite/account/AccountOperationsImpl.java | 6672 | // Copyright (C) 2018 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.gerrit.acceptance.testsuite.account;
import static com.google.common.base.Preconditions.checkState;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.Sequences;
import com.google.gerrit.server.ServerInitiated;
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.account.Accounts;
import com.google.gerrit.server.account.AccountsUpdate;
import com.google.gerrit.server.account.InternalAccountUpdate;
import com.google.gerrit.server.account.externalids.ExternalId;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import java.io.IOException;
import java.util.Optional;
import org.eclipse.jgit.errors.ConfigInvalidException;
/**
* The implementation of {@code AccountOperations}.
*
* <p>There is only one implementation of {@code AccountOperations}. Nevertheless, we keep the
* separation between interface and implementation to enhance clarity.
*/
public class AccountOperationsImpl implements AccountOperations {
private final Accounts accounts;
private final AccountsUpdate accountsUpdate;
private final Sequences seq;
@Inject
public AccountOperationsImpl(
Accounts accounts, @ServerInitiated AccountsUpdate accountsUpdate, Sequences seq) {
this.accounts = accounts;
this.accountsUpdate = accountsUpdate;
this.seq = seq;
}
@Override
public MoreAccountOperations account(Account.Id accountId) {
return new MoreAccountOperationsImpl(accountId);
}
@Override
public TestAccountCreation.Builder newAccount() {
return TestAccountCreation.builder(this::createAccount);
}
private Account.Id createAccount(TestAccountCreation accountCreation) throws Exception {
AccountsUpdate.AccountUpdater accountUpdater =
(account, updateBuilder) ->
fillBuilder(updateBuilder, accountCreation, account.getAccount().getId());
AccountState createdAccount = createAccount(accountUpdater);
return createdAccount.getAccount().getId();
}
private AccountState createAccount(AccountsUpdate.AccountUpdater accountUpdater)
throws OrmException, IOException, ConfigInvalidException {
Account.Id accountId = new Account.Id(seq.nextAccountId());
return accountsUpdate.insert("Create Test Account", accountId, accountUpdater);
}
private static void fillBuilder(
InternalAccountUpdate.Builder builder,
TestAccountCreation accountCreation,
Account.Id accountId) {
accountCreation.fullname().ifPresent(builder::setFullName);
accountCreation.preferredEmail().ifPresent(e -> setPreferredEmail(builder, accountId, e));
String httpPassword = accountCreation.httpPassword().orElse(null);
accountCreation.username().ifPresent(u -> setUsername(builder, accountId, u, httpPassword));
accountCreation.status().ifPresent(builder::setStatus);
accountCreation.active().ifPresent(builder::setActive);
}
private static InternalAccountUpdate.Builder setPreferredEmail(
InternalAccountUpdate.Builder builder, Account.Id accountId, String preferredEmail) {
return builder
.setPreferredEmail(preferredEmail)
.addExternalId(ExternalId.createEmail(accountId, preferredEmail));
}
private static InternalAccountUpdate.Builder setUsername(
InternalAccountUpdate.Builder builder,
Account.Id accountId,
String username,
String httpPassword) {
return builder.addExternalId(ExternalId.createUsername(username, accountId, httpPassword));
}
private class MoreAccountOperationsImpl implements MoreAccountOperations {
private final Account.Id accountId;
MoreAccountOperationsImpl(Account.Id accountId) {
this.accountId = accountId;
}
@Override
public boolean exists() throws Exception {
return accounts.get(accountId).isPresent();
}
@Override
public TestAccount get() throws Exception {
AccountState account =
accounts
.get(accountId)
.orElseThrow(
() -> new IllegalStateException("Tried to get non-existing test account"));
return toTestAccount(account);
}
private TestAccount toTestAccount(AccountState accountState) {
Account account = accountState.getAccount();
return TestAccount.builder()
.accountId(account.getId())
.preferredEmail(Optional.ofNullable(account.getPreferredEmail()))
.fullname(Optional.ofNullable(account.getFullName()))
.username(accountState.getUserName())
.active(accountState.getAccount().isActive())
.build();
}
@Override
public TestAccountUpdate.Builder forUpdate() {
return TestAccountUpdate.builder(this::updateAccount);
}
private void updateAccount(TestAccountUpdate accountUpdate)
throws OrmException, IOException, ConfigInvalidException {
AccountsUpdate.AccountUpdater accountUpdater =
(account, updateBuilder) -> fillBuilder(updateBuilder, accountUpdate, accountId);
Optional<AccountState> updatedAccount = updateAccount(accountUpdater);
checkState(updatedAccount.isPresent(), "Tried to update non-existing test account");
}
private Optional<AccountState> updateAccount(AccountsUpdate.AccountUpdater accountUpdater)
throws OrmException, IOException, ConfigInvalidException {
return accountsUpdate.update("Update Test Account", accountId, accountUpdater);
}
private void fillBuilder(
InternalAccountUpdate.Builder builder,
TestAccountUpdate accountUpdate,
Account.Id accountId) {
accountUpdate.fullname().ifPresent(builder::setFullName);
accountUpdate.preferredEmail().ifPresent(e -> setPreferredEmail(builder, accountId, e));
String httpPassword = accountUpdate.httpPassword().orElse(null);
accountUpdate.username().ifPresent(u -> setUsername(builder, accountId, u, httpPassword));
accountUpdate.status().ifPresent(builder::setStatus);
accountUpdate.active().ifPresent(builder::setActive);
}
}
}
| apache-2.0 |
ChenAt/common-dao | src/test/java/top/chenat/bean/Test2.java | 142 | package top.chenat.bean;
import javax.persistence.Entity;
/**
* Created by ChenAt on 10/17/17.
* desc:
*/
@Entity
public class Test2 {
}
| apache-2.0 |
SoftwareKing/zstack | plugin/virtualRouterProvider/src/main/java/org/zstack/network/service/virtualrouter/APIQueryVirtualRouterVmMsg.java | 337 | package org.zstack.network.service.virtualrouter;
import org.zstack.header.query.APIQueryMessage;
import org.zstack.header.query.AutoQuery;
/**
*/
@AutoQuery(replyClass = APIQueryVirtualRouterVmReply.class, inventoryClass = VirtualRouterVmInventory.class)
public class APIQueryVirtualRouterVmMsg extends APIQueryMessage {
}
| apache-2.0 |
RoundSparrow/Uoccin | app/src/main/java/net/ggelardi/uoccin/SettingsFragment.java | 5266 | package net.ggelardi.uoccin;
import net.ggelardi.uoccin.comp.IntListPreference;
import net.ggelardi.uoccin.serv.Commons.PK;
import net.ggelardi.uoccin.serv.Session;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Intent;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
import android.text.TextUtils;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.common.AccountPicker;
import com.google.api.client.googleapis.extensions.android.accounts.GoogleAccountManager;
public class SettingsFragment extends PreferenceFragment {
private static final String[] ACCOUNT_TYPE = new String[] { GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE };
private static final int CHOOSE_ACCOUNT = 0;
private Session session;
private GoogleAccountManager gaccman;
private Preference cpdauth;
private ListPreference lpstart;
private ListPreference lplocal;
private IntListPreference lpsyint;
private EditTextPreference epduuid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
session = Session.getInstance(getActivity());
gaccman = new GoogleAccountManager(getActivity());
cpdauth = findPreference(PK.GDRVAUTH);
cpdauth.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Intent intent = AccountPicker.newChooseAccountIntent(getPreferenceAccount(), null, ACCOUNT_TYPE,
false, null, null, null, null);
startActivityForResult(intent, CHOOSE_ACCOUNT);
return true;
}
});
lpstart = (ListPreference) findPreference(PK.STARTUPV);
lpstart.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(getStartupDescr(newValue.toString()));
return true;
}
});
lplocal = (ListPreference) findPreference(PK.LANGUAGE);
lplocal.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(getLanguageDescr(newValue.toString()));
return true;
}
});
lpsyint = (IntListPreference) findPreference(PK.GDRVINTV);
lpsyint.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(getIntervalDescr(newValue.toString()));
return true;
}
});
epduuid = (EditTextPreference) findPreference(PK.GDRVUUID);
epduuid.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setSummary(newValue.toString());
return true;
}
});
}
@Override
public void onResume() {
super.onResume();
lpstart.setSummary(getStartupDescr(null));
lplocal.setSummary(getLanguageDescr(null));
lpsyint.setSummary(getIntervalDescr(null));
epduuid.setSummary(session.driveDeviceID());
Account preferenceAccount = getPreferenceAccount();
if (preferenceAccount != null)
cpdauth.setSummary(preferenceAccount.name);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CHOOSE_ACCOUNT && data != null) {
Account accsel = gaccman.getAccountByName(data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME));
if (accsel != null) {
session.setDriveUserAccount(accsel.name);
cpdauth.setSummary(accsel.name);
}
}
}
private String getStartupDescr(String id) {
if (TextUtils.isEmpty(id))
id = session.getPrefs().getString(PK.STARTUPV, "sernext");
String[] keys = session.getRes().getStringArray(R.array.view_defser_ids);
String[] vals = session.getRes().getStringArray(R.array.view_defser_titles);
for (int i = 0; i < keys.length; i++)
if (keys[i].equals(id))
return vals[i];
return "";
}
private String getLanguageDescr(String id) {
if (TextUtils.isEmpty(id))
id = session.getPrefs().getString(PK.LANGUAGE, "en");
String[] keys = session.getRes().getStringArray(R.array.pk_language_values);
String[] vals = session.getRes().getStringArray(R.array.pk_language_names);
for (int i = 0; i < keys.length; i++)
if (keys[i].equals(id))
return vals[i];
return "";
}
private String getIntervalDescr(String id) {
if (TextUtils.isEmpty(id))
id = Integer.toString(session.getPrefs().getInt(PK.GDRVINTV, 30));
String[] keys = session.getRes().getStringArray(R.array.pk_gdrvintv_values);
String[] vals = session.getRes().getStringArray(R.array.pk_gdrvintv_names);
for (int i = 0; i < keys.length; i++)
if (keys[i].equals(id))
return vals[i];
return "";
}
private Account getPreferenceAccount() {
return gaccman.getAccountByName(session.driveAccountName());
}
} | apache-2.0 |
Wessbas/wessbas.behaviorModelExtractor | src-gen/net/sf/markov4jmeter/behavior/impl/BehaviorModelRelativeImpl.java | 1594 | /***************************************************************************
* Copyright (c) 2016 the WESSBAS project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package net.sf.markov4jmeter.behavior.impl;
import net.sf.markov4jmeter.behavior.BehaviorModelRelative;
import net.sf.markov4jmeter.behavior.BehaviorPackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Model Relative</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class BehaviorModelRelativeImpl extends AbstractBehaviorModelGraphImpl implements BehaviorModelRelative {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BehaviorModelRelativeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return BehaviorPackage.Literals.BEHAVIOR_MODEL_RELATIVE;
}
} //BehaviorModelRelativeImpl
| apache-2.0 |
NessComputing/components-ness-jackson | src/main/java/com/nesscomputing/jackson/datatype/CustomUuidSerializer.java | 1355 | /**
* Copyright (C) 2012 Ness Computing, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nesscomputing.jackson.datatype;
import java.io.IOException;
import java.util.UUID;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import com.google.inject.Inject;
import com.nesscomputing.uuid.NessUUID;
class CustomUuidSerializer extends StdSerializer<UUID>
{
@Inject
CustomUuidSerializer()
{
super(UUID.class);
}
@Override
public void serialize(UUID value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonGenerationException
{
jgen.writeString(NessUUID.toString(value));
}
}
| apache-2.0 |
lmjacksoniii/hazelcast | hazelcast/src/test/java/com/hazelcast/nio/tcp/TcpIpConnection_BaseTest.java | 7317 | package com.hazelcast.nio.tcp;
import com.hazelcast.nio.Packet;
import com.hazelcast.spi.impl.PacketHandler;
import com.hazelcast.test.AssertTask;
import org.junit.Before;
import org.junit.Test;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static java.lang.System.currentTimeMillis;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public abstract class TcpIpConnection_BaseTest extends TcpIpConnection_AbstractTest {
// sleep time for lastWrite and lastRead tests
private static final int LAST_READ_WRITE_SLEEP_SECONDS = 5;
// if we make this MARGIN_OF_ERROR_MS very small, there is a high chance of spurious failures
private static final int MARGIN_OF_ERROR_MS = 3000;
private List<Packet> packetsB;
@Before
public void setup() throws Exception {
super.setup();
packetsB = Collections.synchronizedList(new ArrayList<Packet>());
startAllConnectionManagers();
ioServiceB.packetHandler = new PacketHandler() {
@Override
public void handle(Packet packet) throws Exception {
packetsB.add(packet);
}
};
}
@Test
public void write_whenNonUrgent() {
TcpIpConnection c = connect(connManagerA, addressB);
Packet packet = new Packet(serializationService.toBytes("foo"));
boolean result = c.write(packet);
assertTrue(result);
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(1, packetsB.size());
}
});
Packet found = packetsB.get(0);
assertEquals(packet, found);
}
@Test
public void write_whenUrgent() {
TcpIpConnection c = connect(connManagerA, addressB);
Packet packet = new Packet(serializationService.toBytes("foo"));
packet.raiseFlags(Packet.FLAG_URGENT);
boolean result = c.write(packet);
assertTrue(result);
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(1, packetsB.size());
}
});
Packet found = packetsB.get(0);
assertEquals(packet, found);
}
@Test
public void lastWriteTimeMillis_whenPacketWritten() {
TcpIpConnection connAB = connect(connManagerA, addressB);
// we need to sleep some so that the lastWriteTime of the connection gets nice and old.
// we need this so we can determine the lastWriteTime got updated
sleepSeconds(LAST_READ_WRITE_SLEEP_SECONDS);
Packet packet = new Packet(serializationService.toBytes("foo"));
connAB.write(packet);
// wait for the packet to get written.
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(1, packetsB.size());
}
});
long lastWriteTimeMs = connAB.lastWriteTimeMillis();
long nowMs = currentTimeMillis();
// make sure that the lastWrite time is within the given MARGIN_OF_ERROR_MS
// last write time should be equal or smaller than now
assertTrue("nowMs = " + nowMs + ", lastWriteTimeMs = " + lastWriteTimeMs, lastWriteTimeMs <= nowMs);
// last write time should be larger or equal than the now - MARGIN_OF_ERROR_MS
assertTrue("nowMs = " + nowMs + ", lastWriteTimeMs = " + lastWriteTimeMs,
lastWriteTimeMs >= nowMs - MARGIN_OF_ERROR_MS);
}
@Test
public void lastWriteTime_whenNothingWritten() {
TcpIpConnection c = connect(connManagerA, addressB);
long result1 = c.lastWriteTimeMillis();
long result2 = c.lastWriteTimeMillis();
assertEquals(result1, result2);
}
// we check the lastReadTimeMillis by sending a packet on the local connection, and
// on the remote side we check the if the lastReadTime is updated
@Test
public void lastReadTimeMillis() {
TcpIpConnection connAB = connect(connManagerA, addressB);
TcpIpConnection connBA = connect(connManagerB, addressA);
// we need to sleep some so that the lastReadTime of the connection gets nice and old.
// we need this so we can determine the lastReadTime got updated
sleepSeconds(LAST_READ_WRITE_SLEEP_SECONDS);
Packet packet = new Packet(serializationService.toBytes("foo"));
connAB.write(packet);
// wait for the packet to get read.
assertTrueEventually(new AssertTask() {
@Override
public void run() throws Exception {
assertEquals(1, packetsB.size());
System.out.println("Packet processed");
}
});
long lastReadTimeMs = connBA.lastReadTimeMillis();
long nowMs = currentTimeMillis();
// make sure that the lastRead time is within the given MARGIN_OF_ERROR_MS
// last read time should be equal or smaller than now
assertTrue("nowMs = " + nowMs + ", lastReadTimeMs = " + lastReadTimeMs, lastReadTimeMs <= nowMs);
// last read time should be larger or equal than the now - MARGIN_OF_ERROR_MS
assertTrue("nowMs = " + nowMs + ", lastReadTimeMs = " + lastReadTimeMs, lastReadTimeMs >= nowMs - MARGIN_OF_ERROR_MS);
}
@Test
public void lastReadTime_whenNothingWritten() {
TcpIpConnection c = connect(connManagerA, addressB);
long result1 = c.lastReadTimeMillis();
long result2 = c.lastReadTimeMillis();
assertEquals(result1, result2);
}
@Test
public void write_whenNotAlive() {
TcpIpConnection c = connect(connManagerA, addressB);
c.close(null, null);
Packet packet = new Packet(serializationService.toBytes("foo"));
boolean result = c.write(packet);
assertFalse(result);
}
@Test
public void getInetAddress() {
TcpIpConnection c = connect(connManagerA, addressB);
InetAddress result = c.getInetAddress();
assertEquals(c.getSocketChannel().socket().getInetAddress(), result);
}
@Test
public void getRemoteSocketAddress() {
TcpIpConnection c = connect(connManagerA, addressB);
InetSocketAddress result = c.getRemoteSocketAddress();
assertEquals(new InetSocketAddress(addressB.getHost(), addressB.getPort()), result);
}
@Test
public void getPort() {
TcpIpConnection c = connect(connManagerA, addressB);
int result = c.getPort();
assertEquals(c.getSocketChannel().socket().getPort(), result);
}
@Test
public void test_equals() {
TcpIpConnection connAB = connect(connManagerA, addressB);
TcpIpConnection connAC = connect(connManagerA, addressC);
assertEquals(connAB, connAB);
assertEquals(connAC, connAC);
assertNotEquals(connAB, null);
assertNotEquals(connAB, connAC);
assertNotEquals(connAC, connAB);
assertNotEquals(connAB, "foo");
}
}
| apache-2.0 |
wso2-extensions/identity-governance | components/org.wso2.carbon.identity.captcha/src/main/java/org/wso2/carbon/identity/captcha/filter/CaptchaFilter.java | 8907 | /*
* Copyright (c) 2016, 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.carbon.identity.captcha.filter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.captcha.connector.CaptchaConnector;
import org.wso2.carbon.identity.captcha.connector.CaptchaPostValidationResponse;
import org.wso2.carbon.identity.captcha.connector.CaptchaPreValidationResponse;
import org.wso2.carbon.identity.captcha.exception.CaptchaClientException;
import org.wso2.carbon.identity.captcha.exception.CaptchaException;
import org.wso2.carbon.identity.captcha.internal.CaptchaDataHolder;
import org.wso2.carbon.identity.captcha.util.CaptchaHttpServletRequestWrapper;
import org.wso2.carbon.identity.captcha.util.CaptchaHttpServletResponseWrapper;
import org.wso2.carbon.identity.captcha.util.CaptchaUtil;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Captcha filter.
*/
public class CaptchaFilter implements Filter {
private static final Log log = LogFactory.getLog(CaptchaFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
if (log.isDebugEnabled()) {
log.debug("Captcha filter activated.");
}
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
try {
if (!CaptchaDataHolder.getInstance().isReCaptchaEnabled()) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
// Wrap Servlet request for password recovery flow as the data are in POST body of request.
// May need multiple reads of request body value from connectors.
if (servletRequest instanceof HttpServletRequest) {
String currentPath = ((HttpServletRequest) servletRequest).getRequestURI();
if (StringUtils.isNotBlank(currentPath) &&
CaptchaUtil.isPathAvailable(currentPath, CaptchaDataHolder.getInstance()
.getReCaptchaRequestWrapUrls())) {
servletRequest = new CaptchaHttpServletRequestWrapper((HttpServletRequest) servletRequest);
}
}
List<CaptchaConnector> captchaConnectors = CaptchaDataHolder.getInstance().getCaptchaConnectors();
CaptchaConnector selectedCaptchaConnector = null;
for (CaptchaConnector captchaConnector : captchaConnectors) {
if (captchaConnector.canHandle(servletRequest, servletResponse) && (selectedCaptchaConnector == null ||
captchaConnector.getPriority() > selectedCaptchaConnector.getPriority())) {
selectedCaptchaConnector = captchaConnector;
}
}
if (selectedCaptchaConnector == null) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
// Check whether captcha is required or will reach to the max failed attempts with the current attempt.
CaptchaPreValidationResponse captchaPreValidationResponse = selectedCaptchaConnector
.preValidate(servletRequest, servletResponse);
if (captchaPreValidationResponse == null) {
// Captcha connector failed to response. Default is success.
filterChain.doFilter(servletRequest, servletResponse);
return;
}
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
if (captchaPreValidationResponse.isCaptchaValidationRequired()) {
try {
boolean validCaptcha = selectedCaptchaConnector.verifyCaptcha(servletRequest, servletResponse);
if (!validCaptcha) {
log.warn("Captcha validation failed for the user.");
httpResponse.sendRedirect(CaptchaUtil.getOnFailRedirectUrl(httpRequest.getHeader("referer"),
captchaPreValidationResponse.getOnCaptchaFailRedirectUrls(),
captchaPreValidationResponse.getCaptchaAttributes()));
return;
}
} catch (CaptchaClientException e) {
log.warn("Captcha validation failed for the user. Cause : " + e.getMessage());
httpResponse.sendRedirect(CaptchaUtil.getOnFailRedirectUrl(httpRequest.getHeader("referer"),
captchaPreValidationResponse.getOnCaptchaFailRedirectUrls(),
captchaPreValidationResponse.getCaptchaAttributes()));
return;
}
}
// Enable reCaptcha for the destination.
if (captchaPreValidationResponse.isEnableCaptchaForRequestPath()) {
if (captchaPreValidationResponse.getCaptchaAttributes() != null) {
for (Map.Entry<String, String> parameter : captchaPreValidationResponse.getCaptchaAttributes()
.entrySet()) {
servletRequest.setAttribute(parameter.getKey(), parameter.getValue());
}
}
doFilter(captchaPreValidationResponse, servletRequest, servletResponse, filterChain);
return;
}
// Below the no. of max failed attempts, including the current attempt
if (!captchaPreValidationResponse.isPostValidationRequired() || (!captchaPreValidationResponse
.isCaptchaValidationRequired() && !captchaPreValidationResponse.isMaxFailedLimitReached())) {
doFilter(captchaPreValidationResponse, servletRequest, servletResponse, filterChain);
return;
}
CaptchaHttpServletResponseWrapper responseWrapper = new CaptchaHttpServletResponseWrapper(httpResponse);
doFilter(captchaPreValidationResponse, servletRequest, responseWrapper, filterChain);
CaptchaPostValidationResponse postValidationResponse = selectedCaptchaConnector
.postValidate(servletRequest, responseWrapper);
// Check whether this attempt is failed
if (postValidationResponse == null || postValidationResponse.isSuccessfulAttempt()) {
if (responseWrapper.isRedirect()) {
httpResponse.sendRedirect(responseWrapper.getRedirectURL());
}
return;
}
if (postValidationResponse.isEnableCaptchaResponsePath() && responseWrapper.isRedirect()) {
httpResponse.sendRedirect(CaptchaUtil.getUpdatedUrl(responseWrapper.getRedirectURL(),
postValidationResponse.getCaptchaAttributes()));
}
} catch (CaptchaException e) {
log.error("Error occurred in processing captcha.", e);
((HttpServletResponse) servletResponse).sendRedirect(CaptchaUtil.getErrorPage("Server Error", "Something " +
"went wrong. Please try again"));
}
}
@Override
public void destroy() {
}
private void doFilter(CaptchaPreValidationResponse preValidationResponse, ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
if(preValidationResponse.getWrappedHttpServletRequest() != null) {
filterChain.doFilter(preValidationResponse.getWrappedHttpServletRequest(), servletResponse);
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
}
| apache-2.0 |
gsh199449/DistributedCrawler | src/main/java/com/gs/Classifier/TrainingDataManager.java | 4595 | package com.gs.Classifier;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;
/**
* ѵÁ·¼¯¹ÜÀíÆ÷
*/
public class TrainingDataManager
{
private String[] traningFileClassifications;//ѵÁ·ÓïÁÏ·ÖÀ༯ºÏ
private File traningTextDir;//ѵÁ·ÓïÁÏ´æ·ÅĿ¼
//private static String defaultPath = "D:\\Lucene\\docs\\ѵÁ··ÖÀàÓÃÎı¾\\";
//private static String defaultPath = "D:\\Lucene\\ClassFile\\";
//private static String defaultPath = "D:\\Lucene\\·ÖÀàѵÁ·Óë²âÊÔÓïÁÏ¿â\\DRAPÌṩµÄ²âÊÔѵÁ·ÓïÁÏ\\TanCorpMinTrain\\";
//private static String defaultPath = "D:\\Lucene\\·ÖÀàѵÁ·Óë²âÊÔÓïÁÏ¿â\\¸´µ©ÀîÈÙ½ÌṩµÄÓïÁÏ¿â\\";
private static String defaultPath = "D:\\Lucene\\Corpus\\";
//private static String defaultPath = "/opt/Test/Corpus";
//private static String defaultPath = "D:\\Lucene\\·ÖÀàѵÁ·Óë²âÊÔÓïÁÏ¿â\\DRAPÌṩµÄ²âÊÔѵÁ·ÓïÁÏ\\Corpus\\";
private Map<String,Map<String,Double>> classMap = new HashMap<String,Map<String,Double>>();
private static TrainingDataManager ini = new TrainingDataManager();
@SuppressWarnings("unchecked")
private TrainingDataManager()
{
traningTextDir = new File(defaultPath);
if (!traningTextDir.isDirectory())
{
throw new IllegalArgumentException("ѵÁ·ÓïÁÏ¿âËÑË÷ʧ°Ü£¡ [" +defaultPath + "]");
}
this.traningFileClassifications = traningTextDir.list();
//¼ÓÔØËùÓÐMap
String ss[] = traningTextDir.list();
for(int i= 0;i<ss.length;i++){
Map<String, Double> map = new HashMap<String, Double>();
ObjectInputStream ois = null;
try {
FileInputStream is = new FileInputStream(defaultPath+ss[i]+"\\map");
ois = new ObjectInputStream(is);
map = (Map<String, Double>) ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
classMap.put(ss[i], map);
map = null;
}
}
public static TrainingDataManager getInstance(){
return ini;
}
/**
* ·µ»ØÑµÁ·Îı¾Àà±ð£¬Õâ¸öÀà±ð¾ÍÊÇĿ¼Ãû
* @return ѵÁ·Îı¾Àà±ð
*/
public String[] getTraningClassifications()
{
return this.traningFileClassifications;
}
/**
* ¸ù¾ÝѵÁ·Îı¾Àà±ð·µ»ØÕâ¸öÀà±ðϵÄËùÓÐѵÁ·Îı¾Â·¾¶£¨full path£©
* @param classification ¸ø¶¨µÄ·ÖÀà
* @return ¸ø¶¨·ÖÀàÏÂËùÓÐÎļþµÄ·¾¶£¨full path£©
*/
public String[] getFilesPath(String classification)
{
File classDir = new File(traningTextDir.getPath() +File.separator +classification);
String[] ret = classDir.list();
for (int i = 0; i < ret.length; i++)
{
ret[i] = traningTextDir.getPath() +File.separator +classification +File.separator +ret[i];
}
return ret;
}
/**
* ·µ»Ø¸ø¶¨Â·¾¶µÄÎı¾ÎļþÄÚÈÝ
* @param filePath ¸ø¶¨µÄÎı¾Îļþ·¾¶
* @return Îı¾ÄÚÈÝ
* @throws java.io.FileNotFoundException
* @throws java.io.IOException
*/
public static String getText(String filePath) throws FileNotFoundException,IOException
{
InputStreamReader isReader =new InputStreamReader(new FileInputStream(filePath),"GBK");
BufferedReader reader = new BufferedReader(isReader);
String aline;
StringBuilder sb = new StringBuilder();
while ((aline = reader.readLine()) != null)
{
sb.append(aline + " ");
}
isReader.close();
reader.close();
return sb.toString();
}
/**
* ·µ»ØÑµÁ·Îı¾¼¯ÖÐËùÓеÄÎı¾ÊýÄ¿
* @return ѵÁ·Îı¾¼¯ÖÐËùÓеÄÎı¾ÊýÄ¿
*/
public int getTrainingFileCount()
{
int ret = 0;
for (int i = 0; i < traningFileClassifications.length; i++)
{
ret +=getTrainingFileCountOfClassification(traningFileClassifications[i]);
}
return ret;
}
/**
* ·µ»ØÑµÁ·Îı¾¼¯ÖÐÔÚ¸ø¶¨·ÖÀàϵÄѵÁ·Îı¾ÊýÄ¿
* @param classification ¸ø¶¨µÄ·ÖÀà
* @return ѵÁ·Îı¾¼¯ÖÐÔÚ¸ø¶¨·ÖÀàϵÄѵÁ·Îı¾ÊýÄ¿
*/
public int getTrainingFileCountOfClassification(String classification)
{
File classDir = new File(traningTextDir.getPath() +File.separator +classification);
return classDir.list().length;
}
/**
* ·µ»Ø¸ø¶¨·ÖÀàÖаüº¬¹Ø¼ü×Ö£¯´ÊµÄѵÁ·Îı¾µÄÊýÄ¿
* @param classification ¸ø¶¨µÄ·ÖÀà
* @param key ¸ø¶¨µÄ¹Ø¼ü×Ö£¯´Ê
* @return ¸ø¶¨·ÖÀàÖаüº¬¹Ø¼ü×Ö£¯´ÊµÄѵÁ·Îı¾µÄÊýÄ¿
*/
public int getCountContainKeyOfClassification(String classification,String key)
{
int ret = 0;
ret = (int) (classMap.get(classification).containsKey(key) ? classMap.get(classification).get(key):0);
return ret;
}
} | apache-2.0 |
iritgo/iritgo-aktario | aktario-participant/src/main/java/de/iritgo/aktario/participant/command/AddAttributeToParticipantStateCommand.java | 2082 | /**
* This file is part of the Iritgo/Aktario Framework.
*
* Copyright (C) 2005-2011 Iritgo Technologies.
* Copyright (C) 2003-2005 BueroByte GbR.
*
* Iritgo 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 de.iritgo.aktario.participant.command;
import de.iritgo.aktario.core.Engine;
import de.iritgo.aktario.core.command.Command;
import de.iritgo.aktario.core.logger.Log;
import de.iritgo.aktario.participant.ParticipantManager;
/**
* Add a attribute to the participantstate object.
*
* @version $Id: AddAttributeToParticipantStateCommand.java,v 1.6 2006/09/25 10:34:31 grappendorf Exp $
*/
public class AddAttributeToParticipantStateCommand extends Command
{
/**
* Create a new startup command.
*/
public AddAttributeToParticipantStateCommand()
{
super("AddAttributeToParticipantState");
}
/**
*
*/
public void perform()
{
ParticipantManager participantManager = null;
participantManager = (ParticipantManager) Engine.instance().getManagerRegistry().getManager(
"ParticipantServerManager");
if (participantManager == null)
{
participantManager = (ParticipantManager) Engine.instance().getManagerRegistry().getManager(
"ParticipantClientManager");
}
try
{
participantManager.addAttribute(properties.getProperty("attribute"), properties.get("attributeType"));
}
catch (Exception x)
{
Log.logFatal("system", "AddAttributeToParticipantCommand:perform",
"Class not found Exception, Attribute type unknown: "
+ properties.getProperty("attributeType"));
}
}
}
| apache-2.0 |
Sean-PAN2014/BlueOrange | blueo-commons/src/main/java/org/blueo/csv/Parser.java | 1024 | package org.blueo.csv;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.Assert;
public class Parser {
@SuppressWarnings("unchecked")
public static <T> List<T> propertyParser(Class<T> clazz, String csvFileLoc) throws IOException {
List<T> list = new ArrayList<T>();
List<String> lines = FileUtils.readLines(new File(csvFileLoc));
Assert.notEmpty(lines);
// header
String[] headers = lines.remove(0).split(",");
int headerCount = headers.length;
// content
for (String line : lines) {
String[] values = line.split(",");
// each header/value pair
BeanWrapper instance = new BeanWrapperImpl(clazz);
for (int i = 0; i < headerCount; i++) {
instance.setPropertyValue(headers[i], values[i]);
}
list.add((T) instance.getWrappedInstance());
}
return list;
}
}
| apache-2.0 |
peke87ou/XCeP | XCeP/src/com/irina/xcep/utils/barcode/IntentResultBarcode.java | 2984 | package com.irina.xcep.utils.barcode;
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* <p>Encapsulates the result of a barcode scan invoked through {@link IntentIntegratorBarCode}.</p>
*
* @author Sean Owen
*/
/**
* No se usa actualmente el lector QR por intent
* @author 0010832
*
*/
public final class IntentResultBarcode {
private final String contents;
private final String formatName;
private final byte[] rawBytes;
private final Integer orientation;
private final String errorCorrectionLevel;
IntentResultBarcode() {
this(null, null, null, null, null);
}
IntentResultBarcode(String contents,
String formatName,
byte[] rawBytes,
Integer orientation,
String errorCorrectionLevel) {
this.contents = contents;
this.formatName = formatName;
this.rawBytes = rawBytes;
this.orientation = orientation;
this.errorCorrectionLevel = errorCorrectionLevel;
}
/**
* @return raw content of barcode
*/
public String getContents() {
return contents;
}
/**
* @return name of format, like "QR_CODE", "UPC_A". See {@code BarcodeFormat} for more format names.
*/
public String getFormatName() {
return formatName;
}
/**
* @return raw bytes of the barcode content, if applicable, or null otherwise
*/
public byte[] getRawBytes() {
return rawBytes;
}
/**
* @return rotation of the image, in degrees, which resulted in a successful scan. May be null.
*/
public Integer getOrientation() {
return orientation;
}
/**
* @return name of the error correction level used in the barcode, if applicable
*/
public String getErrorCorrectionLevel() {
return errorCorrectionLevel;
}
@Override
public String toString() {
StringBuilder dialogText = new StringBuilder(100);
dialogText.append("Format: ").append(formatName).append('\n');
dialogText.append("Contents: ").append(contents).append('\n');
int rawBytesLength = rawBytes == null ? 0 : rawBytes.length;
dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n");
dialogText.append("Orientation: ").append(orientation).append('\n');
dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n');
return dialogText.toString();
}
}
| apache-2.0 |
xiaguangme/struts2-src-study | src/org/apache/struts2/dispatcher/StrutsResultSupport.java | 8804 | /*
* $Id: StrutsResultSupport.java 651946 2008-04-27 13:41:38Z apetrelli $
*
* 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.struts2.dispatcher;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.util.TextParseUtil;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
/**
* <!-- START SNIPPET: javadoc -->
*
* A base class for all Struts action execution results.
* The "location" param is the default parameter, meaning the most common usage of this result would be:
* <p/>
* This class provides two common parameters for any subclass:
* <ul>
* <li>location - the location to go to after execution (could be a jsp page or another action).
* It can be parsed as per the rules definied in the
* {@link TextParseUtil#translateVariables(java.lang.String, com.opensymphony.xwork2.util.ValueStack) translateVariables}
* method</li>
* <li>parse - true by default. If set to false, the location param will not be parsed for expressions</li>
* <li>encode - false by default. If set to false, the location param will not be url encoded. This only have effect when parse is true</li>
* </ul>
*
* <b>NOTE:</b>
* The encode param will only have effect when parse is true
*
* <!-- END SNIPPET: javadoc -->
*
* <p/>
*
* <!-- START SNIPPET: example -->
*
* <p/>
* In the struts.xml configuration file, these would be included as:
* <p/>
* <pre>
* <result name="success" type="redirect">
* <param name="<b>location</b>">foo.jsp</param>
* </result></pre>
* <p/>
* or
* <p/>
* <pre>
* <result name="success" type="redirect" >
* <param name="<b>location</b>">foo.jsp?url=${myUrl}</param>
* <param name="<b>parse</b>">true</param>
* <param name="<b>encode</b>">true</param>
* </result></pre>
* <p/>
* In the above case, myUrl will be parsed against Ognl Value Stack and then
* URL encoded.
* <p/>
* or when using the default parameter feature
* <p/>
* <pre>
* <result name="success" type="redirect"><b>foo.jsp</b></result></pre>
* <p/>
* You should subclass this class if you're interested in adding more parameters or functionality
* to your Result. If you do subclass this class you will need to
* override {@link #doExecute(String, ActionInvocation)}.<p>
* <p/>
* Any custom result can be defined in struts.xml as:
* <p/>
* <pre>
* <result-types>
* ...
* <result-type name="myresult" class="com.foo.MyResult" />
* </result-types></pre>
* <p/>
* Please see the {@link com.opensymphony.xwork2.Result} class for more info on Results in general.
*
* <!-- END SNIPPET: example -->
*
* @see com.opensymphony.xwork2.Result
*/
public abstract class StrutsResultSupport implements Result, StrutsStatics {
private static final Logger LOG = LoggerFactory.getLogger(StrutsResultSupport.class);
/** The default parameter */
public static final String DEFAULT_PARAM = "location";
private boolean parse;
private boolean encode;
private String location;
private String lastFinalLocation;
public StrutsResultSupport() {
this(null, true, false);
}
public StrutsResultSupport(String location) {
this(location, true, false);
}
public StrutsResultSupport(String location, boolean parse, boolean encode) {
this.location = location;
this.parse = parse;
this.encode = encode;
}
/**
* The location to go to after action execution. This could be a JSP page or another action.
* The location can contain OGNL expressions which will be evaulated if the <tt>parse</tt>
* parameter is set to <tt>true</tt>.
*
* @param location the location to go to after action execution.
* @see #setParse(boolean)
*/
public void setLocation(String location) {
this.location = location;
}
/**
* Gets the location it was created with, mainly for testing
*/
public String getLocation() {
return location;
}
/**
* Returns the last parsed and encoded location value
*/
public String getLastFinalLocation() {
return lastFinalLocation;
}
/**
* Set parse to <tt>true</tt> to indicate that the location should be parsed as an OGNL expression. This
* is set to <tt>true</tt> by default.
*
* @param parse <tt>true</tt> if the location parameter is an OGNL expression, <tt>false</tt> otherwise.
*/
public void setParse(boolean parse) {
this.parse = parse;
}
/**
* Set encode to <tt>true</tt> to indicate that the location should be url encoded. This is set to
* <tt>true</tt> by default
*
* @param encode <tt>true</tt> if the location parameter should be url encode, <tt>false</tt> otherwise.
*/
public void setEncode(boolean encode) {
this.encode = encode;
}
/**
* Implementation of the <tt>execute</tt> method from the <tt>Result</tt> interface. This will call
* the abstract method {@link #doExecute(String, ActionInvocation)} after optionally evaluating the
* location as an OGNL evaluation.
*
* @param invocation the execution state of the action.
* @throws Exception if an error occurs while executing the result.
*/
public void execute(ActionInvocation invocation) throws Exception {
lastFinalLocation = conditionalParse(location, invocation);
doExecute(lastFinalLocation, invocation);
}
/**
* Parses the parameter for OGNL expressions against the valuestack
*
* @param param The parameter value
* @param invocation The action invocation instance
* @return The resulting string
*/
protected String conditionalParse(String param, ActionInvocation invocation) {
if (parse && param != null && invocation != null) {
return TextParseUtil.translateVariables(param, invocation.getStack(),
new TextParseUtil.ParsedValueEvaluator() {
public Object evaluate(Object parsedValue) {
if (encode) {
if (parsedValue != null) {
try {
// use UTF-8 as this is the recommended encoding by W3C to
// avoid incompatibilities.
return URLEncoder.encode(parsedValue.toString(), "UTF-8");
}
catch(UnsupportedEncodingException e) {
LOG.warn("error while trying to encode ["+parsedValue+"]", e);
}
}
}
return parsedValue;
}
});
} else {
return param;
}
}
/**
* Executes the result given a final location (jsp page, action, etc) and the action invocation
* (the state in which the action was executed). Subclasses must implement this class to handle
* custom logic for result handling.
*
* @param finalLocation the location (jsp page, action, etc) to go to.
* @param invocation the execution state of the action.
* @throws Exception if an error occurs while executing the result.
*/
protected abstract void doExecute(String finalLocation, ActionInvocation invocation) throws Exception;
}
| apache-2.0 |
mgargadennec/blossom | blossom-ui/blossom-ui-web/src/test/java/com/blossomproject/ui/web/administration/user/UsersControllerTest.java | 18707 | package com.blossomproject.ui.web.administration.user;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.blossomproject.core.common.dto.AbstractDTO;
import com.blossomproject.core.common.search.SearchEngineImpl;
import com.blossomproject.core.common.search.SearchResult;
import com.blossomproject.core.group.GroupDTO;
import com.blossomproject.core.role.RoleDTO;
import com.blossomproject.core.user.User;
import com.blossomproject.core.user.UserCreateForm;
import com.blossomproject.core.user.UserDTO;
import com.blossomproject.core.user.UserService;
import com.blossomproject.core.user.UserUpdateForm;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.tika.Tika;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
@RunWith(MockitoJUnitRunner.class)
public class UsersControllerTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Mock
private UserService service;
@Mock
private SearchEngineImpl<UserDTO> searchEngine;
@Mock
private Tika tika;
private UsersController controller;
@Before
public void setUp() {
controller = new UsersController(service, searchEngine, tika);
}
@Test
public void should_display_paged_users_without_query_parameter() throws Exception {
when(service.getAll(any(Pageable.class))).thenAnswer(a -> new PageImpl<UserDTO>(Lists.newArrayList()));
ModelAndView modelAndView = controller.getUsersPage(null, PageRequest.of(0, 20), null, new ExtendedModelMap());
assertTrue(modelAndView.getViewName().equals("blossom/users/users"));
assertTrue(modelAndView.getModel().get("users") instanceof Page);
verify(service, times(1)).getAll(any(Pageable.class));
}
@Test
public void should_display_paged_users_with_query_parameter() throws Exception {
when(searchEngine.search(any(String.class), any(Pageable.class), any(), anyList())).thenAnswer(a -> new SearchResult<>(0, new PageImpl<UserDTO>(Lists.newArrayList())));
ModelAndView modelAndView = controller.getUsersPage("test", PageRequest.of(0, 10), null, new ExtendedModelMap());
assertTrue(modelAndView.getViewName().equals("blossom/users/users"));
assertTrue(modelAndView.getModel().get("users") instanceof Page);
verify(searchEngine, times(1)).search(eq("test"), any(Pageable.class), any(), anyList());
}
@Test
public void should_display_create_page() throws Exception {
UserCreateForm userCreateForm = new UserCreateForm();
userCreateForm.setLocale(Locale.FRANCE);
ModelAndView modelAndView = controller.getUserCreatePage(new ExtendedModelMap(), Locale.FRANCE);
assertTrue(modelAndView.getViewName().equals("blossom/users/create"));
assertTrue(EqualsBuilder.reflectionEquals(userCreateForm, modelAndView.getModel().get("userCreateForm")));
assertTrue(EqualsBuilder.reflectionEquals(modelAndView.getModel().get("civilities"), User.Civility.values()));
}
@Test
public void should_handle_create_without_form_error() throws Exception {
UserCreateForm form = new UserCreateForm();
BindingResult result = mock(BindingResult.class);
when(result.hasErrors()).thenReturn(false);
UserDTO userToCreate = new UserDTO();
userToCreate.setId(1L);
when(service.create(any(UserCreateForm.class))).thenReturn(userToCreate);
ModelAndView modelAndView = controller.handleUserCreateForm(form, result, new ExtendedModelMap());
verify(service, times(1)).create(eq(form));
assertTrue(modelAndView.getViewName().equals("redirect:../users/1"));
}
@Test
public void should_handle_create_with_form_error() throws Exception {
UserCreateForm form = new UserCreateForm();
form.setFirstname("Firstname");
form.setLastname("Lastname");
form.setLocale(Locale.FRANCE);
form.setCivility(User.Civility.MAN);
form.setEmail("email@email.com");
form.setIdentifier("test");
BindingResult result = mock(BindingResult.class);
when(result.hasErrors()).thenReturn(true);
ModelAndView modelAndView = controller.handleUserCreateForm(form, result, new ExtendedModelMap());
assertTrue(modelAndView.getViewName().equals("blossom/users/create"));
assertTrue(EqualsBuilder.reflectionEquals(form, modelAndView.getModel().get("userCreateForm")));
}
@Test
public void should_handle_create_with_exception() throws Exception {
UserCreateForm form = new UserCreateForm();
form.setFirstname("Firstname");
form.setLastname("Lastname");
form.setLocale(Locale.FRANCE);
form.setCivility(User.Civility.MAN);
form.setEmail("email@email.com");
form.setIdentifier("test");
BindingResult result = mock(BindingResult.class);
when(result.hasErrors()).thenReturn(false);
when(service.create(any(UserCreateForm.class))).thenThrow(new Exception());
ModelAndView modelAndView = controller.handleUserCreateForm(form, result, new ExtendedModelMap());
assertTrue(modelAndView.getViewName().equals("blossom/users/create"));
assertTrue(EqualsBuilder.reflectionEquals(form, modelAndView.getModel().get("userCreateForm")));
}
@Test
public void should_display_one_with_id_not_found() throws Exception {
HttpServletRequest req = mock(HttpServletRequest.class);
when(service.getOne(any(Long.class))).thenReturn(null);
thrown.expect(NoSuchElementException.class);
thrown.expectMessage(String.format("User=%s not found", 1L));
controller.getUser(1L, new ExtendedModelMap(), req);
}
@Test
public void should_display_one_with_id_found() throws Exception {
HttpServletRequest req = mock(HttpServletRequest.class);
UserDTO userDTO = new UserDTO();
userDTO.setId(1L);
when(service.getOne(any(Long.class))).thenReturn(userDTO);
ModelAndView modelAndView = controller.getUser(1L, new ExtendedModelMap(), req);
assertTrue(modelAndView.getViewName().equals("blossom/users/user"));
assertTrue(EqualsBuilder.reflectionEquals(userDTO, modelAndView.getModel().get("user")));
verify(service, times(1)).getOne(eq(1L));
}
@Test
public void should_display_one_informations_with_id_not_found() throws Exception {
when(service.getOne(any(Long.class))).thenReturn(null);
thrown.expect(NoSuchElementException.class);
thrown.expectMessage(String.format("User=%s not found", 1L));
controller.getUserInformations(1L);
}
@Test
public void should_display_one_informations_with_id_found() throws Exception {
UserDTO userDTO = new UserDTO();
userDTO.setId(1L);
when(service.getOne(any(Long.class))).thenReturn(userDTO);
ModelAndView modelAndView = controller.getUserInformations(1L);
assertTrue(modelAndView.getViewName().equals("blossom/users/userinformations"));
assertTrue(EqualsBuilder.reflectionEquals(userDTO, modelAndView.getModel().get("user")));
verify(service, times(1)).getOne(eq(1L));
}
@Test
public void should_display_one_form_edit_with_id_not_found() throws Exception {
when(service.getOne(any(Long.class))).thenReturn(null);
thrown.expect(NoSuchElementException.class);
thrown.expectMessage(String.format("User=%s not found", 1L));
controller.getUserInformationsForm(1L, new ExtendedModelMap());
}
@Test
public void should_display_one_form_edit_with_id_found() throws Exception {
UserDTO userDTO = new UserDTO();
userDTO.setId(1L);
when(service.getOne(any(Long.class))).thenReturn(userDTO);
ModelAndView modelAndView = controller.getUserInformationsForm(1L, new ExtendedModelMap());
assertTrue(modelAndView.getViewName().equals("blossom/users/userinformations-edit"));
assertTrue(modelAndView.getStatus() == HttpStatus.OK);
UserUpdateForm userUpdateForm = (UserUpdateForm) modelAndView.getModel().get("userUpdateForm");
assertTrue(userUpdateForm.getId() == 1L);
assertTrue(EqualsBuilder.reflectionEquals(modelAndView.getModel().get("civilities"), User.Civility.values()));
assertTrue(EqualsBuilder.reflectionEquals(modelAndView.getModel().get("user"), userDTO));
verify(service, times(1)).getOne(eq(1L));
}
@Test
public void should_handle_update_without_id_found() throws Exception {
BindingResult result = mock(BindingResult.class);
when(service.getOne(any(Long.class))).thenReturn(null);
thrown.expect(NoSuchElementException.class);
thrown.expectMessage(String.format("User=%s not found", 1L));
controller.handleUserInformationsUpdateForm(1L, new UserUpdateForm(), result, new ExtendedModelMap());
}
@Test
public void should_handle_update_without_form_error() throws Exception {
UserUpdateForm form = new UserUpdateForm();
BindingResult result = mock(BindingResult.class);
when(result.hasErrors()).thenReturn(false);
UserDTO userUpdated = new UserDTO();
userUpdated.setId(1L);
when(service.getOne(any(Long.class))).thenReturn(userUpdated);
when(service.update(any(Long.class), any(UserUpdateForm.class))).thenReturn(userUpdated);
ModelAndView modelAndView = controller.handleUserInformationsUpdateForm(1L, form, result, new ExtendedModelMap());
verify(service, times(1)).update(eq(1L), eq(form));
assertTrue(modelAndView.getViewName().equals("blossom/users/userinformations"));
assertTrue(EqualsBuilder.reflectionEquals(userUpdated, modelAndView.getModel().get("user")));
}
@Test
public void should_handle_update_with_form_error() throws Exception {
UserUpdateForm form = new UserUpdateForm();
form.setFirstname("Firstname");
form.setLastname("Lastname");
form.setCivility(User.Civility.MAN);
form.setEmail("email@email.com");
BindingResult result = mock(BindingResult.class);
when(result.hasErrors()).thenReturn(true);
UserDTO userDTO = new UserDTO();
userDTO.setId(1L);
when(service.getOne(any(Long.class))).thenReturn(userDTO);
ModelAndView modelAndView = controller.handleUserInformationsUpdateForm(1L, form, result, new ExtendedModelMap());
assertTrue(modelAndView.getViewName().equals("blossom/users/userinformations-edit"));
assertTrue(EqualsBuilder.reflectionEquals(form, modelAndView.getModel().get("userUpdateForm")));
assertTrue(EqualsBuilder.reflectionEquals(userDTO, modelAndView.getModel().get("user")));
assertTrue(EqualsBuilder.reflectionEquals(modelAndView.getModel().get("civilities"), User.Civility.values()));
assertTrue(modelAndView.getStatus() == HttpStatus.CONFLICT);
}
@Test
public void should_get_avatar_with_id_found() throws Exception {
Long id = 1L;
InputStream avatar = new ByteArrayInputStream("test".getBytes());
when(service.loadAvatar(any(Long.class))).thenReturn(avatar);
when(tika.detect(any(InputStream.class))).thenReturn("image/png");
ResponseEntity<InputStreamResource> response = controller.displayAvatar(id);
verify(service, times(1)).loadAvatar(eq(id));
Assert.assertNotNull(response);
Assert.assertNotNull(response.getBody());
Assert.assertTrue((response.getBody().getInputStream().equals(avatar)));
Assert.assertTrue(response.getStatusCode() == HttpStatus.OK);
}
@Test
public void should_get_avatar_with_id_not_found() throws Exception {
Long id = 1L;
InputStream defaultAvatar = new ByteArrayInputStream("defaultAvatar".getBytes());
when(service.loadAvatar(any(Long.class))).thenReturn(defaultAvatar);
when(tika.detect(any(InputStream.class))).thenReturn("image/png");
ResponseEntity<InputStreamResource> response = controller.displayAvatar(id);
verify(service, times(1)).loadAvatar(eq(id));
Assert.assertNotNull(response);
Assert.assertNotNull(response.getBody());
Assert.assertTrue((response.getBody().getInputStream().equals(defaultAvatar)));
Assert.assertTrue(response.getStatusCode() == HttpStatus.OK);
}
@Test
public void should_display_avatar_form_with_id_found() throws Exception {
UserDTO userDTO = new UserDTO();
userDTO.setId(1L);
when(service.getOne(any(Long.class))).thenReturn(userDTO);
ModelAndView modelAndView = controller.getUserAvatarForm(1L, new ExtendedModelMap());
assertTrue(modelAndView.getViewName().equals("blossom/users/useravatar-edit-modal"));
assertTrue(EqualsBuilder.reflectionEquals(userDTO, modelAndView.getModel().get("user")));
verify(service, times(1)).getOne(eq(1L));
}
@Test
public void should_display_avatar_form_with_id_not_found() throws Exception {
when(service.getOne(any(Long.class))).thenReturn(null);
thrown.expect(NoSuchElementException.class);
thrown.expectMessage(String.format("User=%s not found", 1L));
controller.getUserAvatarForm(1L, new ExtendedModelMap());
}
@Test
public void should_update_avatar_with_id_found() throws Exception {
Long id = 1L;
when(service.getOne(any(Long.class))).thenAnswer(a -> {
UserDTO userDTO = new UserDTO();
userDTO.setId((Long) a.getArguments()[0]);
return userDTO;
});
MultipartFile multipartFile = new MockMultipartFile("testFile", "content".getBytes());
controller.handleUserAvatarUpdateForm(id, multipartFile);
verify(service, times(1)).getOne(eq(id));
verify(service, times(1)).updateAvatar(eq(id), eq(multipartFile.getBytes()));
}
@Test
public void should_update_avatar_with_id_not_found() throws Exception {
Long id = 1L;
when(service.getOne(any(Long.class))).thenReturn(null);
MultipartFile multipartFile = new MockMultipartFile("testFile", "content".getBytes());
thrown.expect(NoSuchElementException.class);
thrown.expectMessage(String.format("User=%s not found", id));
controller.handleUserAvatarUpdateForm(id, multipartFile);
}
@Test
public void should_delete_one_with_id_not_found() throws Exception {
Long id = 1L;
when(service.getOne(any(Long.class))).thenReturn(null);
ResponseEntity<Map<Class<? extends AbstractDTO>, Long>> response = controller.deleteUser(id, false);
verify(service, times(1)).getOne(eq(id));
verify(service, times(0)).delete(any(UserDTO.class), anyBoolean());
Assert.assertNotNull(response);
Assert.assertTrue(response.getBody().isEmpty());
Assert.assertTrue(response.getStatusCode() == HttpStatus.OK);
}
@Test
public void should_delete_one_with_id_found_without_associations() throws Exception {
Long id = 1L;
when(service.getOne(any(Long.class))).thenReturn(new UserDTO());
when(service.delete(any(UserDTO.class), anyBoolean())).thenReturn(Optional.empty());
ResponseEntity<Map<Class<? extends AbstractDTO>, Long>> response = controller.deleteUser(id, false);
verify(service, times(1)).getOne(eq(id));
verify(service, times(1)).delete(any(UserDTO.class), anyBoolean());
Assert.assertNotNull(response);
Assert.assertTrue(response.getBody().isEmpty());
Assert.assertTrue(response.getStatusCode() == HttpStatus.OK);
}
@Test
public void should_delete_one_with_id_found_with_associations_no_force() throws Exception {
Long id = 1L;
when(service.getOne(any(Long.class))).thenReturn(new UserDTO());
when(service.delete(any(UserDTO.class), eq(false))).thenReturn(Optional.of(ImmutableMap.<Class<? extends AbstractDTO>, Long>builder().put(GroupDTO.class, 2L).put(RoleDTO.class, 5L).build()));
ResponseEntity<Map<Class<? extends AbstractDTO>, Long>> response = controller.deleteUser(id, false);
verify(service, times(1)).getOne(eq(id));
verify(service, times(1)).delete(any(UserDTO.class), anyBoolean());
Assert.assertNotNull(response);
Assert.assertNotNull(response.getBody());
Assert.assertFalse(response.getBody().isEmpty());
Assert.assertTrue(response.getStatusCode() == HttpStatus.CONFLICT);
}
@Test
public void should_delete_one_with_id_found_with_associations_force() throws Exception {
Long id = 1L;
when(service.getOne(any(Long.class))).thenReturn(new UserDTO());
when(service.delete(any(UserDTO.class), eq(true))).thenReturn(Optional.empty());
ResponseEntity<Map<Class<? extends AbstractDTO>, Long>> response = controller.deleteUser(id, true);
Assert.assertNotNull(response);
Assert.assertTrue(response.getBody().isEmpty());
Assert.assertTrue(response.getStatusCode() == HttpStatus.OK);
verify(service, times(1)).getOne(eq(id));
verify(service, times(1)).delete(any(UserDTO.class), anyBoolean());
}
}
| apache-2.0 |
Praveen2112/presto | core/trino-main/src/test/java/io/trino/operator/aggregation/TestArrayAggregation.java | 9927 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.operator.aggregation;
import com.google.common.collect.ImmutableList;
import com.google.common.primitives.Ints;
import io.trino.metadata.Metadata;
import io.trino.metadata.ResolvedFunction;
import io.trino.operator.aggregation.groupby.AggregationTestInput;
import io.trino.operator.aggregation.groupby.AggregationTestInputBuilder;
import io.trino.operator.aggregation.groupby.AggregationTestOutput;
import io.trino.operator.aggregation.groupby.GroupByAggregationTestUtils;
import io.trino.spi.block.Block;
import io.trino.spi.block.BlockBuilder;
import io.trino.spi.type.ArrayType;
import io.trino.spi.type.SqlDate;
import io.trino.sql.tree.QualifiedName;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import static io.trino.SessionTestUtils.TEST_SESSION;
import static io.trino.block.BlockAssertions.createArrayBigintBlock;
import static io.trino.block.BlockAssertions.createBooleansBlock;
import static io.trino.block.BlockAssertions.createLongsBlock;
import static io.trino.block.BlockAssertions.createStringsBlock;
import static io.trino.block.BlockAssertions.createTypedLongsBlock;
import static io.trino.metadata.MetadataManager.createTestMetadataManager;
import static io.trino.operator.aggregation.AggregationTestUtils.assertAggregation;
import static io.trino.spi.type.BigintType.BIGINT;
import static io.trino.spi.type.BooleanType.BOOLEAN;
import static io.trino.spi.type.DateType.DATE;
import static io.trino.spi.type.VarcharType.VARCHAR;
import static io.trino.sql.analyzer.TypeSignatureProvider.fromTypes;
import static org.testng.Assert.assertTrue;
public class TestArrayAggregation
{
private static final Metadata metadata = createTestMetadataManager();
@Test
public void testEmpty()
{
ResolvedFunction bigIntAgg = metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(BIGINT));
assertAggregation(
metadata,
bigIntAgg,
null,
createLongsBlock(new Long[] {}));
}
@Test
public void testNullOnly()
{
ResolvedFunction bigIntAgg = metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(BIGINT));
assertAggregation(
metadata,
bigIntAgg,
Arrays.asList(null, null, null),
createLongsBlock(new Long[] {null, null, null}));
}
@Test
public void testNullPartial()
{
ResolvedFunction bigIntAgg = metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(BIGINT));
assertAggregation(
metadata,
bigIntAgg,
Arrays.asList(null, 2L, null, 3L, null),
createLongsBlock(new Long[] {null, 2L, null, 3L, null}));
}
@Test
public void testBoolean()
{
ResolvedFunction booleanAgg = metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(BOOLEAN));
assertAggregation(
metadata,
booleanAgg,
Arrays.asList(true, false),
createBooleansBlock(new Boolean[] {true, false}));
}
@Test
public void testBigInt()
{
ResolvedFunction bigIntAgg = metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(BIGINT));
assertAggregation(
metadata,
bigIntAgg,
Arrays.asList(2L, 1L, 2L),
createLongsBlock(new Long[] {2L, 1L, 2L}));
}
@Test
public void testVarchar()
{
ResolvedFunction varcharAgg = metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(VARCHAR));
assertAggregation(
metadata,
varcharAgg,
Arrays.asList("hello", "world"),
createStringsBlock(new String[] {"hello", "world"}));
}
@Test
public void testDate()
{
ResolvedFunction varcharAgg = metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(DATE));
assertAggregation(
metadata,
varcharAgg,
Arrays.asList(new SqlDate(1), new SqlDate(2), new SqlDate(4)),
createTypedLongsBlock(DATE, ImmutableList.of(1L, 2L, 4L)));
}
@Test
public void testArray()
{
ResolvedFunction varcharAgg = metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(new ArrayType(BIGINT)));
assertAggregation(
metadata,
varcharAgg,
Arrays.asList(Arrays.asList(1L), Arrays.asList(1L, 2L), Arrays.asList(1L, 2L, 3L)),
createArrayBigintBlock(ImmutableList.of(ImmutableList.of(1L), ImmutableList.of(1L, 2L), ImmutableList.of(1L, 2L, 3L))));
}
@Test
public void testEmptyStateOutputsNull()
{
InternalAggregationFunction bigIntAgg = metadata.getAggregateFunctionImplementation(metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(BIGINT)));
GroupedAccumulator groupedAccumulator = bigIntAgg.bind(Ints.asList(new int[] {}), Optional.empty())
.createGroupedAccumulator();
BlockBuilder blockBuilder = groupedAccumulator.getFinalType().createBlockBuilder(null, 1000);
groupedAccumulator.evaluateFinal(0, blockBuilder);
assertTrue(blockBuilder.isNull(0));
}
@Test
public void testWithMultiplePages()
{
InternalAggregationFunction varcharAgg = metadata.getAggregateFunctionImplementation(metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(VARCHAR)));
AggregationTestInputBuilder testInputBuilder = new AggregationTestInputBuilder(
new Block[] {
createStringsBlock("hello", "world", "hello2", "world2", "hello3", "world3", "goodbye")},
varcharAgg);
AggregationTestOutput testOutput = new AggregationTestOutput(ImmutableList.of("hello", "world", "hello2", "world2", "hello3", "world3", "goodbye"));
AggregationTestInput testInput = testInputBuilder.build();
testInput.runPagesOnAccumulatorWithAssertion(0L, testInput.createGroupedAccumulator(), testOutput);
}
@Test
public void testMultipleGroupsWithMultiplePages()
{
InternalAggregationFunction varcharAgg = metadata.getAggregateFunctionImplementation(metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(VARCHAR)));
Block block1 = createStringsBlock("a", "b", "c", "d", "e");
Block block2 = createStringsBlock("f", "g", "h", "i", "j");
AggregationTestOutput aggregationTestOutput1 = new AggregationTestOutput(ImmutableList.of("a", "b", "c", "d", "e"));
AggregationTestInputBuilder testInputBuilder1 = new AggregationTestInputBuilder(
new Block[] {block1},
varcharAgg);
AggregationTestInput test1 = testInputBuilder1.build();
GroupedAccumulator groupedAccumulator = test1.createGroupedAccumulator();
test1.runPagesOnAccumulatorWithAssertion(0L, groupedAccumulator, aggregationTestOutput1);
AggregationTestOutput aggregationTestOutput2 = new AggregationTestOutput(ImmutableList.of("f", "g", "h", "i", "j"));
AggregationTestInputBuilder testBuilder2 = new AggregationTestInputBuilder(
new Block[] {block2},
varcharAgg);
AggregationTestInput test2 = testBuilder2.build();
test2.runPagesOnAccumulatorWithAssertion(255L, groupedAccumulator, aggregationTestOutput2);
}
@Test
public void testManyValues()
{
// Test many values so multiple BlockBuilders will be used to store group state.
InternalAggregationFunction varcharAgg = metadata.getAggregateFunctionImplementation(metadata.resolveFunction(TEST_SESSION, QualifiedName.of("array_agg"), fromTypes(VARCHAR)));
int numGroups = 50000;
int arraySize = 30;
Random random = new Random();
GroupedAccumulator groupedAccumulator = createGroupedAccumulator(varcharAgg);
for (int j = 0; j < numGroups; j++) {
List<String> expectedValues = new ArrayList<>();
List<String> valueList = new ArrayList<>();
for (int i = 0; i < arraySize; i++) {
String str = String.valueOf(random.nextInt());
valueList.add(str);
expectedValues.add(str);
}
Block block = createStringsBlock(valueList);
AggregationTestInputBuilder testInputBuilder = new AggregationTestInputBuilder(
new Block[] {block},
varcharAgg);
AggregationTestInput test1 = testInputBuilder.build();
test1.runPagesOnAccumulatorWithAssertion(j, groupedAccumulator, new AggregationTestOutput(expectedValues));
}
}
private GroupedAccumulator createGroupedAccumulator(InternalAggregationFunction function)
{
int[] args = GroupByAggregationTestUtils.createArgs(function);
return function.bind(Ints.asList(args), Optional.empty())
.createGroupedAccumulator();
}
}
| apache-2.0 |
nla/bamboo | ui/src/bamboo/pandas/PandasDirectorySync.java | 5798 | package bamboo.pandas;
import org.skife.jdbi.v2.ResultIterator;
import java.util.*;
import static bamboo.pandas.PandasType.AGENCY;
import static bamboo.pandas.PandasType.COLLECTION;
import static bamboo.pandas.PandasType.SUBJECT;
import static java.util.stream.Collectors.toSet;
public class PandasDirectorySync {
// PandasDAO pandasDAO;
// Categories categories;
// Agencies agencies;
//
// void sync() {
// syncAgencies();
// syncSubjects();
// syncCollections();
// syncTitles();
// }
//
// void syncAgencies() {
// for (PandasAgency panAgency : pandasDAO.listAgencies()) {
// Agency agency = agencies.getByLegacyIdOrNull(AGENCY.id(), panAgency.getId());
// if (agency == null) {
// agency = new Agency();
// }
//
// agency.setName(panAgency.getName());
// agency.setLogo(panAgency.getLogo());
// agency.setLegacyId(AGENCY.id(), panAgency.getId());
// agency.setUrl(panAgency.getUrl());
//
// agencies.save(agency);
// }
//
// }
//
// /**
// * For each subject:
// * - Create a corresponding category with the same name
// * - If the subject has a parent subject, link the new category to the corresponding parent category.
// */
// void syncSubjects() {
// for (PandasSubject subject : pandasDAO.listSubjects()) {
// Category category = categories.getByLegacyIdOrNull(SUBJECT.id(), subject.getId());
// if (category == null) {
// category = new Category();
// }
//
// category.setName(subject.getName());
// category.setLegacyId(SUBJECT.id(), subject.getId());
//
// Category parent = categories.getByLegacyId(SUBJECT.id(), subject.getParentId());
// category.setParentId(parent == null ? null : parent.getId());
//
// categories.save(category);
// }
// }
//
// /**
// * For each collection:
// * - Create a corresponding category with the same name
// * - TODO Add curating agencies to the category based on the owner of each title in the collection.
// * - If the collection has a parent collection, link the new category to the corresponding parent category.
// * - For each subject the collection is in:
// * + If there was a parent collection and it has this same subject, ignore this subject.
// * + If the new category has no parent yet, set its parent to this subject.
// * + Otherwise, since the category already has a parent, add a reference from the subject.
// */
// void syncCollections() {
// for (PandasCollection collection : pandasDAO.listCollections()) {
// Category category = categories.getByLegacyIdOrNull(COLLECTION.id(), collection.getId());
// if (category == null) {
// category = new Category();
// }
//
// category.setName(collection.getName());
// category.setDescription(collection.getDisplayComment());
// category.setLegacyId(COLLECTION.id(), collection.getId());
//
// Category parent = categories.getByLegacyIdOrNull(COLLECTION.id(), collection.getParentId());
// Set<Long> parentSubjectIds = Collections.emptySet();
// if (parent != null) {
// category.setParentId(parent.getId());
// parentSubjectIds = pandasDAO.listSubjectsForCollectionId(collection.getId()).stream()
// .map(PandasSubject::getId).collect(toSet());
// }
//
// List<Long> categoriesToLinkFrom = new ArrayList<>();
// for (PandasSubject subject : pandasDAO.listSubjectsForCollectionId(collection.getId())) {
// if (!parentSubjectIds.contains(subject.getId())) {
// Category subjectCategory = categories.getByLegacyIdOrNull(SUBJECT.id(), subject.getId());
// if (category.getParentId() == null) {
// category.setParentId(subjectCategory.getId());
// } else {
// categoriesToLinkFrom.add(subjectCategory.getId());
// }
// }
// }
//
// categories.save(category);
//
// for (long categoryId : categoriesToLinkFrom) {
// categories.addSymLinkIfNotExists(categoryId, category.getId());
// }
// }
// }
//
// /**
// For each title
// - If the title has issues
// + Create a category for the title
// + Create a subcategory for each issue group
// + Add each issue as an entry in the appropriate category
// + Ignore the instances
// - Else if the title has multiple instances with different domains
// + Create a category for the title
// + Create entries in the category for each variation
// - Name these entries using the domain and year ranges: "Jason's blog (geocities.com) 1998-2002", "Jason's blog (jason.id.au) 2003-"
// - Otherwise if the title has instances all sharing the same domain
// + Create a directory entry for the title
// - For each collection the title is in:
// + If the title has no parent, set the parent to the be collection.
// + Otherwise, since the title already has a parent add a reference from the collection.
// - For each subject the title is in that is in the "subjects we want to treat as a collection" list:
// + Apply the above collection rules.
// */
// private void syncTitles() {
// try (ResultIterator<PandasTitle> it = pandasDAO.iterateTitles()) {
// while (it.hasNext()) {
// PandasTitle title = it.next();
//
//
// }
// }
// }
//
}
| apache-2.0 |
jawer/mvlasov | chapter_005/src/main/java/ru/job4j/stackandqueuecontainers/SimpleStack.java | 1589 | package ru.job4j.stackandqueuecontainers;
import ru.job4j.simplelinkedlist.SimpleLinkedList;
import java.util.NoSuchElementException;
/**.
* Class SimpleStack uses container based on linked list creates simple stack container.
* @author Mikhail Vlasov
* @since 03.25.2018
* @version 1
*/
public class SimpleStack<T> {
/**.
* SimpleLinkedList container.
*/
private SimpleLinkedList<T> lnkList = new SimpleLinkedList<>();
/**.
* Size.
*/
private int index = 0;
/**.
* Constructor.
*/
public SimpleStack() {
}
/**.
* Gets SimpleLinkedList container for testing purpose.
*/
public SimpleLinkedList<T> getSimpleLinkedList() {
return lnkList;
}
/**.
* Pushes new value into stack.
* @param value object.
*/
public void push(T value) {
lnkList.add(value);
index++;
}
/**.
* Polls first value based on LIFO - last input, first output.
* @return T value.
*/
public T poll() {
if (index == 0) {
throw new NoSuchElementException("The stack is empty.");
}
return remove(index--);
}
/**.
* Removes polled value from the stack.
* @param index value.
* @return T value.
*/
private T remove(int index) {
SimpleLinkedList<T> temp = new SimpleLinkedList<>();
for (int i = 0; i < index - 1; i++) {
temp.add(lnkList.get(i));
}
T removedValue = lnkList.get(index - 1);
lnkList = temp;
return removedValue;
}
}
| apache-2.0 |
vam-google/google-cloud-java | google-api-grpc/proto-google-cloud-dialogflow-v2/src/main/java/com/google/cloud/dialogflow/v2/DeleteSessionEntityTypeRequest.java | 21231 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/dialogflow/v2/session_entity_type.proto
package com.google.cloud.dialogflow.v2;
/**
*
*
* <pre>
* The request message for
* [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest}
*/
public final class DeleteSessionEntityTypeRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest)
DeleteSessionEntityTypeRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeleteSessionEntityTypeRequest.newBuilder() to construct.
private DeleteSessionEntityTypeRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeleteSessionEntityTypeRequest() {
name_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private DeleteSessionEntityTypeRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
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:
{
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
default:
{
if (!parseUnknownFieldProto3(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.cloud.dialogflow.v2.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_v2_DeleteSessionEntityTypeRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_v2_DeleteSessionEntityTypeRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest.class,
com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
*
*
* <pre>
* Required. The name of the entity type to delete. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type
* Display Name>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the entity type to delete. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type
* Display Name>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
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 (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
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.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest other =
(com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest) obj;
boolean result = true;
result = result && getName().equals(other.getName());
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest 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.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest 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.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest 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.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest 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.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest 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>
* The request message for
* [SessionEntityTypes.DeleteSessionEntityType][google.cloud.dialogflow.v2.SessionEntityTypes.DeleteSessionEntityType].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest)
com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_v2_DeleteSessionEntityTypeRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_v2_DeleteSessionEntityTypeRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest.class,
com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest.Builder.class);
}
// Construct using com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest.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();
name_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.v2.SessionEntityTypeProto
.internal_static_google_cloud_dialogflow_v2_DeleteSessionEntityTypeRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest
getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest build() {
com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest buildPartial() {
com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest result =
new com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest(this);
result.name_ = name_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return (Builder) super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest) {
return mergeFrom((com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest other) {
if (other
== com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest.getDefaultInstance())
return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
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.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. The name of the entity type to delete. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type
* Display Name>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the entity type to delete. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type
* Display Name>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the entity type to delete. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type
* Display Name>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the entity type to delete. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type
* Display Name>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the entity type to delete. Format:
* `projects/<Project ID>/agent/sessions/<Session ID>/entityTypes/<Entity Type
* Display Name>`.
* </pre>
*
* <code>string name = 1;</code>
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest)
private static final com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest();
}
public static com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeleteSessionEntityTypeRequest> PARSER =
new com.google.protobuf.AbstractParser<DeleteSessionEntityTypeRequest>() {
@java.lang.Override
public DeleteSessionEntityTypeRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new DeleteSessionEntityTypeRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<DeleteSessionEntityTypeRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeleteSessionEntityTypeRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.DeleteSessionEntityTypeRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
alanfgates/hive | ql/src/java/org/apache/hadoop/hive/ql/exec/MaterializedViewTask.java | 3612 | /*
* 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.hive.ql.exec;
import com.google.common.collect.ImmutableSet;
import org.apache.hadoop.hive.common.ValidTxnWriteIdList;
import org.apache.hadoop.hive.metastore.api.CreationMetadata;
import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.DriverContext;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.HiveMaterializedViewsRegistry;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.parse.ExplainConfiguration.AnalyzeState;
import org.apache.hadoop.hive.ql.plan.api.StageType;
import java.io.Serializable;
import static org.apache.hadoop.hive.metastore.Warehouse.DEFAULT_CATALOG_NAME;
/**
* This task does some work related to materialized views. In particular, it adds
* or removes the materialized view from the registry if needed, or registers new
* creation metadata.
*/
public class MaterializedViewTask extends Task<MaterializedViewDesc> implements Serializable {
private static final long serialVersionUID = 1L;
public MaterializedViewTask() {
super();
}
@Override
public int execute(DriverContext driverContext) {
if (driverContext.getCtx().getExplainAnalyze() == AnalyzeState.RUNNING) {
return 0;
}
try {
if (getWork().isRetrieveAndInclude()) {
Hive db = Hive.get(conf);
Table mvTable = db.getTable(getWork().getViewName());
HiveMaterializedViewsRegistry.get().createMaterializedView(db.getConf(), mvTable);
} else if (getWork().isDisableRewrite()) {
// Disabling rewriting, removing from cache
String[] names = getWork().getViewName().split("\\.");
HiveMaterializedViewsRegistry.get().dropMaterializedView(names[0], names[1]);
} else if (getWork().isUpdateCreationMetadata()) {
// We need to update the status of the creation signature
Hive db = Hive.get(conf);
Table mvTable = db.getTable(getWork().getViewName());
CreationMetadata cm =
new CreationMetadata(MetaStoreUtils.getDefaultCatalog(conf), mvTable.getDbName(),
mvTable.getTableName(),
ImmutableSet.copyOf(mvTable.getCreationMetadata().getTablesUsed()));
cm.setValidTxnList(conf.get(ValidTxnWriteIdList.VALID_TABLES_WRITEIDS_KEY));
db.updateCreationMetadata(mvTable.getDbName(), mvTable.getTableName(), cm);
}
} catch (HiveException e) {
LOG.debug("Exception during materialized view cache update", e);
setException(e);
}
return 0;
}
@Override
public StageType getType() {
return StageType.DDL;
}
@Override
public String getName() {
return MaterializedViewTask.class.getSimpleName();
}
}
| apache-2.0 |
BrunoEberhard/minimal-j | ext/historized/src/test/java/org/minimalj/repository/sql/SqlHistorizedOptimisticLockingTest.java | 1620 | package org.minimalj.repository.sql;
import org.junit.BeforeClass;
import org.junit.Test;
import org.minimalj.model.Keys;
import org.minimalj.model.annotation.Size;
import org.minimalj.repository.DataSourceFactory;
public class SqlHistorizedOptimisticLockingTest {
private static SqlHistorizedRepository repository;
@BeforeClass
public static void setupRepository() {
repository = new SqlHistorizedRepository(DataSourceFactory.embeddedDataSource(), TestEntityHistorized.class);
}
@Test
public void testHistorizedOptimisticLockingOk() {
TestEntityHistorized entity = new TestEntityHistorized();
entity.string = "A";
Object id = repository.insert(entity);
entity = repository.read(TestEntityHistorized.class, id);
entity.string = "B";
repository.update(entity);
entity = repository.read(TestEntityHistorized.class, id);
entity.string = "C";
repository.update(entity);
}
@Test(expected = Exception.class)
public void testHistorizedOptimisticLockingFail() {
TestEntityHistorized entity = new TestEntityHistorized();
entity.string = "A";
Object id = repository.insert(entity);
entity = repository.read(TestEntityHistorized.class, id);
entity.string = "B";
repository.update(entity);
// here the read is forgotten
// this tries to update an old version of r
entity.string = "C";
repository.update(entity);
}
public static class TestEntityHistorized {
public static final TestEntityHistorized $ = Keys.of(TestEntityHistorized.class);
public Object id;
public int version;
public boolean historized;
@Size(255)
public String string;
}
}
| apache-2.0 |
bloomberg/presto | presto-main/src/main/java/com/facebook/presto/sql/planner/optimizations/UnaliasSymbolReferences.java | 33443 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner.optimizations;
import com.facebook.presto.Session;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.spi.block.SortOrder;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.planner.DeterminismEvaluator;
import com.facebook.presto.sql.planner.PartitioningScheme;
import com.facebook.presto.sql.planner.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.SymbolAllocator;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.ApplyNode;
import com.facebook.presto.sql.planner.plan.AssignUniqueId;
import com.facebook.presto.sql.planner.plan.Assignments;
import com.facebook.presto.sql.planner.plan.DeleteNode;
import com.facebook.presto.sql.planner.plan.DistinctLimitNode;
import com.facebook.presto.sql.planner.plan.EnforceSingleRowNode;
import com.facebook.presto.sql.planner.plan.ExceptNode;
import com.facebook.presto.sql.planner.plan.ExchangeNode;
import com.facebook.presto.sql.planner.plan.ExplainAnalyzeNode;
import com.facebook.presto.sql.planner.plan.FilterNode;
import com.facebook.presto.sql.planner.plan.GroupIdNode;
import com.facebook.presto.sql.planner.plan.IndexJoinNode;
import com.facebook.presto.sql.planner.plan.IndexSourceNode;
import com.facebook.presto.sql.planner.plan.IntersectNode;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.LimitNode;
import com.facebook.presto.sql.planner.plan.MarkDistinctNode;
import com.facebook.presto.sql.planner.plan.OutputNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.RemoteSourceNode;
import com.facebook.presto.sql.planner.plan.RowNumberNode;
import com.facebook.presto.sql.planner.plan.SampleNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.SetOperationNode;
import com.facebook.presto.sql.planner.plan.SimplePlanRewriter;
import com.facebook.presto.sql.planner.plan.SortNode;
import com.facebook.presto.sql.planner.plan.TableFinishNode;
import com.facebook.presto.sql.planner.plan.TableScanNode;
import com.facebook.presto.sql.planner.plan.TableWriterNode;
import com.facebook.presto.sql.planner.plan.TopNNode;
import com.facebook.presto.sql.planner.plan.TopNRowNumberNode;
import com.facebook.presto.sql.planner.plan.UnionNode;
import com.facebook.presto.sql.planner.plan.UnnestNode;
import com.facebook.presto.sql.planner.plan.ValuesNode;
import com.facebook.presto.sql.planner.plan.WindowNode;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.ExpressionRewriter;
import com.facebook.presto.sql.tree.ExpressionTreeRewriter;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.NullLiteral;
import com.facebook.presto.sql.tree.SymbolReference;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static com.facebook.presto.sql.planner.plan.JoinNode.Type.INNER;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static java.util.Objects.requireNonNull;
/**
* Re-maps symbol references that are just aliases of each other (e.g., due to projections like {@code $0 := $1})
* <p/>
* E.g.,
* <p/>
* {@code Output[$0, $1] -> Project[$0 := $2, $1 := $3 * 100] -> Aggregate[$2, $3 := sum($4)] -> ...}
* <p/>
* gets rewritten as
* <p/>
* {@code Output[$2, $1] -> Project[$2, $1 := $3 * 100] -> Aggregate[$2, $3 := sum($4)] -> ...}
*/
public class UnaliasSymbolReferences
implements PlanOptimizer
{
@Override
public PlanNode optimize(PlanNode plan, Session session, Map<Symbol, Type> types, SymbolAllocator symbolAllocator, PlanNodeIdAllocator idAllocator)
{
requireNonNull(plan, "plan is null");
requireNonNull(session, "session is null");
requireNonNull(types, "types is null");
requireNonNull(symbolAllocator, "symbolAllocator is null");
requireNonNull(idAllocator, "idAllocator is null");
return SimplePlanRewriter.rewriteWith(new Rewriter(types), plan);
}
private static class Rewriter
extends SimplePlanRewriter<Void>
{
private final Map<Symbol, Symbol> mapping = new HashMap<>();
private final Map<Symbol, Type> types;
private Rewriter(Map<Symbol, Type> types)
{
this.types = types;
}
@Override
public PlanNode visitAggregation(AggregationNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
//TODO: use mapper in other methods
SymbolMapper mapper = new SymbolMapper(mapping);
return mapper.map(node, source);
}
@Override
public PlanNode visitGroupId(GroupIdNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
Map<Symbol, Symbol> newGroupingMappings = new HashMap<>();
ImmutableList.Builder<List<Symbol>> newGroupingSets = ImmutableList.builder();
for (List<Symbol> groupingSet : node.getGroupingSets()) {
ImmutableList.Builder<Symbol> newGroupingSet = ImmutableList.builder();
for (Symbol output : groupingSet) {
newGroupingMappings.putIfAbsent(canonicalize(output), canonicalize(node.getGroupingSetMappings().get(output)));
newGroupingSet.add(canonicalize(output));
}
newGroupingSets.add(newGroupingSet.build());
}
Map<Symbol, Symbol> newArgumentMappings = new HashMap<>();
for (Symbol output : node.getArgumentMappings().keySet()) {
Symbol canonicalOutput = canonicalize(output);
if (newArgumentMappings.containsKey(canonicalOutput)) {
map(output, canonicalOutput);
}
else {
newArgumentMappings.put(canonicalOutput, canonicalize(node.getArgumentMappings().get(output)));
}
}
return new GroupIdNode(node.getId(), source, newGroupingSets.build(), newGroupingMappings, newArgumentMappings, canonicalize(node.getGroupIdSymbol()));
}
@Override
public PlanNode visitExplainAnalyze(ExplainAnalyzeNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
return new ExplainAnalyzeNode(node.getId(), source, canonicalize(node.getOutputSymbol()));
}
@Override
public PlanNode visitMarkDistinct(MarkDistinctNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
List<Symbol> symbols = canonicalizeAndDistinct(node.getDistinctSymbols());
return new MarkDistinctNode(node.getId(), source, canonicalize(node.getMarkerSymbol()), symbols, canonicalize(node.getHashSymbol()));
}
@Override
public PlanNode visitUnnest(UnnestNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
ImmutableMap.Builder<Symbol, List<Symbol>> builder = ImmutableMap.builder();
for (Map.Entry<Symbol, List<Symbol>> entry : node.getUnnestSymbols().entrySet()) {
builder.put(canonicalize(entry.getKey()), entry.getValue());
}
return new UnnestNode(node.getId(), source, canonicalizeAndDistinct(node.getReplicateSymbols()), builder.build(), node.getOrdinalitySymbol());
}
@Override
public PlanNode visitWindow(WindowNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
ImmutableMap.Builder<Symbol, WindowNode.Function> functions = ImmutableMap.builder();
for (Map.Entry<Symbol, WindowNode.Function> entry : node.getWindowFunctions().entrySet()) {
Symbol symbol = entry.getKey();
FunctionCall canonicalFunctionCall = (FunctionCall) canonicalize(entry.getValue().getFunctionCall());
Signature signature = entry.getValue().getSignature();
WindowNode.Frame canonicalFrame = canonicalize(entry.getValue().getFrame());
functions.put(canonicalize(symbol), new WindowNode.Function(canonicalFunctionCall, signature, canonicalFrame));
}
ImmutableMap.Builder<Symbol, SortOrder> orderings = ImmutableMap.builder();
for (Map.Entry<Symbol, SortOrder> entry : node.getOrderings().entrySet()) {
orderings.put(canonicalize(entry.getKey()), entry.getValue());
}
return new WindowNode(
node.getId(),
source,
canonicalizeAndDistinct(node.getSpecification()),
functions.build(),
canonicalize(node.getHashSymbol()),
canonicalize(node.getPrePartitionedInputs()),
node.getPreSortedOrderPrefix());
}
private WindowNode.Frame canonicalize(WindowNode.Frame frame)
{
return new WindowNode.Frame(frame.getType(),
frame.getStartType(), canonicalize(frame.getStartValue()),
frame.getEndType(), canonicalize(frame.getEndValue()));
}
@Override
public PlanNode visitTableScan(TableScanNode node, RewriteContext<Void> context)
{
Expression originalConstraint = null;
if (node.getOriginalConstraint() != null) {
originalConstraint = canonicalize(node.getOriginalConstraint());
}
return new TableScanNode(
node.getId(),
node.getTable(),
node.getOutputSymbols(),
node.getAssignments(),
node.getLayout(),
node.getCurrentConstraint(),
originalConstraint);
}
@Override
public PlanNode visitExchange(ExchangeNode node, RewriteContext<Void> context)
{
List<PlanNode> sources = node.getSources().stream()
.map(context::rewrite)
.collect(toImmutableList());
mapExchangeNodeSymbols(node);
List<List<Symbol>> inputs = new ArrayList<>();
for (int i = 0; i < node.getInputs().size(); i++) {
inputs.add(new ArrayList<>());
}
Set<Symbol> addedOutputs = new HashSet<>();
ImmutableList.Builder<Symbol> outputs = ImmutableList.builder();
for (int symbolIndex = 0; symbolIndex < node.getOutputSymbols().size(); symbolIndex++) {
Symbol canonicalOutput = canonicalize(node.getOutputSymbols().get(symbolIndex));
if (addedOutputs.add(canonicalOutput)) {
outputs.add(canonicalOutput);
for (int i = 0; i < node.getInputs().size(); i++) {
List<Symbol> input = node.getInputs().get(i);
inputs.get(i).add(canonicalize(input.get(symbolIndex)));
}
}
}
PartitioningScheme partitioningScheme = new PartitioningScheme(
node.getPartitioningScheme().getPartitioning().translate(this::canonicalize),
outputs.build(),
canonicalize(node.getPartitioningScheme().getHashColumn()),
node.getPartitioningScheme().isReplicateNullsAndAny(),
node.getPartitioningScheme().getBucketToPartition());
return new ExchangeNode(node.getId(), node.getType(), node.getScope(), partitioningScheme, sources, inputs);
}
private void mapExchangeNodeSymbols(ExchangeNode node)
{
if (node.getInputs().size() == 1) {
mapExchangeNodeOutputToInputSymbols(node);
return;
}
// Mapping from list [node.getInput(0).get(symbolIndex), node.getInput(1).get(symbolIndex), ...] to node.getOutputSymbols(symbolIndex).
// All symbols are canonical.
Map<List<Symbol>, Symbol> inputsToOutputs = new HashMap<>();
// Map each same list of input symbols [I1, I2, ..., In] to the same output symbol O
for (int symbolIndex = 0; symbolIndex < node.getOutputSymbols().size(); symbolIndex++) {
Symbol canonicalOutput = canonicalize(node.getOutputSymbols().get(symbolIndex));
List<Symbol> canonicalInputs = canonicalizeExchangeNodeInputs(node, symbolIndex);
Symbol output = inputsToOutputs.get(canonicalInputs);
if (output == null || canonicalOutput.equals(output)) {
inputsToOutputs.put(canonicalInputs, canonicalOutput);
}
else {
map(canonicalOutput, output);
}
}
}
private void mapExchangeNodeOutputToInputSymbols(ExchangeNode node)
{
checkState(node.getInputs().size() == 1);
for (int symbolIndex = 0; symbolIndex < node.getOutputSymbols().size(); symbolIndex++) {
Symbol canonicalOutput = canonicalize(node.getOutputSymbols().get(symbolIndex));
Symbol canonicalInput = canonicalize(node.getInputs().get(0).get(symbolIndex));
if (!canonicalOutput.equals(canonicalInput)) {
map(canonicalOutput, canonicalInput);
}
}
}
private List<Symbol> canonicalizeExchangeNodeInputs(ExchangeNode node, int symbolIndex)
{
return node.getInputs().stream()
.map(input -> canonicalize(input.get(symbolIndex)))
.collect(toImmutableList());
}
@Override
public PlanNode visitRemoteSource(RemoteSourceNode node, RewriteContext<Void> context)
{
return new RemoteSourceNode(node.getId(), node.getSourceFragmentIds(), canonicalizeAndDistinct(node.getOutputSymbols()));
}
@Override
public PlanNode visitLimit(LimitNode node, RewriteContext<Void> context)
{
return context.defaultRewrite(node);
}
@Override
public PlanNode visitDistinctLimit(DistinctLimitNode node, RewriteContext<Void> context)
{
return new DistinctLimitNode(node.getId(), context.rewrite(node.getSource()), node.getLimit(), node.isPartial(), canonicalizeAndDistinct(node.getDistinctSymbols()), canonicalize(node.getHashSymbol()));
}
@Override
public PlanNode visitSample(SampleNode node, RewriteContext<Void> context)
{
return new SampleNode(node.getId(), context.rewrite(node.getSource()), node.getSampleRatio(), node.getSampleType());
}
@Override
public PlanNode visitValues(ValuesNode node, RewriteContext<Void> context)
{
return context.defaultRewrite(node);
}
@Override
public PlanNode visitDelete(DeleteNode node, RewriteContext<Void> context)
{
return new DeleteNode(node.getId(), context.rewrite(node.getSource()), node.getTarget(), canonicalize(node.getRowId()), node.getOutputSymbols());
}
@Override
public PlanNode visitTableFinish(TableFinishNode node, RewriteContext<Void> context)
{
return context.defaultRewrite(node);
}
@Override
public PlanNode visitRowNumber(RowNumberNode node, RewriteContext<Void> context)
{
return new RowNumberNode(node.getId(), context.rewrite(node.getSource()), canonicalizeAndDistinct(node.getPartitionBy()), canonicalize(node.getRowNumberSymbol()), node.getMaxRowCountPerPartition(), canonicalize(node.getHashSymbol()));
}
@Override
public PlanNode visitTopNRowNumber(TopNRowNumberNode node, RewriteContext<Void> context)
{
return new TopNRowNumberNode(
node.getId(),
context.rewrite(node.getSource()),
canonicalizeAndDistinct(node.getSpecification()),
canonicalize(node.getRowNumberSymbol()),
node.getMaxRowCountPerPartition(),
node.isPartial(),
canonicalize(node.getHashSymbol()));
}
@Override
public PlanNode visitFilter(FilterNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
return new FilterNode(node.getId(), source, canonicalize(node.getPredicate()));
}
@Override
public PlanNode visitProject(ProjectNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
return new ProjectNode(node.getId(), source, canonicalize(node.getAssignments()));
}
@Override
public PlanNode visitOutput(OutputNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
List<Symbol> canonical = Lists.transform(node.getOutputSymbols(), this::canonicalize);
return new OutputNode(node.getId(), source, node.getColumnNames(), canonical);
}
@Override
public PlanNode visitEnforceSingleRow(EnforceSingleRowNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
return new EnforceSingleRowNode(node.getId(), source);
}
@Override
public PlanNode visitAssignUniqueId(AssignUniqueId node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
return new AssignUniqueId(node.getId(), source, node.getIdColumn());
}
@Override
public PlanNode visitApply(ApplyNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getInput());
PlanNode subquery = context.rewrite(node.getSubquery());
List<Symbol> canonicalCorrelation = Lists.transform(node.getCorrelation(), this::canonicalize);
return new ApplyNode(node.getId(), source, subquery, canonicalize(node.getSubqueryAssignments()), canonicalCorrelation);
}
@Override
public PlanNode visitTopN(TopNNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
SymbolMapper mapper = new SymbolMapper(mapping);
return mapper.map(node, source, node.getId());
}
@Override
public PlanNode visitSort(SortNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
Set<Symbol> added = new HashSet<>();
ImmutableList.Builder<Symbol> symbols = ImmutableList.builder();
ImmutableMap.Builder<Symbol, SortOrder> orderings = ImmutableMap.builder();
for (Symbol symbol : node.getOrderBy()) {
Symbol canonical = canonicalize(symbol);
if (added.add(canonical)) {
symbols.add(canonical);
orderings.put(canonical, node.getOrderings().get(symbol));
}
}
return new SortNode(node.getId(), source, symbols.build(), orderings.build());
}
@Override
public PlanNode visitJoin(JoinNode node, RewriteContext<Void> context)
{
PlanNode left = context.rewrite(node.getLeft());
PlanNode right = context.rewrite(node.getRight());
List<JoinNode.EquiJoinClause> canonicalCriteria = canonicalizeJoinCriteria(node.getCriteria());
Optional<Expression> canonicalFilter = node.getFilter().map(this::canonicalize);
Optional<Symbol> canonicalLeftHashSymbol = canonicalize(node.getLeftHashSymbol());
Optional<Symbol> canonicalRightHashSymbol = canonicalize(node.getRightHashSymbol());
if (node.getType().equals(INNER)) {
canonicalCriteria.stream()
.filter(clause -> types.get(clause.getLeft()).equals(types.get(clause.getRight())))
.filter(clause -> node.getOutputSymbols().contains(clause.getLeft()))
.forEach(clause -> map(clause.getRight(), clause.getLeft()));
}
return new JoinNode(node.getId(), node.getType(), left, right, canonicalCriteria, canonicalizeAndDistinct(node.getOutputSymbols()), canonicalFilter, canonicalLeftHashSymbol, canonicalRightHashSymbol, node.getDistributionType());
}
@Override
public PlanNode visitSemiJoin(SemiJoinNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
PlanNode filteringSource = context.rewrite(node.getFilteringSource());
return new SemiJoinNode(
node.getId(),
source,
filteringSource,
canonicalize(node.getSourceJoinSymbol()),
canonicalize(node.getFilteringSourceJoinSymbol()),
canonicalize(node.getSemiJoinOutput()),
canonicalize(node.getSourceHashSymbol()),
canonicalize(node.getFilteringSourceHashSymbol()),
node.getDistributionType());
}
@Override
public PlanNode visitIndexSource(IndexSourceNode node, RewriteContext<Void> context)
{
return new IndexSourceNode(node.getId(), node.getIndexHandle(), node.getTableHandle(), node.getLayout(), canonicalize(node.getLookupSymbols()), node.getOutputSymbols(), node.getAssignments(), node.getEffectiveTupleDomain());
}
@Override
public PlanNode visitIndexJoin(IndexJoinNode node, RewriteContext<Void> context)
{
PlanNode probeSource = context.rewrite(node.getProbeSource());
PlanNode indexSource = context.rewrite(node.getIndexSource());
return new IndexJoinNode(node.getId(), node.getType(), probeSource, indexSource, canonicalizeIndexJoinCriteria(node.getCriteria()), canonicalize(node.getProbeHashSymbol()), canonicalize(node.getIndexHashSymbol()));
}
@Override
public PlanNode visitUnion(UnionNode node, RewriteContext<Void> context)
{
return new UnionNode(node.getId(), rewriteSources(node, context).build(), canonicalizeSetOperationSymbolMap(node.getSymbolMapping()), canonicalizeAndDistinct(node.getOutputSymbols()));
}
@Override
public PlanNode visitIntersect(IntersectNode node, RewriteContext<Void> context)
{
return new IntersectNode(node.getId(), rewriteSources(node, context).build(), canonicalizeSetOperationSymbolMap(node.getSymbolMapping()), canonicalizeAndDistinct(node.getOutputSymbols()));
}
@Override
public PlanNode visitExcept(ExceptNode node, RewriteContext<Void> context)
{
return new ExceptNode(node.getId(), rewriteSources(node, context).build(), canonicalizeSetOperationSymbolMap(node.getSymbolMapping()), canonicalizeAndDistinct(node.getOutputSymbols()));
}
private static ImmutableList.Builder<PlanNode> rewriteSources(SetOperationNode node, RewriteContext<Void> context)
{
ImmutableList.Builder<PlanNode> rewrittenSources = ImmutableList.builder();
for (PlanNode source : node.getSources()) {
rewrittenSources.add(context.rewrite(source));
}
return rewrittenSources;
}
@Override
public PlanNode visitTableWriter(TableWriterNode node, RewriteContext<Void> context)
{
PlanNode source = context.rewrite(node.getSource());
// Intentionally does not use canonicalizeAndDistinct as that would remove columns
ImmutableList<Symbol> columns = node.getColumns().stream()
.map(this::canonicalize)
.collect(toImmutableList());
return new TableWriterNode(
node.getId(),
source,
node.getTarget(),
columns,
node.getColumnNames(),
node.getOutputSymbols(),
node.getPartitioningScheme().map(partitioningScheme -> canonicalizePartitionFunctionBinding(partitioningScheme, source)));
}
@Override
protected PlanNode visitPlan(PlanNode node, RewriteContext<Void> context)
{
throw new UnsupportedOperationException("Unsupported plan node " + node.getClass().getSimpleName());
}
private void map(Symbol symbol, Symbol canonical)
{
Preconditions.checkArgument(!symbol.equals(canonical), "Can't map symbol to itself: %s", symbol);
mapping.put(symbol, canonical);
}
private Assignments canonicalize(Assignments oldAssignments)
{
Map<Expression, Symbol> computedExpressions = new HashMap<>();
Assignments.Builder assignments = Assignments.builder();
for (Map.Entry<Symbol, Expression> entry : oldAssignments.getMap().entrySet()) {
Expression expression = canonicalize(entry.getValue());
if (expression instanceof SymbolReference) {
// Always map a trivial symbol projection
Symbol symbol = Symbol.from(expression);
if (!symbol.equals(entry.getKey())) {
map(entry.getKey(), symbol);
}
}
else if (DeterminismEvaluator.isDeterministic(expression) && !(expression instanceof NullLiteral)) {
// Try to map same deterministic expressions within a projection into the same symbol
// Omit NullLiterals since those have ambiguous types
Symbol computedSymbol = computedExpressions.get(expression);
if (computedSymbol == null) {
// If we haven't seen the expression before in this projection, record it
computedExpressions.put(expression, entry.getKey());
}
else {
// If we have seen the expression before and if it is deterministic
// then we can rewrite references to the current symbol in terms of the parallel computedSymbol in the projection
map(entry.getKey(), computedSymbol);
}
}
Symbol canonical = canonicalize(entry.getKey());
assignments.put(canonical, expression);
}
return assignments.build();
}
private Optional<Symbol> canonicalize(Optional<Symbol> symbol)
{
if (symbol.isPresent()) {
return Optional.of(canonicalize(symbol.get()));
}
return Optional.empty();
}
private Symbol canonicalize(Symbol symbol)
{
Symbol canonical = symbol;
while (mapping.containsKey(canonical)) {
canonical = mapping.get(canonical);
}
return canonical;
}
private Expression canonicalize(Expression value)
{
return ExpressionTreeRewriter.rewriteWith(new ExpressionRewriter<Void>()
{
@Override
public Expression rewriteSymbolReference(SymbolReference node, Void context, ExpressionTreeRewriter<Void> treeRewriter)
{
Symbol canonical = canonicalize(Symbol.from(node));
return canonical.toSymbolReference();
}
}, value);
}
private List<Symbol> canonicalizeAndDistinct(List<Symbol> outputs)
{
Set<Symbol> added = new HashSet<>();
ImmutableList.Builder<Symbol> builder = ImmutableList.builder();
for (Symbol symbol : outputs) {
Symbol canonical = canonicalize(symbol);
if (added.add(canonical)) {
builder.add(canonical);
}
}
return builder.build();
}
private WindowNode.Specification canonicalizeAndDistinct(WindowNode.Specification specification)
{
ImmutableMap.Builder<Symbol, SortOrder> orderings = ImmutableMap.builder();
for (Map.Entry<Symbol, SortOrder> entry : specification.getOrderings().entrySet()) {
orderings.put(canonicalize(entry.getKey()), entry.getValue());
}
return new WindowNode.Specification(
canonicalizeAndDistinct(specification.getPartitionBy()),
canonicalizeAndDistinct(specification.getOrderBy()),
orderings.build());
}
private Set<Symbol> canonicalize(Set<Symbol> symbols)
{
return symbols.stream()
.map(this::canonicalize)
.collect(toImmutableSet());
}
private List<JoinNode.EquiJoinClause> canonicalizeJoinCriteria(List<JoinNode.EquiJoinClause> criteria)
{
ImmutableList.Builder<JoinNode.EquiJoinClause> builder = ImmutableList.builder();
for (JoinNode.EquiJoinClause clause : criteria) {
builder.add(new JoinNode.EquiJoinClause(canonicalize(clause.getLeft()), canonicalize(clause.getRight())));
}
return builder.build();
}
private List<IndexJoinNode.EquiJoinClause> canonicalizeIndexJoinCriteria(List<IndexJoinNode.EquiJoinClause> criteria)
{
ImmutableList.Builder<IndexJoinNode.EquiJoinClause> builder = ImmutableList.builder();
for (IndexJoinNode.EquiJoinClause clause : criteria) {
builder.add(new IndexJoinNode.EquiJoinClause(canonicalize(clause.getProbe()), canonicalize(clause.getIndex())));
}
return builder.build();
}
private ListMultimap<Symbol, Symbol> canonicalizeSetOperationSymbolMap(ListMultimap<Symbol, Symbol> setOperationSymbolMap)
{
ImmutableListMultimap.Builder<Symbol, Symbol> builder = ImmutableListMultimap.builder();
Set<Symbol> addedSymbols = new HashSet<>();
for (Map.Entry<Symbol, Collection<Symbol>> entry : setOperationSymbolMap.asMap().entrySet()) {
Symbol canonicalOutputSymbol = canonicalize(entry.getKey());
if (addedSymbols.add(canonicalOutputSymbol)) {
builder.putAll(canonicalOutputSymbol, Iterables.transform(entry.getValue(), this::canonicalize));
}
}
return builder.build();
}
private PartitioningScheme canonicalizePartitionFunctionBinding(PartitioningScheme scheme, PlanNode source)
{
Set<Symbol> addedOutputs = new HashSet<>();
ImmutableList.Builder<Symbol> outputs = ImmutableList.builder();
for (Symbol symbol : source.getOutputSymbols()) {
Symbol canonicalOutput = canonicalize(symbol);
if (addedOutputs.add(canonicalOutput)) {
outputs.add(canonicalOutput);
}
}
return new PartitioningScheme(
scheme.getPartitioning().translate(this::canonicalize),
outputs.build(),
canonicalize(scheme.getHashColumn()),
scheme.isReplicateNullsAndAny(),
scheme.getBucketToPartition());
}
}
}
| apache-2.0 |
consulo/consulo | modules/base/lang-impl/src/main/java/com/intellij/codeInsight/hint/InspectionDescriptionLinkHandler.java | 2468 | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.hint;
import com.intellij.codeInsight.highlighting.TooltipLinkHandler;
import com.intellij.codeInspection.InspectionProfile;
import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import consulo.logging.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.profile.codeInspection.InspectionProfileManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import javax.annotation.Nonnull;
/**
* Handles tooltip links in format <code>#inspection/inspection_short_name</code>.
* On a click or expend acton returns more detailed description for given inspection.
*
* @author peter
*/
public class InspectionDescriptionLinkHandler extends TooltipLinkHandler {
private static final Logger LOG = Logger.getInstance(InspectionDescriptionLinkHandler.class);
@Override
public String getDescription(@Nonnull final String refSuffix, @Nonnull final Editor editor) {
final Project project = editor.getProject();
if (project == null) {
LOG.error(editor);
return null;
}
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if (file == null) {
return null;
}
final InspectionProfile profile = (InspectionProfile)InspectionProfileManager.getInstance().getRootProfile();
final InspectionToolWrapper toolWrapper = profile.getInspectionTool(refSuffix, file);
if (toolWrapper == null) return null;
String description = toolWrapper.loadDescription();
if (description == null) {
LOG.warn("No description for inspection '" + refSuffix + "'");
description = InspectionsBundle.message("inspection.tool.description.under.construction.text");
}
return description;
}
}
| apache-2.0 |
andrea-colleoni/corso-lutech | EsempioIoC/src/it/lutech/corso/Client.java | 265 | package it.lutech.corso;
public class Client {
Contratto cc;
void usaContratto() {
System.out.println(cc.metodo(10, "pippo"));
}
public Contratto getCc() {
return cc;
}
public void setCc(Contratto cc) {
this.cc = cc;
}
}
| apache-2.0 |
vtemian/uni-west | third_year/gui/test-jogl/src/edu/jogl/HelloWorldDemo.java | 52 | package edu.jogl;
public class HelloWorldDemo {
}
| apache-2.0 |
tiarebalbi/spring-data-dynamodb | src/test/java/org/socialsignin/spring/data/dynamodb/marshaller/Instant2IsoDynamoDBMarshallerTest.java | 1914 | /**
* Copyright © 2018 spring-data-dynamodb (https://github.com/boostchicken/spring-data-dynamodb)
*
* 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.socialsignin.spring.data.dynamodb.marshaller;
import org.junit.Before;
import org.junit.Test;
import java.time.Instant;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class Instant2IsoDynamoDBMarshallerTest {
private Instant2IsoDynamoDBMarshaller underTest;
@Before
public void setUp() {
underTest = new Instant2IsoDynamoDBMarshaller();
}
@Test
public void testNullMarshall() {
String actual = underTest.marshall(null);
assertNull(actual);
}
@Test
public void testMarshall() {
assertEquals("1970-01-01T00:00:00.000Z", underTest.marshall(Instant.ofEpochMilli(0)));
assertEquals("1970-01-01T00:00:00.000Z", underTest.convert(Instant.ofEpochMilli(0)));
}
@Test
public void testUnmarshallNull() {
Instant actual = underTest.unmarshall(Instant.class, null);
assertNull(actual);
}
@Test
public void testUnmarshall() {
assertEquals(Instant.ofEpochMilli(0), underTest.unmarshall(Instant.class, "1970-01-01T00:00:00.000Z"));
assertEquals(Instant.ofEpochMilli(0), underTest.unconvert("1970-01-01T00:00:00.000Z"));
}
@Test(expected = RuntimeException.class)
public void testUnmarshallGarbage() {
underTest.unmarshall(Instant.class, "something");
}
}
| apache-2.0 |
murick/Algorithms | Java/src/main/java/hash/math/collatz/Solution1.java | 2268 | /*
* Copyright (C) 2015 Imran Mammadli
*
* 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 hash.math.collatz;
import java.util.HashSet;
public class Solution1
{
/**
* Tests the Collatz Conjecture for all numbers up to the specified number
*
* @param number the upper limit
* @return true, if conjecture holds for all the numbers up to the given one, otherwise false
* @throws ArithmeticException if the checked number is too big to be represented
*
* @see <a href="http://en.wikipedia.org/wiki/Collatz_conjecture">Collatz Conjecture</a>
*
* @time <i>Ω(n)</i>
* @space <i>Ω(n)</i>
**/
public static boolean checkCollatz(long number)
{
// all the odd numbers that were verified to converge
HashSet<Long> checked_numbers = new HashSet<Long>();
for (long i = 2; i <= number; i++)
{
// numbers encountered so far for the given value of i
HashSet<Long> sequence = new HashSet<Long>();
long current = i;
// all numbers up to i already tested
while (current >= i)
{
// the sequence falls into a loop, which is not 4-2-1
if (sequence.contains(current))
{
return false; // never happens :)
}
sequence.add(current);
// current number is odd
if ((current % 2) == 1)
{
// the number was already encountered
if (checked_numbers.contains(current))
{
break;
}
long next = current * 3 + 1;
// the next number is going to bee too big
if (next <= current)
{
throw new ArithmeticException("The number is too big");
}
checked_numbers.add(current);
current = next;
}
//current number is even
else
{
current /= 2;
}
}
}
return true;
}
} | apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-videointelligence/v1p2beta1/1.31.0/com/google/api/services/videointelligence/v1p2beta1/model/GoogleCloudVideointelligenceV1p2beta1LogoRecognitionAnnotation.java | 4910 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.videointelligence.v1p2beta1.model;
/**
* Annotation corresponding to one detected, tracked and recognized logo class.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Video Intelligence API. For a detailed
* explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudVideointelligenceV1p2beta1LogoRecognitionAnnotation extends com.google.api.client.json.GenericJson {
/**
* Entity category information to specify the logo class that all the logo tracks within this
* LogoRecognitionAnnotation are recognized as.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudVideointelligenceV1p2beta1Entity entity;
/**
* All video segments where the recognized logo appears. There might be multiple instances of the
* same logo class appearing in one VideoSegment.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudVideointelligenceV1p2beta1VideoSegment> segments;
/**
* All logo tracks where the recognized logo appears. Each track corresponds to one logo instance
* appearing in consecutive frames.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudVideointelligenceV1p2beta1Track> tracks;
/**
* Entity category information to specify the logo class that all the logo tracks within this
* LogoRecognitionAnnotation are recognized as.
* @return value or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p2beta1Entity getEntity() {
return entity;
}
/**
* Entity category information to specify the logo class that all the logo tracks within this
* LogoRecognitionAnnotation are recognized as.
* @param entity entity or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p2beta1LogoRecognitionAnnotation setEntity(GoogleCloudVideointelligenceV1p2beta1Entity entity) {
this.entity = entity;
return this;
}
/**
* All video segments where the recognized logo appears. There might be multiple instances of the
* same logo class appearing in one VideoSegment.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudVideointelligenceV1p2beta1VideoSegment> getSegments() {
return segments;
}
/**
* All video segments where the recognized logo appears. There might be multiple instances of the
* same logo class appearing in one VideoSegment.
* @param segments segments or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p2beta1LogoRecognitionAnnotation setSegments(java.util.List<GoogleCloudVideointelligenceV1p2beta1VideoSegment> segments) {
this.segments = segments;
return this;
}
/**
* All logo tracks where the recognized logo appears. Each track corresponds to one logo instance
* appearing in consecutive frames.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudVideointelligenceV1p2beta1Track> getTracks() {
return tracks;
}
/**
* All logo tracks where the recognized logo appears. Each track corresponds to one logo instance
* appearing in consecutive frames.
* @param tracks tracks or {@code null} for none
*/
public GoogleCloudVideointelligenceV1p2beta1LogoRecognitionAnnotation setTracks(java.util.List<GoogleCloudVideointelligenceV1p2beta1Track> tracks) {
this.tracks = tracks;
return this;
}
@Override
public GoogleCloudVideointelligenceV1p2beta1LogoRecognitionAnnotation set(String fieldName, Object value) {
return (GoogleCloudVideointelligenceV1p2beta1LogoRecognitionAnnotation) super.set(fieldName, value);
}
@Override
public GoogleCloudVideointelligenceV1p2beta1LogoRecognitionAnnotation clone() {
return (GoogleCloudVideointelligenceV1p2beta1LogoRecognitionAnnotation) super.clone();
}
}
| apache-2.0 |
songzhw/AndroidArchitecture | deprecated/DataBindingDemo/app/src/main/java/ca/six/bindingdemo/tmp/User.java | 2433 | package ca.six.bindingdemo.tmp;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.databinding.ObservableBoolean;
import android.databinding.ObservableField;
import android.databinding.ObservableInt;
import ca.six.bindingdemo.BR;
/**
* Created by songzhw on 2017-02-18
*/
public class User extends BaseObservable {
public ObservableField<String> name = new ObservableField<>();
public ObservableField<String> desp = new ObservableField<>();
public ObservableBoolean isMale = new ObservableBoolean();
public ObservableInt avatar = new ObservableInt();
public User(String name, String desp, boolean isMale, int avatar) {
this.desp.set(desp);
this.isMale.set(isMale);
this.name.set(name);
this.avatar.set(avatar);
}
@Override
public String toString() {
return "TmpUser{" +
"name=" + name.get() +
", desp=" + desp.get() +
", isMale=" + isMale.get() +
", avatar=" + avatar.get() +
'}';
}
}
//public class User extends BaseObservable {
// public String name;
// public String desp;
// public boolean isMale;
// public int avatar;
//
// public User(String name, String desp, boolean isMale, int avatar ) {
// this.desp = desp;
// this.isMale = isMale;
// this.name = name;
// this.avatar = avatar;
// }
//
// @Override
// public String toString() {
// return "User{" +
// "avatar=" + avatar +
// ", name='" + name + '\'' +
// ", desp='" + desp + '\'' +
// ", isMale=" + isMale +
// '}';
// }
//
// public void setDesp(String desp) {
// this.desp = desp;
// notifyPropertyChanged(BR.desp);
// }
//
// public void setIsMale(boolean male) {
// isMale = male;
// notifyPropertyChanged(BR.male);
// }
//
// public void setName(String name) {
// this.name = name;
// notifyPropertyChanged(BR.name);
// }
//
// @Bindable
// public String getDesp() {
// return desp;
// }
//
// @Bindable
// public boolean isMale() {
// return isMale;
// }
//
// @Bindable
// public String getName() {
// return name;
// }
//
// @Bindable
// public int getAvatar(){
// return avatar;
// }
//}
| apache-2.0 |
CapGeekMini/guava-training | src/test/java/capgemini/training/guava/train/TrainGuavaTest.java | 2862 | package capgemini.training.guava.train;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class TrainGuavaTest {
TrainGuava training;
@Before
public void before() {
training = new TrainGuava();
}
@Test(expected=NullPointerException.class)
public void testCheckNotNull() {
training.checkNotNull(null);
}
@Test(expected=IllegalArgumentException.class)
public void testCheckArgument() {
training.checkArgument("");
}
@Test
public void testPrefix() {
assertEquals("", training.prefix("abcdefgh", "ijklmnop"));
assertEquals("TL_", training.prefix("TL_Snute", "TL_Happy"));
assertEquals("C'est pas ", training.prefix("C'est pas faux", "C'est pas sorcier"));
}
@Test
public void testOrderingNatural() {
List<String> expected = Lists.newArrayList(null, null, "ananas", "anunas", "goyabe", "goyave", "orange", "pamplemousse", "pomme");
assertEquals(expected, training.orderingNatural(Lists.newArrayList("orange", null, "pomme", "pamplemousse", "goyave", null, "ananas", "goyabe", "anunas")));
}
@Test
public void testOrdering() {
List<String> expected = Lists.newArrayList(null, null, "pomme", "ananas", "anunas", "goyabe", "goyave", "orange", "pamplemousse");
assertEquals(expected, training.ordering(Lists.newArrayList("orange", null, "pomme", "pamplemousse", "goyave", null, "ananas", "goyabe", "anunas")));
}
@Test
public void testFilter() {
List<String> expected = Lists.newArrayList("pomme", "orange", "pamplemousse");
assertTrue(Iterables.elementsEqual(expected, training.filter(ImmutableList.of("pomme", "ananas", "goyave", "orange", "pamplemousse"), ImmutableList.of("ananas", "goyave"))));
}
@Test
public void testTransform() {
List<Integer> expected = Lists.newArrayList(5, 6, 6, 6, 12);
assertTrue(Iterables.elementsEqual(expected, training.transform(Lists.newArrayList("pomme", "ananas", "goyave", "orange", "pamplemousse"))));
}
@Test
public void testCompress() {
List<String> values = Lists.newArrayList("a", null, "a", "a", "b", null, "c", "c", null, "d", "e", "f", null, "f", null, null, "f", "f");
assertEquals(Lists.newArrayList("a", "b", "c", "d", "e", "f"), Lists.newArrayList(training.compress(values)));
}
@Test
public void testCounter() {
Map<String, Integer> expected = ImmutableMap.of("a", new Integer(6), "b", new Integer(1), "c", new Integer(2), "d", new Integer(1), "e", new Integer(4));
assertEquals(expected, training.counter(Lists.newArrayList("a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e")));
}
}
| apache-2.0 |
amitkma/android-architecture-boilerplate | presentation/src/main/java/com/github/amitkma/boilerplate/presentation/vo/UserView.java | 834 | /*
* Copyright 2017 Amit Kumar.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.amitkma.boilerplate.presentation.vo;
public class UserView {
public int id;
public String name;
public String email;
public String coverUrl;
public String description;
public int followers;
}
| apache-2.0 |
android-libraries/android_intents | library/src/androidTest/java/com/albedinsky/android/intent/PlayIntentTest.java | 2280 | /*
* =================================================================================================
* Copyright (C) 2015 Martin Albedinsky
* =================================================================================================
* Licensed under the Apache License, Version 2.0 or later (further "License" only).
* -------------------------------------------------------------------------------------------------
* You may use this file only in compliance with the License. More details and copy of this License
* you may obtain at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* You can redistribute, modify or publish any part of the code written within this file but as it
* is described in the License, the software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES or CONDITIONS OF ANY KIND.
*
* See the License for the specific language governing permissions and limitations under the License.
* =================================================================================================
*/
package com.albedinsky.android.intent;
import android.content.Intent;
import android.net.Uri;
/**
* @author Martin Albedinsky
*/
public final class PlayIntentTest extends IntentBaseTest<PlayIntent> {
@SuppressWarnings("unused")
private static final String TAG = "PlayIntentTest";
public PlayIntentTest() {
super(PlayIntent.class);
}
public void testDefaultPackageName() {
final String packageName = mIntent.packageName();
assertNotNull(packageName);
assertEquals(getActivity().getPackageName(), packageName);
}
public void testPackageName() {
mIntent.packageName("com.google.android.inbox");
assertEquals("com.google.android.inbox", mIntent.packageName());
}
public void testBuild() {
mIntent.packageName("com.google.android.inbox");
final Intent intent = mIntent.build();
assertNotNull(intent);
assertEquals(Intent.ACTION_VIEW, intent.getAction());
assertEquals(Uri.parse(PlayIntent.VIEW_URL_BASE + "com.google.android.inbox"), intent.getData());
}
public void testBuildWithInvalidPackageName() {
mIntent.packageName("");
assertBuildThrowsExceptionWithCause(
mIntent,
"No package name specified."
);
}
} | apache-2.0 |
NovaOrdis/series | src/main/java/com/novaordis/series/Series.java | 2927 | package com.novaordis.series;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
/**
* A list of timestamped lists of metrics.
*
* @author <a href="mailto:ovidiu@novaordis.com">Ovidiu Feodorov</a>
*
* Copyright 2012 Nova Ordis LLC
*/
public interface Series
{
// Accessors -------------------------------------------------------------------------------------------------------
String getName();
long getBeginTime();
long getEndTime();
/**
* @return the number of rows in the series.
*/
long getCount();
boolean isEmpty();
/**
* If the series is header-less, it will return an "empty" headers instance.
*
* If a non-empty list is returned, it DOES NOT include a header for the row's timestamp, which is always present
* at the beginning of the row and it is handled differently than the rest of the metrics in the row.
*
* It is up to the implementation to return the underlying list or a copy; consult the implementation documentation
* for more details.
*/
List<Header> getHeaders();
Iterator<Row> iterator();
/**
* The output timestamp format for this series. If the series was loaded from external storage, this method usually
* returns the original timestamp format. The implementations are encouraged to build log messages that include time
* stamps using this format. May return null (no default timestamp format), in which case
* Configuration.TIMESTAMP_FORMAT will be used.
*/
SimpleDateFormat getTimestampFormat();
// Mutators --------------------------------------------------------------------------------------------------------
/**
* @throws IllegalStateException thrown if the series has rows already. New headers cannot be installed if rows were
* previously added to the series, because the existing rows might not match the headers, resulting into a invalid
* hstate series.
*/
void setHeaders(List<Header> headers) throws Exception;
/**
* If headers exist, the metrics will be matched against headers.
*
* @throws Exception on type mismatch between headers (if present) and the row elements.
*/
void add(long timestamp, Metric... metrics) throws Exception;
/**
* If headers exist, the metrics will be matched against headers.
*
* @throws Exception on type mismatch between headers (if present) and the row elements.
*/
void add(long timestamp, List<Metric> metrics) throws Exception;
/**
* If headers exist, the metrics will be matched against headers.
*
* @throws Exception on type mismatch between headers (if present) and the row elements.
*/
void add(Row r) throws Exception;
void setTimestampFormat(SimpleDateFormat f);
}
| apache-2.0 |
LifeLogTLeaf/TLeafDiaryAndroid | src/com/tleaf/tiary/template/ChatAdapter.java | 2223 | package com.tleaf.tiary.template;
import java.util.ArrayList;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.tleaf.tiary.R;
import com.tleaf.tiary.model.Message;
/** 채팅 리스트뷰를 대화로 채워주는 리스트뷰 어답터 **/
public class ChatAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Message> msgArr = new ArrayList<Message>();
public ChatAdapter(Context context, ArrayList<Message> messages) {
this.mContext = context;
this.msgArr = messages;
}
@Override
public int getCount() {
return msgArr.size();
}
@Override
public Object getItem(int position) {
return msgArr.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Message message = (Message) this.getItem(position);
ViewHolder holder;
if(convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_chat, parent, false);
holder.message = (TextView) convertView.findViewById(R.id.txt_chat);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.message.setText(message.getMessage());
LayoutParams lp = (LayoutParams) holder.message.getLayoutParams();
if(message.isStatusMessage()) {
holder.message.setBackgroundDrawable(null);
lp.gravity = Gravity.LEFT;
holder.message.setTextColor(mContext.getResources().getColor(R.color.point));
} else {
if(message.isMine()) {
holder.message.setBackgroundResource(R.drawable.bubble_white);
lp.gravity = Gravity.RIGHT;
} else {
holder.message.setBackgroundResource(R.drawable.bubble_skyblue_grey_left);
lp.gravity = Gravity.LEFT; }
holder.message.setLayoutParams(lp);
holder.message.setTextColor(mContext.getResources().getColor(R.color.diary_content));
}
return convertView;
}
private class ViewHolder
{
TextView message;
}
}
| apache-2.0 |
Netflix/astyanax | astyanax-cassandra/src/main/java/com/netflix/astyanax/serializers/TypeInferringSerializer.java | 1626 | /**
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.astyanax.serializers;
import java.nio.ByteBuffer;
import com.netflix.astyanax.Serializer;
/**
* A serializer that dynamically delegates to a proper serializer based on the
* value passed
*
* @author Bozhidar Bozhanov
*
* @param <T>
* type
*/
public class TypeInferringSerializer<T> extends AbstractSerializer<T> implements Serializer<T> {
@SuppressWarnings("rawtypes")
private static final TypeInferringSerializer instance = new TypeInferringSerializer();
@SuppressWarnings("unchecked")
public static <T> TypeInferringSerializer<T> get() {
return instance;
}
@Override
public ByteBuffer toByteBuffer(T obj) {
return SerializerTypeInferer.getSerializer(obj).toByteBuffer(obj);
}
@Override
public T fromByteBuffer(ByteBuffer byteBuffer) {
throw new IllegalStateException(
"The type inferring serializer can only be used for data going to the database, and not data coming from the database");
}
}
| apache-2.0 |
pillingworthz/android-snowball | app/src/main/java/uk/co/threeonefour/android/snowball/gamestate/FileGameStateDao.java | 9382 | /**
* Copyright 2014 Paul Illingworth
*
* 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 uk.co.threeonefour.android.snowball.gamestate;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import uk.co.threeonefour.android.snowball.basics.io.IOUtils;
import uk.co.threeonefour.android.snowball.level9j.vm.GameState;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;
public class FileGameStateDao implements GameStateDao {
private static final String LOGTAG = FileGameStateDao.class.getName();
private static final String SERIALISED_FILENAME_EXTENSION = "ser";
private static final String JSON_FILENAME_EXTENSION = "json";
private static final String PNG_FILENAME_EXTENSION = "png";
private static final String SUMMARY_SUFFIX = "_summary";
private static final String STATE_SUFFIX = "_vmstate";
private static final String GRAPHICS_SUFFIX = "_graphics";
private static final int MAX_SLOTS = 6;
private final Activity activity;
public FileGameStateDao(Activity activity) {
this.activity = activity;
}
@Override
public void save(GameStateSummary gameStateSummary, GameState gameState, Bitmap graphics) {
int slot = gameStateSummary.getSlot();
String filename = getSummaryFilename(slot);
OutputStream fos = null;
try {
Log.i(LOGTAG, " saveFile " + filename);
fos = activity.openFileOutput(filename, Context.MODE_PRIVATE);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(fos, "UTF-8"));
String str = gameStateSummary.toJson().toString();
writer.write(str);
writer.close();
} catch (IOException e) {
Log.e(LOGTAG, "Failed to save game state summary for " + slot, e);
} finally {
IOUtils.closeQuietly(fos);
}
filename = getStateFilename(slot);
fos = null;
try {
Log.i(LOGTAG, " saveFile " + filename);
fos = activity.openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(gameState);
oos.close();
} catch (IOException e) {
Log.e(LOGTAG, "Failed to save game state for " + slot, e);
} finally {
IOUtils.closeQuietly(fos);
}
filename = getGraphicsFilename(slot);
if (graphics == null) {
deleteFile(filename);
} else {
fos = null;
try {
Log.i(LOGTAG, " saveFile " + filename);
fos = activity.openFileOutput(filename, Context.MODE_PRIVATE);
graphics.compress(CompressFormat.PNG, 100, fos);
} catch (IOException e) {
Log.e(LOGTAG, "Failed to save preview for " + slot, e);
} finally {
IOUtils.closeQuietly(fos);
}
}
}
@Override
public void copy(GameStateSummary from, GameStateSummary to) {
int fromSlot = from.getSlot();
int toSlot = to.getSlot();
clear(toSlot);
copyFile(getSummaryFilename(fromSlot), getSummaryFilename(toSlot));
copyFile(getStateFilename(fromSlot), getStateFilename(toSlot));
copyFile(getGraphicsFilename(fromSlot), getGraphicsFilename(toSlot));
}
private void copyFile(String from, String to) {
Log.i(LOGTAG, " copyFile from " + from + " to " + to);
InputStream fis = null;
OutputStream fos = null;
try {
fis = activity.openFileInput(from);
fos = activity.openFileOutput(to, Context.MODE_PRIVATE);
IOUtils.copy(fis, fos);
} catch (IOException e) {
Log.e(LOGTAG, "Failed to copy file from " + from + " to " + to, e);
} finally {
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(fos);
}
}
private void deleteFile(String filename) {
Log.i(LOGTAG, " deleteFile " + filename);
activity.deleteFile(filename);
}
@Override
public void clear(int slot) {
Log.i(LOGTAG, "Clearing slot + " + slot);
deleteFile(getSummaryFilename(slot));
deleteFile(getStateFilename(slot));
deleteFile(getGraphicsFilename(slot));
}
@Override
public GameState loadLatest() {
List<GameStateSummary> infos = listSavedGames();
if (!infos.isEmpty()) {
GameStateSummary info = infos.get(infos.size() - 1);
return loadGameState(info.getSlot());
}
return null;
}
@Override
public GameState loadGameState(int slot) {
String filename = getStateFilename(slot);
InputStream fis = null;
try {
Log.i(LOGTAG, " loadFile " + filename);
fis = activity.openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
GameState gameState = (GameState) ois.readObject();
ois.close();
return gameState;
} catch (FileNotFoundException e) {
Log.i(LOGTAG, "Failed to find game state file for " + slot);
} catch (IOException e) {
Log.e(LOGTAG, "Failed to load game state file for " + slot, e);
} catch (ClassNotFoundException e) {
Log.e(LOGTAG, "Failed to load game state file for " + slot, e);
} finally {
if (fis != null) {
IOUtils.closeQuietly(fis);
}
}
return null;
}
@Override
public GameStateSummary loadGameStateSummary(int slot) {
String filename = getSummaryFilename(slot);
InputStream fis = null;
try {
Log.i(LOGTAG, " loadFile " + filename);
fis = activity.openFileInput(filename);
StringWriter sw = new StringWriter();
InputStreamReader isr = new InputStreamReader(fis);
IOUtils.copy(isr, sw);
JSONObject jo = new JSONObject(sw.toString());
GameStateSummary gameStateSummary = GameStateSummary.fromJson(jo);
if (gameStateSummary != null) {
gameStateSummary.setSlot(slot);
}
return gameStateSummary;
} catch (FileNotFoundException e) {
Log.i(LOGTAG, "Failed to find game state summary for " + slot);
} catch (IOException e) {
Log.e(LOGTAG, "Failed to load game state summary for " + slot, e);
} catch (JSONException e) {
Log.e(LOGTAG, "Failed to load game state summary for " + slot, e);
} finally {
if (fis != null) {
IOUtils.closeQuietly(fis);
}
}
return null;
}
public Bitmap loadGraphics(int slot) {
String filename = getGraphicsFilename(slot);
InputStream fis = null;
try {
Log.i(LOGTAG, " loadFile " + filename);
fis = activity.openFileInput(filename);
Bitmap bitmap = BitmapFactory.decodeStream(fis);
return bitmap;
} catch (FileNotFoundException e) {
Log.i(LOGTAG, "Failed to find preview for " + slot);
} finally {
if (fis != null) {
IOUtils.closeQuietly(fis);
}
}
return null;
}
@Override
public List<GameStateSummary> listSavedGames() {
List<GameStateSummary> infos = new ArrayList<GameStateSummary>();
for (int slot = 0; slot < MAX_SLOTS; slot++) {
GameStateSummary info = loadGameStateSummary(slot);
if (info != null) {
infos.add(info);
} else {
infos.add(new GameStateSummary(slot, 0, null));
}
}
return infos;
}
public static String getId(int slot) {
return "slot" + slot;
}
public static String getSummaryFilename(int slot) {
return "slot_" + slot + SUMMARY_SUFFIX + "." + JSON_FILENAME_EXTENSION;
}
public static String getStateFilename(int slot) {
return "slot_" + slot + STATE_SUFFIX + "." + SERIALISED_FILENAME_EXTENSION;
}
public static String getGraphicsFilename(int slot) {
return "slot_" + slot + GRAPHICS_SUFFIX + "." + PNG_FILENAME_EXTENSION;
}
}
| apache-2.0 |
everttigchelaar/camel-svn | components/camel-csv/src/test/java/org/apache/camel/dataformat/csv/CsvMarshalTest.java | 2741 | /**
* 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.camel.dataformat.csv;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
/**
* @version
*/
public class CsvMarshalTest extends CamelTestSupport {
@Test
public void testCsvMarshal() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
Map<String, Object> row1 = new LinkedHashMap<String, Object>();
row1.put("orderId", 123);
row1.put("item", "Camel in Action");
row1.put("amount", 1);
data.add(row1);
Map<String, Object> row2 = new LinkedHashMap<String, Object>();
row2.put("orderId", 124);
row2.put("item", "ActiveMQ in Action");
row2.put("amount", 2);
data.add(row2);
template.sendBody("direct:toCsv", data);
assertMockEndpointsSatisfied();
String body = mock.getReceivedExchanges().get(0).getIn().getBody(String.class);
String[] lines = body.split("\n");
assertEquals("There should be 2 rows", 2, lines.length);
assertEquals("123,Camel in Action,1", lines[0]);
assertEquals("124,ActiveMQ in Action,2", lines[1]);
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:toCsv")
.marshal().csv()
.convertBodyTo(String.class)
.to("mock:result");
}
};
}
}
| apache-2.0 |
jjrobinson/Reddit-DailyProgrammer | src/challenge291/Chair.java | 703 | /*
* 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 challenge291;
/**
*
* @author robinsj1
*/
public class Chair {
private int weight;
private int temp;
public int getWeight() {
return weight;
}
public Chair(int w, int t){
this.weight = w;
this.temp = t;
}
public void setWeight(int seat) {
this.weight = seat;
}
public int getTemp() {
return temp;
}
public void setTemp(int temp) {
this.temp = temp;
}
}
| apache-2.0 |
nfalco79/tools-ant | src/test/java/com/github/nfalco79/tools/ant/taskdefs/FreePortTest.java | 1510 | /*
* Copyright 2017 Nikolas Falco
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.github.nfalco79.tools.ant.taskdefs;
import static org.junit.Assert.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import org.apache.tools.ant.Project;
import org.junit.Test;
import com.github.nfalco79.tools.ant.taskdefs.FreePort;
public class FreePortTest {
@Test
public void get_free_port() throws Exception {
String fpPropName = "freeport";
Project project = AntUtil.createEmptyProject();
FreePort task = new FreePort();
task.setProject(project);
task.setProperty(fpPropName);
task.execute();
String fpPropValue = project.getProperty(fpPropName);
assertNotNull(fpPropValue);
Integer port = Integer.valueOf(fpPropValue);
assertTrue(port > 0);
Socket socket = new Socket();
try {
socket.bind(new InetSocketAddress(port));
} catch (IOException e) {
fail(e.getMessage());
} finally {
socket.close();
}
}
}
| apache-2.0 |
christophwidulle/Raclette | raclette-ext-rx/src/main/java/de/chefkoch/raclette/rx/lifecycle/RxViewModelLifecycle.java | 5353 | package de.chefkoch.raclette.rx.lifecycle;
import de.chefkoch.raclette.ViewModelLifecycleState;
import rx.Observable;
import rx.exceptions.Exceptions;
import rx.functions.Func1;
import rx.functions.Func2;
/**
* thx to https://github.com/trello/RxLifecycle
*
* Created by christophwidulle on 15.04.16.
*/
public class RxViewModelLifecycle {
public static <T> Observable.Transformer<T, T> bindUntilEvent(final Observable<ViewModelLifecycleState> lifecycle, final ViewModelLifecycleState event) {
return bind(lifecycle, event);
}
private static <T, R> Observable.Transformer<T, T> bind(final Observable<R> lifecycle, final R event) {
if (lifecycle == null) {
throw new IllegalArgumentException("Lifecycle must be given");
} else if (event == null) {
throw new IllegalArgumentException("Event must be given");
}
return new Observable.Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> source) {
return source.takeUntil(
lifecycle.takeFirst(new Func1<R, Boolean>() {
@Override
public Boolean call(R lifecycleEvent) {
return lifecycleEvent == event;
}
})
);
}
};
}
public static <T> Observable.Transformer<T, T> bind(Observable<ViewModelLifecycleState> lifecycle) {
return bind(lifecycle, VIEWMODEL_LIFECYCLE);
}
private static <T, R> Observable.Transformer<T, T> bind(Observable<R> lifecycle,
final Func1<R, R> correspondingEvents) {
if (lifecycle == null) {
throw new IllegalArgumentException("Lifecycle must be given");
}
// Make sure we're truly comparing a single stream to itself
final Observable<R> sharedLifecycle = lifecycle.share();
// Keep emitting from source until the corresponding event occurs in the lifecycle
return new Observable.Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> source) {
return source.takeUntil(
Observable.combineLatest(
sharedLifecycle.take(1).map(correspondingEvents),
sharedLifecycle.skip(1),
new Func2<R, R, Boolean>() {
@Override
public Boolean call(R bindUntilEvent, R lifecycleEvent) {
return lifecycleEvent == bindUntilEvent;
}
})
.onErrorReturn(RESUME_FUNCTION)
.takeFirst(SHOULD_COMPLETE)
);
}
};
}
private static final Func1<Throwable, Boolean> RESUME_FUNCTION = new Func1<Throwable, Boolean>() {
@Override
public Boolean call(Throwable throwable) {
if (throwable instanceof OutsideLifecycleException) {
return true;
}
Exceptions.propagate(throwable);
return false;
}
};
private static final Func1<Boolean, Boolean> SHOULD_COMPLETE = new Func1<Boolean, Boolean>() {
@Override
public Boolean call(Boolean shouldComplete) {
return shouldComplete;
}
};
// Figures out which corresponding next lifecycle event in which to unsubscribe
private static final Func1<ViewModelLifecycleState, ViewModelLifecycleState> VIEWMODEL_LIFECYCLE =
new Func1<ViewModelLifecycleState, ViewModelLifecycleState>() {
@Override
public ViewModelLifecycleState call(ViewModelLifecycleState lastEvent) {
switch (lastEvent) {
case VIEWMODEL_CREATE:
return ViewModelLifecycleState.VIEWMODEL_DESTROY;
case CREATE:
return ViewModelLifecycleState.DESTROY;
case START:
return ViewModelLifecycleState.STOP;
case RESUME:
return ViewModelLifecycleState.PAUSE;
case PAUSE:
return ViewModelLifecycleState.STOP;
case STOP:
return ViewModelLifecycleState.DESTROY;
case DESTROY:
return ViewModelLifecycleState.VIEWMODEL_DESTROY;
case VIEWMODEL_DESTROY:
throw new OutsideLifecycleException("Cannot bind to ViewModel lifecycle when outside of it.");
default:
throw new UnsupportedOperationException("Binding to " + lastEvent + " not yet implemented");
}
}
};
private static class OutsideLifecycleException extends IllegalStateException {
public OutsideLifecycleException(String detailMessage) {
super(detailMessage);
}
}
}
| apache-2.0 |
ChristianNavolskyi/YCSB | geode/src/main/java/com/yahoo/ycsb/db/GeodeClient.java | 8357 | /**
* Copyright (c) 2013 - 2016 YCSB Contributors. All rights reserved.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.yahoo.ycsb.db;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.yahoo.ycsb.ByteArrayByteIterator;
import com.yahoo.ycsb.ByteIterator;
import com.yahoo.ycsb.DB;
import com.yahoo.ycsb.DBException;
import com.yahoo.ycsb.Status;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.CacheFactory;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionExistsException;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.pdx.JSONFormatter;
import org.apache.geode.pdx.PdxInstance;
import org.apache.geode.pdx.PdxInstanceFactory;
/**
* Apache Geode client for the YCSB benchmark.<br />
* <p>By default acts as a Geode client and tries to connect
* to Geode cache server running on localhost with default
* cache server port. Hostname and port of a Geode cacheServer
* can be provided using <code>geode.serverport=port</code> and <code>
* geode.serverhost=host</code> properties on YCSB command line.
* A locator may also be used for discovering a cacheServer
* by using the property <code>geode.locator=host[port]</code></p>
* <p>
* <p>To run this client in a peer-to-peer topology with other Geode
* nodes, use the property <code>geode.topology=p2p</code>. Running
* in p2p mode will enable embedded caching in this client.</p>
* <p>
* <p>YCSB by default does its operations against "usertable". When running
* as a client this is a <code>ClientRegionShortcut.PROXY</code> region,
* when running in p2p mode it is a <code>RegionShortcut.PARTITION</code>
* region. A cache.xml defining "usertable" region can be placed in the
* working directory to override these region definitions.</p>
*/
public class GeodeClient extends DB {
/**
* property name of the port where Geode server is listening for connections.
*/
private static final String SERVERPORT_PROPERTY_NAME = "geode.serverport";
/**
* property name of the host where Geode server is running.
*/
private static final String SERVERHOST_PROPERTY_NAME = "geode.serverhost";
/**
* default value of {@link #SERVERHOST_PROPERTY_NAME}.
*/
private static final String SERVERHOST_PROPERTY_DEFAULT = "localhost";
/**
* property name to specify a Geode locator. This property can be used in both
* client server and p2p topology
*/
private static final String LOCATOR_PROPERTY_NAME = "geode.locator";
/**
* property name to specify Geode topology.
*/
private static final String TOPOLOGY_PROPERTY_NAME = "geode.topology";
/**
* value of {@value #TOPOLOGY_PROPERTY_NAME} when peer to peer topology should be used.
* (client-server topology is default)
*/
private static final String TOPOLOGY_P2P_VALUE = "p2p";
/**
* Pattern to split up a locator string in the form host[port].
*/
private static final Pattern LOCATOR_PATTERN = Pattern.compile("(.+)\\[(\\d+)\\]");;
private GemFireCache cache;
/**
* true if ycsb client runs as a client to a Geode cache server.
*/
private boolean isClient;
@Override
public void init() throws DBException {
Properties props = getProperties();
// hostName where Geode cacheServer is running
String serverHost = null;
// port of Geode cacheServer
int serverPort = 0;
String locatorStr = null;
if (props != null && !props.isEmpty()) {
String serverPortStr = props.getProperty(SERVERPORT_PROPERTY_NAME);
if (serverPortStr != null) {
serverPort = Integer.parseInt(serverPortStr);
}
serverHost = props.getProperty(SERVERHOST_PROPERTY_NAME, SERVERHOST_PROPERTY_DEFAULT);
locatorStr = props.getProperty(LOCATOR_PROPERTY_NAME);
String topology = props.getProperty(TOPOLOGY_PROPERTY_NAME);
if (topology != null && topology.equals(TOPOLOGY_P2P_VALUE)) {
CacheFactory cf = new CacheFactory();
if (locatorStr != null) {
cf.set("locators", locatorStr);
}
cache = cf.create();
isClient = false;
return;
}
}
isClient = true;
ClientCacheFactory ccf = new ClientCacheFactory();
ccf.setPdxReadSerialized(true);
if (serverPort != 0) {
ccf.addPoolServer(serverHost, serverPort);
} else {
InetSocketAddress locatorAddress = getLocatorAddress(locatorStr);
ccf.addPoolLocator(locatorAddress.getHostName(), locatorAddress.getPort());
}
cache = ccf.create();
}
static InetSocketAddress getLocatorAddress(String locatorStr) {
Matcher matcher = LOCATOR_PATTERN.matcher(locatorStr);
if(!matcher.matches()) {
throw new IllegalStateException("Unable to parse locator: " + locatorStr);
}
return new InetSocketAddress(matcher.group(1), Integer.parseInt(matcher.group(2)));
}
@Override
public Status read(String table, String key, Set<String> fields,
Map<String, ByteIterator> result) {
Region<String, PdxInstance> r = getRegion(table);
PdxInstance val = r.get(key);
if (val != null) {
if (fields == null) {
for (String fieldName : val.getFieldNames()) {
result.put(fieldName, new ByteArrayByteIterator((byte[]) val.getField(fieldName)));
}
} else {
for (String field : fields) {
result.put(field, new ByteArrayByteIterator((byte[]) val.getField(field)));
}
}
return Status.OK;
}
return Status.ERROR;
}
@Override
public Status scan(String table, String startkey, int recordcount,
Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {
// Geode does not support scan
return Status.ERROR;
}
@Override
public Status update(String table, String key, Map<String, ByteIterator> values) {
getRegion(table).put(key, convertToBytearrayMap(values));
return Status.OK;
}
@Override
public Status insert(String table, String key, Map<String, ByteIterator> values) {
getRegion(table).put(key, convertToBytearrayMap(values));
return Status.OK;
}
@Override
public Status delete(String table, String key) {
getRegion(table).destroy(key);
return Status.OK;
}
private PdxInstance convertToBytearrayMap(Map<String, ByteIterator> values) {
PdxInstanceFactory pdxInstanceFactory = cache.createPdxInstanceFactory(JSONFormatter.JSON_CLASSNAME);
for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
pdxInstanceFactory.writeByteArray(entry.getKey(), entry.getValue().toArray());
}
return pdxInstanceFactory.create();
}
private Region<String, PdxInstance> getRegion(String table) {
Region<String, PdxInstance> r = cache.getRegion(table);
if (r == null) {
try {
if (isClient) {
ClientRegionFactory<String, PdxInstance> crf =
((ClientCache) cache).createClientRegionFactory(ClientRegionShortcut.PROXY);
r = crf.create(table);
} else {
RegionFactory<String, PdxInstance> rf = ((Cache) cache).createRegionFactory(RegionShortcut.PARTITION);
r = rf.create(table);
}
} catch (RegionExistsException e) {
// another thread created the region
r = cache.getRegion(table);
}
}
return r;
}
}
| apache-2.0 |
ahwxl/deep | src/main/java/org/activiti/engine/impl/persistence/entity/GroupEntityManager.java | 4560 | /* 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.activiti.engine.impl.persistence.entity;
import java.util.List;
import java.util.Map;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.GroupQuery;
import org.activiti.engine.impl.GroupQueryImpl;
import org.activiti.engine.impl.Page;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.db.DbSqlSession;
import org.activiti.engine.impl.db.PersistentObject;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.AbstractManager;
/**
* @author Tom Baeyens
* @author Saeid Mirzaei
* @author Joram Barrez
*/
public class GroupEntityManager extends AbstractManager implements GroupIdentityManager {
public Group createNewGroup(String groupId) {
return new GroupEntity(groupId);
}
public void insertGroup(Group group) {
getDbSqlSession().insert((PersistentObject) group);
if(getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED, group));
getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_INITIALIZED, group));
}
}
public void updateGroup(Group updatedGroup) {
CommandContext commandContext = Context.getCommandContext();
DbSqlSession dbSqlSession = commandContext.getDbSqlSession();
dbSqlSession.update((GroupEntity) updatedGroup);
if(getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_UPDATED, updatedGroup));
}
}
public void deleteGroup(String groupId) {
GroupEntity group = getDbSqlSession().selectById(GroupEntity.class, groupId);
if(group != null) {
if(getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createMembershipEvent(ActivitiEventType.MEMBERSHIPS_DELETED, groupId, null));
}
getDbSqlSession().delete("deleteMembershipsByGroupId", groupId);
getDbSqlSession().delete(group);
if(getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, group));
}
}
}
public GroupQuery createNewGroupQuery() {
return new GroupQueryImpl(Context.getProcessEngineConfiguration().getCommandExecutor());
}
@SuppressWarnings("unchecked")
public List<Group> findGroupByQueryCriteria(GroupQueryImpl query, Page page) {
return getDbSqlSession().selectList("selectGroupByQueryCriteria", query, page);
}
public long findGroupCountByQueryCriteria(GroupQueryImpl query) {
return (Long) getDbSqlSession().selectOne("selectGroupCountByQueryCriteria", query);
}
@SuppressWarnings("unchecked")
public List<Group> findGroupsByUser(String userId) {
return getDbSqlSession().selectList("selectGroupsByUserId", userId);
}
@SuppressWarnings("unchecked")
public List<Group> findGroupsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbSqlSession().selectListWithRawParameter("selectGroupByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findGroupCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectGroupCountByNativeQuery", parameterMap);
}
@Override
public boolean isNewGroup(Group group) {
return ((GroupEntity) group).getRevision() == 0;
}
}
| apache-2.0 |
googleapis/api-compiler | src/main/java/com/google/api/tools/framework/aspects/documentation/source/SourceParser.java | 11277 | /*
* Copyright (C) 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.tools.framework.aspects.documentation.source;
import com.google.api.tools.framework.model.DiagReporter;
import com.google.api.tools.framework.model.DiagReporter.LocationContext;
import com.google.api.tools.framework.model.Model;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Parser that parses given Markdown source into {@link SourceElement} structure. */
public class SourceParser {
/**
*
*
* <pre>Setext-style headers:
* Header 1
* ========
*
* Header 2
* -------- </pre>
*
* Based on standard Markdown.pl
*/
private static final Pattern SETEXT_HEADING =
Pattern.compile(
"(?<=^|\\n)(.+)" // Header text
+ "[ \\t]*"
+ "\\n(=+|-+)" // Header level
+ "[ \\t]*"
+ "\\n+");
/**
*
*
* <pre>atx-style headers:
* # Header 1
* ## Header 2
* ## Header 2 with closing hashes ##
* ...
* ###### Header 6 </pre>
*
* We will match any number of '#'s for normalized subsections.
*/
private static final Pattern ATX_HEADING =
Pattern.compile(
"(?<=^|\\n)(#+)" // Header level
+ "[ \\t]*"
+ "(.+?)" // Header text
+ "[ \\t]*"
+ "#*"
+ "\\n+");
private static final Pattern HEADING =
Pattern.compile(String.format("%s|%s", SETEXT_HEADING, ATX_HEADING));
private static final int SEXEXT_HEADING_TEXT = 1;
private static final int SEXEXT_HEADING_LEVEL = 2;
private static final int ATX_HEADING_LEVEL = 3;
private static final int ATX_HEADING_TEXT = 4;
/**
* Instruction. Syntax:
* (== code arg ==)
*/
private static final Pattern INSTRUCTION = Pattern.compile(
"(?<!\\\\)\\(==" // Begin tag
+ "\\s*"
+ "(?<instrcode>[\\w-]+)" // Instruction code
+ "\\s+"
+ "(?<instrarg>[\\S\\s]*?)" // Instruction arg
+ "\\s*"
+ "(?<!\\\\)==\\)(?:\n|\\Z)?"); // End tag
private static final Pattern CODE_BLOCK =
Pattern.compile(
"(?<=\\n\\n|\\A)"
+ "(?<codeblocksource>" // The code block -- one or more lines, starting with a
// space/tab
+ "(?:"
+ "(?:\\s{4}|\\t)" // # Lines must start with a tab or a tab-width of spaces
+ ".*\n*"
+ ")+"
+ ")"
+ "((?=\\s{0,3}\\S)|\\Z)"); // Lookahead for non-space at line-start, or end of doc
private static final Pattern HTML_CODE_BLOCK =
Pattern.compile(
// If the HTML code block is preceeded by two newlines, we strip one. This does not affect
// DocGen's final, rendered HTML output. But it ensures that G3doc, which adds an extra
// newline around code blocks, does not end up surrounding codeblocks with three newlines
// rather than the expected two.
"((?<=\\n)(?:(\\s*\\n\\s*)?)|)"
+ "(?<htmlcodeblocksource>"
+ "<(?<tag>pre|code)(|\\s.*)>[\\S\\s]*?"
+ "</\\k<tag>>)"
+ "((?:\\s*\\n)?(?=\\s*\\n)|)"); // Ignore possible following newline to prevent
//duplication by G3doc; see preceeding comment.
private static final Pattern FENCED_CODE_BLOCK =
Pattern.compile("(?<fencedcodeblocksource>```.*\\n[\\S\\s]*?```)");
private static final Pattern CONTENT_PARSING_PATTERNS =
Pattern.compile(
String.format(
"(?<instr>%s)|(?<codeblock>%s)|(?<htmlcodeblock>%s)|(?<fencedcodeblock>%s)",
INSTRUCTION, CODE_BLOCK, HTML_CODE_BLOCK, FENCED_CODE_BLOCK));
private static final String INSTRUCTION_GROUP = "instr";
private static final String INSTRUCTION_CODE = "instrcode";
private static final String INSTRUCTION_ARG = "instrarg";
private static final String CODE_BLOCK_SOURCE_GROUP = "codeblocksource";
private static final String HTML_CODE_BLOCK_SOURCE_GROUP = "htmlcodeblocksource";
private static final String FENCED_CODE_BLOCK_SOURCE_GROUP = "fencedcodeblocksource";
private static final String INCLUSION_CODE = "include";
private static final String PLAIN_CODE_TAG = "disable-markdown-code-block";
private final DiagReporter diagReporter;
private final LocationContext sourceLocation;
private final String source;
private final String docPath;
private final Model model;
public SourceParser(
String source,
LocationContext sourceLocation,
DiagReporter diagReporter,
String docPath,
Model model) {
this.source = source;
this.sourceLocation = sourceLocation;
this.diagReporter = diagReporter;
this.docPath = docPath;
this.model = model;
}
public SourceParser(
String source, LocationContext sourceLocation, DiagReporter diagReporter, String docPath) {
this(source, sourceLocation, diagReporter, docPath, null);
}
/**
* Parses given Markdown source and generates model of {@link SourceRoot}. The generated model is
* based on Markdown header sections.
*/
public SourceRoot parse() {
SourceRoot root = new SourceRoot(0, source.length());
SectionHeader curHeader = null;
Matcher headerMatcher = HEADING.matcher(source);
while (headerMatcher.find()) {
SectionHeader nextHeader = createHeader(headerMatcher);
fillContents(source, root, curHeader, nextHeader);
curHeader = nextHeader;
}
fillContents(source, root, curHeader, null);
return root;
}
/**
* Fills {@link ContentElement}s into model from region between given header boundaries in the
* source. If content elements are top level, they will be filled into {@link SourceRoot}
* directly. Otherwise a {@link SourceSection} will be created and filled with those content
* elements.
*/
private void fillContents(
String source, SourceRoot root, SectionHeader curHeader, SectionHeader nextHeader) {
List<ContentElement> contents = parseContents(source, curHeader, nextHeader);
if (curHeader == null) {
// Add top level contents to source root.
root.addTopLevelContents(contents);
} else {
// Create a section with curHeader as header and fill parsed content elements into
// the section
int sectionEnd = nextHeader == null ? source.length() : nextHeader.getStartIndex();
SourceSection section = new SourceSection(curHeader, curHeader.getStartIndex(), sectionEnd);
section.addContents(contents);
root.addSection(section);
}
}
/**
* Parse the source region between given section headers boundary to generate {@link
* ContentElement}s.
*/
private List<ContentElement> parseContents(
String source, SectionHeader curHeader, SectionHeader nextHeader) {
List<ContentElement> contents = Lists.newArrayList();
// Decide the source region for the content based on two header boundaries.
int curIndex = curHeader == null ? 0 : curHeader.getEndIndex();
int end = nextHeader == null ? source.length() : nextHeader.getStartIndex();
if (curIndex >= end) {
return contents;
}
Matcher matcher = CONTENT_PARSING_PATTERNS.matcher(source).region(curIndex, end);
while (matcher.find()) {
if (matcher.start() > curIndex) {
// Extract text content between current index and start of found inclusion instruction.
String text = source.substring(curIndex, matcher.start());
contents.add(new Text(unescapeInstructions(text), curIndex, matcher.start()));
}
ContentElement newElement;
if (matcher.group(INSTRUCTION_GROUP) != null) {
int headingLevel = curHeader == null ? 0 : curHeader.getLevel();
String code = matcher.group(INSTRUCTION_CODE);
if (INCLUSION_CODE.equals(code)) {
// Create content element for found file inclusion instruction.
newElement =
new FileInclusion(
docPath,
unescapeInstructions(matcher.group(INSTRUCTION_ARG).trim()),
headingLevel,
matcher.start(),
matcher.end(),
diagReporter,
sourceLocation);
} else {
// Create content element for other instruction.
newElement =
new Instruction(
code,
unescapeInstructions(matcher.group(INSTRUCTION_ARG)),
matcher.start(),
matcher.end());
}
} else if (matcher.group(CODE_BLOCK_SOURCE_GROUP) != null) {
// Create content element for code block.
newElement =
new CodeBlock(
unescapeInstructions(matcher.group(CODE_BLOCK_SOURCE_GROUP)),
matcher.start(),
matcher.end());
} else if (matcher.group(HTML_CODE_BLOCK_SOURCE_GROUP) != null) {
newElement =
new CodeBlock(
unescapeInstructions(matcher.group(HTML_CODE_BLOCK_SOURCE_GROUP)),
matcher.start(),
matcher.end());
} else if (matcher.group(FENCED_CODE_BLOCK_SOURCE_GROUP) != null) {
newElement =
new CodeBlock(
unescapeInstructions(matcher.group(FENCED_CODE_BLOCK_SOURCE_GROUP)),
matcher.start(),
matcher.end());
} else {
// If the matcher matched, we should have been in one of the cases handled above;
// this line should never be reached.
throw new IllegalStateException("Internal error: no valid regex subgroup found");
}
contents.add(newElement);
curIndex = matcher.end();
}
String text = source.substring(curIndex, end);
// Extract trailing text content.
if (!text.isEmpty()) {
end = curIndex + text.length();
contents.add(new Text(text, curIndex, end));
}
return contents;
}
/** Create {@link SectionHeader} instance based on matching result. */
private SectionHeader createHeader(Matcher matcher) {
int level;
String text;
if (!Strings.isNullOrEmpty(matcher.group(ATX_HEADING_LEVEL))) {
level = matcher.group(ATX_HEADING_LEVEL).length();
text = matcher.group(ATX_HEADING_TEXT);
} else {
level = matcher.group(SEXEXT_HEADING_LEVEL).startsWith("=") ? 1 : 2;
text = matcher.group(SEXEXT_HEADING_TEXT);
}
return new SectionHeader(level, text, matcher.start(), matcher.end());
}
private String unescapeInstructions(String string) {
return string.replace("\\(==", "(==").replace("\\==)", "==)");
}
}
| apache-2.0 |
gerdriesselmann/netty | transport/src/test/java/io/netty/channel/local/LocalChannelTest.java | 46313 | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.channel.local;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.AbstractChannel;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.IoHandler;
import io.netty.channel.MultithreadEventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.SingleThreadEventLoop;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.Promise;
import io.netty.util.concurrent.RejectedExecutionHandler;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.net.ConnectException;
import java.nio.channels.ClosedChannelException;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class LocalChannelTest {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(LocalChannelTest.class);
private static final LocalAddress TEST_ADDRESS = new LocalAddress("test.id");
private static EventLoopGroup group1;
private static EventLoopGroup group2;
private static EventLoopGroup sharedGroup;
@BeforeClass
public static void beforeClass() {
group1 = new MultithreadEventLoopGroup(2, LocalHandler.newFactory());
group2 = new MultithreadEventLoopGroup(2, LocalHandler.newFactory());
sharedGroup = new MultithreadEventLoopGroup(1, LocalHandler.newFactory());
}
@AfterClass
public static void afterClass() throws InterruptedException {
Future<?> group1Future = group1.shutdownGracefully(0, 0, SECONDS);
Future<?> group2Future = group2.shutdownGracefully(0, 0, SECONDS);
Future<?> sharedGroupFuture = sharedGroup.shutdownGracefully(0, 0, SECONDS);
group1Future.await();
group2Future.await();
sharedGroupFuture.await();
}
@Test
public void testLocalAddressReuse() throws Exception {
for (int i = 0; i < 2; i ++) {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
cb.group(group1)
.channel(LocalChannel.class)
.handler(new TestHandler());
sb.group(group2)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new TestHandler());
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).sync().channel();
final CountDownLatch latch = new CountDownLatch(1);
// Connect to the server
cc = cb.connect(sc.localAddress()).sync().channel();
final Channel ccCpy = cc;
cc.eventLoop().execute(() -> {
// Send a message event up the pipeline.
ccCpy.pipeline().fireChannelRead("Hello, World");
latch.countDown();
});
assertTrue(latch.await(5, SECONDS));
// Close the channel
closeChannel(cc);
closeChannel(sc);
sc.closeFuture().sync();
assertNull(String.format(
"Expected null, got channel '%s' for local address '%s'",
LocalChannelRegistry.get(TEST_ADDRESS), TEST_ADDRESS), LocalChannelRegistry.get(TEST_ADDRESS));
} finally {
closeChannel(cc);
closeChannel(sc);
}
}
}
@Test
public void testWriteFailsFastOnClosedChannel() throws Exception {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
cb.group(group1)
.channel(LocalChannel.class)
.handler(new TestHandler());
sb.group(group2)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new TestHandler());
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).sync().channel();
// Connect to the server
cc = cb.connect(sc.localAddress()).sync().channel();
// Close the channel and write something.
cc.close().sync();
try {
cc.writeAndFlush(new Object()).sync();
fail("must raise a ClosedChannelException");
} catch (CompletionException cause) {
Throwable e = cause.getCause();
assertThat(e, is(instanceOf(ClosedChannelException.class)));
// Ensure that the actual write attempt on a closed channel was never made by asserting that
// the ClosedChannelException has been created by AbstractUnsafe rather than transport implementations.
if (e.getStackTrace().length > 0) {
assertThat(
e.getStackTrace()[0].getClassName(), is(AbstractChannel.class.getName() +
"$AbstractUnsafe"));
e.printStackTrace();
}
}
} finally {
closeChannel(cc);
closeChannel(sc);
}
}
@Test
public void testServerCloseChannelSameEventLoop() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
ServerBootstrap sb = new ServerBootstrap()
.group(group2)
.channel(LocalServerChannel.class)
.childHandler(new SimpleChannelInboundHandler<Object>() {
@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.close();
latch.countDown();
}
});
Channel sc = null;
Channel cc = null;
try {
sc = sb.bind(TEST_ADDRESS).sync().channel();
Bootstrap b = new Bootstrap()
.group(group2)
.channel(LocalChannel.class)
.handler(new SimpleChannelInboundHandler<Object>() {
@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
// discard
}
});
cc = b.connect(sc.localAddress()).sync().channel();
cc.writeAndFlush(new Object());
assertTrue(latch.await(5, SECONDS));
} finally {
closeChannel(cc);
closeChannel(sc);
}
}
@Test
public void localChannelRaceCondition() throws Exception {
final CountDownLatch closeLatch = new CountDownLatch(1);
final EventLoopGroup clientGroup = new LocalEventLoopGroup(1) {
@Override
protected EventLoop newChild(
Executor executor, int maxPendingTasks, RejectedExecutionHandler rejectedExecutionHandler,
IoHandler ioHandler, int maxTasksPerRun, Object... args) {
return new SingleThreadEventLoop(executor, ioHandler, maxPendingTasks, rejectedExecutionHandler) {
@Override
protected void run() {
do {
runIo();
Runnable task = pollTask();
if (task != null) {
/* Only slow down the anonymous class in LocalChannel#doRegister() */
if (task.getClass().getEnclosingClass() == LocalChannel.class) {
try {
closeLatch.await(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new Error(e);
}
}
task.run();
updateLastExecutionTime();
}
} while (!confirmShutdown());
}
};
}
};
Channel sc = null;
Channel cc = null;
try {
ServerBootstrap sb = new ServerBootstrap();
sc = sb.group(group2).
channel(LocalServerChannel.class).
childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.close();
closeLatch.countDown();
}
}).
bind(TEST_ADDRESS).
sync().channel();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(clientGroup).
channel(LocalChannel.class).
handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
/* Do nothing */
}
});
ChannelFuture future = bootstrap.connect(sc.localAddress());
assertTrue("Connection should finish, not time out", future.await(2000));
cc = future.channel();
} finally {
closeChannel(cc);
closeChannel(sc);
clientGroup.shutdownGracefully(0, 0, SECONDS).await();
}
}
@Test
public void testReRegister() {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
cb.group(group1)
.channel(LocalChannel.class)
.handler(new TestHandler());
sb.group(group2)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new TestHandler());
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
// Connect to the server
cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
cc.deregister().syncUninterruptibly();
} finally {
closeChannel(cc);
closeChannel(sc);
}
}
@Test
public void testCloseInWritePromiseCompletePreservesOrder() throws InterruptedException {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
final CountDownLatch messageLatch = new CountDownLatch(2);
final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
try {
cb.group(group1)
.channel(LocalChannel.class)
.handler(new TestHandler());
sb.group(group2)
.channel(LocalServerChannel.class)
.childHandler(new ChannelHandler() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg.equals(data)) {
ReferenceCountUtil.safeRelease(msg);
messageLatch.countDown();
} else {
ctx.fireChannelRead(msg);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
messageLatch.countDown();
ctx.fireChannelInactive();
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
// Connect to the server
cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
final Channel ccCpy = cc;
// Make sure a write operation is executed in the eventloop
cc.pipeline().lastContext().executor().execute(() -> {
ChannelPromise promise = ccCpy.newPromise();
promise.addListener((ChannelFutureListener) future -> ccCpy.pipeline().lastContext().close());
ccCpy.writeAndFlush(data.retainedDuplicate(), promise);
});
assertTrue(messageLatch.await(5, SECONDS));
assertFalse(cc.isOpen());
} finally {
closeChannel(cc);
closeChannel(sc);
}
} finally {
data.release();
}
}
@Test
public void testCloseAfterWriteInSameEventLoopPreservesOrder() throws InterruptedException {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
final CountDownLatch messageLatch = new CountDownLatch(3);
final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
try {
cb.group(sharedGroup)
.channel(LocalChannel.class)
.handler(new ChannelHandler() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(data.retainedDuplicate());
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (data.equals(msg)) {
ReferenceCountUtil.safeRelease(msg);
messageLatch.countDown();
} else {
ctx.fireChannelRead(msg);
}
}
});
sb.group(sharedGroup)
.channel(LocalServerChannel.class)
.childHandler(new ChannelHandler() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (data.equals(msg)) {
messageLatch.countDown();
ctx.writeAndFlush(data);
ctx.close();
} else {
ctx.fireChannelRead(msg);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
messageLatch.countDown();
ctx.fireChannelInactive();
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
// Connect to the server
cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
assertTrue(messageLatch.await(5, SECONDS));
assertFalse(cc.isOpen());
} finally {
closeChannel(cc);
closeChannel(sc);
}
} finally {
data.release();
}
}
@Test
public void testWriteInWritePromiseCompletePreservesOrder() throws InterruptedException {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
final CountDownLatch messageLatch = new CountDownLatch(2);
final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
final ByteBuf data2 = Unpooled.wrappedBuffer(new byte[512]);
try {
cb.group(group1)
.channel(LocalChannel.class)
.handler(new TestHandler());
sb.group(group2)
.channel(LocalServerChannel.class)
.childHandler(new ChannelHandler() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
final long count = messageLatch.getCount();
if ((data.equals(msg) && count == 2) || (data2.equals(msg) && count == 1)) {
ReferenceCountUtil.safeRelease(msg);
messageLatch.countDown();
} else {
ctx.fireChannelRead(msg);
}
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
// Connect to the server
cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
final Channel ccCpy = cc;
// Make sure a write operation is executed in the eventloop
cc.pipeline().lastContext().executor().execute(() -> {
ChannelPromise promise = ccCpy.newPromise();
promise.addListener((ChannelFutureListener) future ->
ccCpy.writeAndFlush(data2.retainedDuplicate(), ccCpy.newPromise()));
ccCpy.writeAndFlush(data.retainedDuplicate(), promise);
});
assertTrue(messageLatch.await(5, SECONDS));
} finally {
closeChannel(cc);
closeChannel(sc);
}
} finally {
data.release();
data2.release();
}
}
@Test
public void testPeerWriteInWritePromiseCompleteDifferentEventLoopPreservesOrder() throws InterruptedException {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
final CountDownLatch messageLatch = new CountDownLatch(2);
final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
final ByteBuf data2 = Unpooled.wrappedBuffer(new byte[512]);
final CountDownLatch serverChannelLatch = new CountDownLatch(1);
final AtomicReference<Channel> serverChannelRef = new AtomicReference<>();
cb.group(group1)
.channel(LocalChannel.class)
.handler(new ChannelHandler() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (data2.equals(msg)) {
ReferenceCountUtil.safeRelease(msg);
messageLatch.countDown();
} else {
ctx.fireChannelRead(msg);
}
}
});
sb.group(group2)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelHandler() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (data.equals(msg)) {
ReferenceCountUtil.safeRelease(msg);
messageLatch.countDown();
} else {
ctx.fireChannelRead(msg);
}
}
});
serverChannelRef.set(ch);
serverChannelLatch.countDown();
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
// Connect to the server
cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
assertTrue(serverChannelLatch.await(5, SECONDS));
final Channel ccCpy = cc;
// Make sure a write operation is executed in the eventloop
cc.pipeline().lastContext().executor().execute(() -> {
ChannelPromise promise = ccCpy.newPromise();
promise.addListener((ChannelFutureListener) future -> {
Channel serverChannelCpy = serverChannelRef.get();
serverChannelCpy.writeAndFlush(data2.retainedDuplicate(), serverChannelCpy.newPromise());
});
ccCpy.writeAndFlush(data.retainedDuplicate(), promise);
});
assertTrue(messageLatch.await(5, SECONDS));
} finally {
closeChannel(cc);
closeChannel(sc);
data.release();
data2.release();
}
}
@Test
public void testPeerWriteInWritePromiseCompleteSameEventLoopPreservesOrder() throws InterruptedException {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
final CountDownLatch messageLatch = new CountDownLatch(2);
final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
final ByteBuf data2 = Unpooled.wrappedBuffer(new byte[512]);
final CountDownLatch serverChannelLatch = new CountDownLatch(1);
final AtomicReference<Channel> serverChannelRef = new AtomicReference<>();
try {
cb.group(sharedGroup)
.channel(LocalChannel.class)
.handler(new ChannelHandler() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (data2.equals(msg) && messageLatch.getCount() == 1) {
ReferenceCountUtil.safeRelease(msg);
messageLatch.countDown();
} else {
ctx.fireChannelRead(msg);
}
}
});
sb.group(sharedGroup)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelHandler() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (data.equals(msg) && messageLatch.getCount() == 2) {
ReferenceCountUtil.safeRelease(msg);
messageLatch.countDown();
} else {
ctx.fireChannelRead(msg);
}
}
});
serverChannelRef.set(ch);
serverChannelLatch.countDown();
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
// Connect to the server
cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
assertTrue(serverChannelLatch.await(5, SECONDS));
final Channel ccCpy = cc;
// Make sure a write operation is executed in the eventloop
cc.pipeline().lastContext().executor().execute(() -> {
ChannelPromise promise = ccCpy.newPromise();
promise.addListener((ChannelFutureListener) future -> {
Channel serverChannelCpy = serverChannelRef.get();
serverChannelCpy.writeAndFlush(
data2.retainedDuplicate(), serverChannelCpy.newPromise());
});
ccCpy.writeAndFlush(data.retainedDuplicate(), promise);
});
assertTrue(messageLatch.await(5, SECONDS));
} finally {
closeChannel(cc);
closeChannel(sc);
}
} finally {
data.release();
data2.release();
}
}
@Test
public void testWriteWhilePeerIsClosedReleaseObjectAndFailPromise() throws InterruptedException {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
final CountDownLatch serverMessageLatch = new CountDownLatch(1);
final LatchChannelFutureListener serverChannelCloseLatch = new LatchChannelFutureListener(1);
final LatchChannelFutureListener clientChannelCloseLatch = new LatchChannelFutureListener(1);
final CountDownLatch writeFailLatch = new CountDownLatch(1);
final ByteBuf data = Unpooled.wrappedBuffer(new byte[1024]);
final ByteBuf data2 = Unpooled.wrappedBuffer(new byte[512]);
final CountDownLatch serverChannelLatch = new CountDownLatch(1);
final AtomicReference<Channel> serverChannelRef = new AtomicReference<>();
try {
cb.group(group1)
.channel(LocalChannel.class)
.handler(new TestHandler());
sb.group(group2)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelHandler() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (data.equals(msg)) {
ReferenceCountUtil.safeRelease(msg);
serverMessageLatch.countDown();
} else {
ctx.fireChannelRead(msg);
}
}
});
serverChannelRef.set(ch);
serverChannelLatch.countDown();
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).syncUninterruptibly().channel();
// Connect to the server
cc = cb.connect(sc.localAddress()).syncUninterruptibly().channel();
assertTrue(serverChannelLatch.await(5, SECONDS));
final Channel ccCpy = cc;
final Channel serverChannelCpy = serverChannelRef.get();
serverChannelCpy.closeFuture().addListener(serverChannelCloseLatch);
ccCpy.closeFuture().addListener(clientChannelCloseLatch);
// Make sure a write operation is executed in the eventloop
cc.pipeline().lastContext().executor().execute(() ->
ccCpy.writeAndFlush(data.retainedDuplicate(), ccCpy.newPromise())
.addListener((ChannelFutureListener) future -> {
serverChannelCpy.eventLoop().execute(() -> {
// The point of this test is to write while the peer is closed, so we should
// ensure the peer is actually closed before we write.
int waitCount = 0;
while (ccCpy.isOpen()) {
try {
Thread.sleep(50);
} catch (InterruptedException ignored) {
// ignored
}
if (++waitCount > 5) {
fail();
}
}
serverChannelCpy.writeAndFlush(data2.retainedDuplicate(),
serverChannelCpy.newPromise())
.addListener((ChannelFutureListener) future1 -> {
if (!future1.isSuccess() &&
future1.cause() instanceof ClosedChannelException) {
writeFailLatch.countDown();
}
});
});
ccCpy.close();
}));
assertTrue(serverMessageLatch.await(5, SECONDS));
assertTrue(writeFailLatch.await(5, SECONDS));
assertTrue(serverChannelCloseLatch.await(5, SECONDS));
assertTrue(clientChannelCloseLatch.await(5, SECONDS));
assertFalse(ccCpy.isOpen());
assertFalse(serverChannelCpy.isOpen());
} finally {
closeChannel(cc);
closeChannel(sc);
}
} finally {
data.release();
data2.release();
}
}
@Test(timeout = 3000)
public void testConnectFutureBeforeChannelActive() throws Exception {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
cb.group(group1)
.channel(LocalChannel.class)
.handler(new ChannelHandler() { });
sb.group(group2)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new TestHandler());
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).sync().channel();
cc = cb.register().sync().channel();
final ChannelPromise promise = cc.newPromise();
final Promise<Void> assertPromise = cc.eventLoop().newPromise();
cc.pipeline().addLast(new TestHandler() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// Ensure the promise was done before the handler method is triggered.
if (promise.isDone()) {
assertPromise.setSuccess(null);
} else {
assertPromise.setFailure(new AssertionError("connect promise should be done"));
}
}
});
// Connect to the server
cc.connect(sc.localAddress(), promise).sync();
assertPromise.syncUninterruptibly();
assertTrue(promise.isSuccess());
} finally {
closeChannel(cc);
closeChannel(sc);
}
}
@Test(expected = ConnectException.class)
public void testConnectionRefused() throws Throwable {
try {
Bootstrap sb = new Bootstrap();
sb.group(group1)
.channel(LocalChannel.class)
.handler(new TestHandler())
.connect(LocalAddress.ANY).syncUninterruptibly();
} catch (CompletionException e) {
throw e.getCause();
}
}
private static final class LatchChannelFutureListener extends CountDownLatch implements ChannelFutureListener {
private LatchChannelFutureListener(int count) {
super(count);
}
@Override
public void operationComplete(ChannelFuture future) throws Exception {
countDown();
}
}
private static void closeChannel(Channel cc) {
if (cc != null) {
cc.close().syncUninterruptibly();
}
}
static class TestHandler implements ChannelHandler {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.info(String.format("Received message: %s", msg));
ReferenceCountUtil.safeRelease(msg);
}
}
@Test
public void testNotLeakBuffersWhenCloseByRemotePeer() throws Exception {
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
cb.group(sharedGroup)
.channel(LocalChannel.class)
.handler(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
ctx.writeAndFlush(ctx.alloc().buffer().writeZero(100));
}
@Override
public void messageReceived(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
// Just drop the buffer
}
});
sb.group(sharedGroup)
.channel(LocalServerChannel.class)
.childHandler(new ChannelInitializer<LocalChannel>() {
@Override
public void initChannel(LocalChannel ch) throws Exception {
ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
public void messageReceived(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
while (buffer.isReadable()) {
// Fill the ChannelOutboundBuffer with multiple buffers
ctx.write(buffer.readRetainedSlice(1));
}
// Flush and so transfer the written buffers to the inboundBuffer of the remote peer.
// After this point the remote peer is responsible to release all the buffers.
ctx.flush();
// This close call will trigger the remote peer close as well.
ctx.close();
}
});
}
});
Channel sc = null;
LocalChannel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).sync().channel();
// Connect to the server
cc = (LocalChannel) cb.connect(sc.localAddress()).sync().channel();
// Close the channel
closeChannel(cc);
assertTrue(cc.inboundBuffer.isEmpty());
closeChannel(sc);
} finally {
closeChannel(cc);
closeChannel(sc);
}
}
private static void writeAndFlushReadOnSuccess(final ChannelHandlerContext ctx, Object msg) {
ctx.writeAndFlush(msg).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
ctx.read();
}
});
}
@Test(timeout = 5000)
public void testAutoReadDisabledSharedGroup() throws Exception {
testAutoReadDisabled(sharedGroup, sharedGroup);
}
@Test(timeout = 5000)
public void testAutoReadDisabledDifferentGroup() throws Exception {
testAutoReadDisabled(group1, group2);
}
private static void testAutoReadDisabled(EventLoopGroup serverGroup, EventLoopGroup clientGroup) throws Exception {
final CountDownLatch latch = new CountDownLatch(100);
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
cb.group(serverGroup)
.channel(LocalChannel.class)
.option(ChannelOption.AUTO_READ, false)
.handler(new ChannelHandler() {
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
writeAndFlushReadOnSuccess(ctx, "test");
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
writeAndFlushReadOnSuccess(ctx, msg);
}
});
sb.group(clientGroup)
.channel(LocalServerChannel.class)
.childOption(ChannelOption.AUTO_READ, false)
.childHandler(new ChannelHandler() {
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
ctx.read();
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
latch.countDown();
if (latch.getCount() > 0) {
writeAndFlushReadOnSuccess(ctx, msg);
}
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).sync().channel();
cc = cb.connect(TEST_ADDRESS).sync().channel();
latch.await();
} finally {
closeChannel(cc);
closeChannel(sc);
}
}
@Test(timeout = 5000)
public void testMaxMessagesPerReadRespectedWithAutoReadSharedGroup() throws Exception {
testMaxMessagesPerReadRespected(sharedGroup, sharedGroup, true);
}
@Test(timeout = 5000)
public void testMaxMessagesPerReadRespectedWithoutAutoReadSharedGroup() throws Exception {
testMaxMessagesPerReadRespected(sharedGroup, sharedGroup, false);
}
@Test(timeout = 5000)
public void testMaxMessagesPerReadRespectedWithAutoReadDifferentGroup() throws Exception {
testMaxMessagesPerReadRespected(group1, group2, true);
}
@Test(timeout = 5000)
public void testMaxMessagesPerReadRespectedWithoutAutoReadDifferentGroup() throws Exception {
testMaxMessagesPerReadRespected(group1, group2, false);
}
private static void testMaxMessagesPerReadRespected(
EventLoopGroup serverGroup, EventLoopGroup clientGroup, final boolean autoRead) throws Exception {
final CountDownLatch countDownLatch = new CountDownLatch(5);
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
cb.group(serverGroup)
.channel(LocalChannel.class)
.option(ChannelOption.AUTO_READ, autoRead)
.option(ChannelOption.MAX_MESSAGES_PER_READ, 1)
.handler(new ChannelReadHandler(countDownLatch, autoRead));
sb.group(clientGroup)
.channel(LocalServerChannel.class)
.childHandler(new ChannelHandler() {
@Override
public void channelActive(final ChannelHandlerContext ctx) {
for (int i = 0; i < 10; i++) {
ctx.write(i);
}
ctx.flush();
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).sync().channel();
cc = cb.connect(TEST_ADDRESS).sync().channel();
countDownLatch.await();
} finally {
closeChannel(cc);
closeChannel(sc);
}
}
@Test(timeout = 5000)
public void testServerMaxMessagesPerReadRespectedWithAutoReadSharedGroup() throws Exception {
testServerMaxMessagesPerReadRespected(sharedGroup, sharedGroup, true);
}
@Test(timeout = 5000)
public void testServerMaxMessagesPerReadRespectedWithoutAutoReadSharedGroup() throws Exception {
testServerMaxMessagesPerReadRespected(sharedGroup, sharedGroup, false);
}
@Test(timeout = 5000)
public void testServerMaxMessagesPerReadRespectedWithAutoReadDifferentGroup() throws Exception {
testServerMaxMessagesPerReadRespected(group1, group2, true);
}
@Test(timeout = 5000)
public void testServerMaxMessagesPerReadRespectedWithoutAutoReadDifferentGroup() throws Exception {
testServerMaxMessagesPerReadRespected(group1, group2, false);
}
private void testServerMaxMessagesPerReadRespected(
EventLoopGroup serverGroup, EventLoopGroup clientGroup, final boolean autoRead) throws Exception {
final CountDownLatch countDownLatch = new CountDownLatch(5);
Bootstrap cb = new Bootstrap();
ServerBootstrap sb = new ServerBootstrap();
cb.group(serverGroup)
.channel(LocalChannel.class)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
// NOOP
}
});
sb.group(clientGroup)
.channel(LocalServerChannel.class)
.option(ChannelOption.AUTO_READ, autoRead)
.option(ChannelOption.MAX_MESSAGES_PER_READ, 1)
.handler(new ChannelReadHandler(countDownLatch, autoRead))
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
// NOOP
}
});
Channel sc = null;
Channel cc = null;
try {
// Start server
sc = sb.bind(TEST_ADDRESS).sync().channel();
for (int i = 0; i < 5; i++) {
try {
cc = cb.connect(TEST_ADDRESS).sync().channel();
} finally {
closeChannel(cc);
}
}
countDownLatch.await();
} finally {
closeChannel(sc);
}
}
private static final class ChannelReadHandler implements ChannelHandler {
private final CountDownLatch latch;
private final boolean autoRead;
private int read;
ChannelReadHandler(CountDownLatch latch, boolean autoRead) {
this.latch = latch;
this.autoRead = autoRead;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
if (!autoRead) {
ctx.read();
}
ctx.fireChannelActive();
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {
assertEquals(0, read);
read++;
ctx.fireChannelRead(msg);
}
@Override
public void channelReadComplete(final ChannelHandlerContext ctx) {
assertEquals(1, read);
latch.countDown();
if (latch.getCount() > 0) {
if (!autoRead) {
// The read will be scheduled 100ms in the future to ensure we not receive any
// channelRead calls in the meantime.
ctx.executor().schedule(() -> {
read = 0;
ctx.read();
}, 100, TimeUnit.MILLISECONDS);
} else {
read = 0;
}
} else {
read = 0;
}
ctx.fireChannelReadComplete();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.fireExceptionCaught(cause);
ctx.close();
}
}
}
| apache-2.0 |
sothawo/mapjfx | src/main/java/com/sothawo/mapjfx/MapCoordinateElement.java | 3607 | /*
Copyright 2015-2021 Peter-Josef Meisch (pj.meisch@sothawo.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.sothawo.mapjfx;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
/**
* Common base class for elements on the map that have a defined position on the map.
*
* @author P.J. Meisch (pj.meisch@sothawo.com).
*/
public abstract class MapCoordinateElement extends MapElement {
/** the coordinate */
protected final SimpleObjectProperty<Coordinate> position = new SimpleObjectProperty<>();
/** horizontal offset */
protected final int offsetX;
/** the vertical offset */
protected final int offsetY;
/** custom css style name. */
protected SimpleStringProperty cssClass = new SimpleStringProperty("");
/** the rotation of the element. */
protected SimpleIntegerProperty rotation = new SimpleIntegerProperty(0);
public MapCoordinateElement() {
this(0, 0);
}
public MapCoordinateElement(int offsetX, int offsetY) {
this.offsetX = offsetX;
this.offsetY = offsetY;
}
public int getOffsetX() {
return offsetX;
}
public int getOffsetY() {
return offsetY;
}
public String getCssClass() {
return cssClass.get();
}
/**
* sets the cssClass for the Label
*
* @param cssClass
* class name
* @return this object
*/
public MapCoordinateElement setCssClass(final String cssClass) {
this.cssClass.set((null == cssClass) ? "" : cssClass);
return this;
}
public SimpleStringProperty cssClassProperty() {
return cssClass;
}
public Integer getRotation() {
return rotation.get();
}
/**
* sets the rotation of the element on the map.
*
* @param rotation
* rotation value
* @return this object
*/
public MapCoordinateElement setRotation(final Integer rotation) {
this.rotation.set(rotation == null ? 0 : rotation);
return this;
}
public SimpleIntegerProperty rotationProperty() {
return rotation;
}
/**
* @return the marker's id
*/
public abstract String getId();
@Override
public String toString() {
return "MapCoordinateElement{" +
"position=" + position +
", offsetX=" + offsetX +
", offsetY=" + offsetY +
", cssClass=" + cssClass +
", rotation=" + rotation +
", visible=" + visible +
"} " + super.toString();
}
public Coordinate getPosition() {
return position.get();
}
public SimpleObjectProperty<Coordinate> positionProperty() {
return position;
}
/**
* sets the marker's new position
*
* @param position
* new position
* @return this object
*/
public MapCoordinateElement setPosition(Coordinate position) {
this.position.set(position);
return this;
}
}
| apache-2.0 |
gaoxianglong/shark | src/main/java/com/sharksharding/sql/dialect/mysql/ast/statement/MySqlShowSlaveHostsStatement.java | 967 | /*
* Copyright 1999-2101 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sharksharding.sql.dialect.mysql.ast.statement;
import com.sharksharding.sql.dialect.mysql.visitor.MySqlASTVisitor;
public class MySqlShowSlaveHostsStatement extends MySqlStatementImpl implements MySqlShowStatement {
public void accept0(MySqlASTVisitor visitor) {
visitor.visit(this);
visitor.endVisit(this);
}
}
| apache-2.0 |
ripdajacker/commons-betwixt | src/java/org/apache/commons/betwixt/strategy/DefaultNameMapper.java | 2298 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.betwixt.strategy;
/**
* <p>A default implementation of the name mapper.
* This mapper simply returns the unmodified type name.</p>
*
* <p>For example, <code>PropertyName</code> would be converted to <code>PropertyName</code>.
*
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @version $Revision$
*/
public class DefaultNameMapper implements NameMapper {
/** Used to convert bad character in the name */
private static final BadCharacterReplacingNMapper badCharacterReplacementNMapper
= new BadCharacterReplacingNMapper(new PlainMapper());
/** Base implementation chained by bad character replacement mapper */
private static final class PlainMapper implements NameMapper {
/**
* This implementation returns the parameter passed in without modification.
*
* @param typeName the string to convert
* @return the typeName parameter without modification
*/
public String mapTypeToElementName(String typeName) {
return typeName;
}
}
/**
* This implementation returns the parameter passed after
* deleting any characters which the XML specification does not allow
* in element names.
*
* @param typeName the string to convert
* @return the typeName parameter without modification
*/
public String mapTypeToElementName(String typeName) {
return badCharacterReplacementNMapper.mapTypeToElementName(typeName);
}
}
| apache-2.0 |
peterkang7790/shms | src/shms/validation/CustomStringLengthFieldValidator.java | 1427 | package shms.validation;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator;
public class CustomStringLengthFieldValidator extends StringLengthFieldValidator {
/**
* validation check¸¦ ÇÒ¶§
* hashMap nameÀÌ view(jsp)¿¡¼ ÀԷµǾú´ÂÁö¸¦ ¾Ë¼ö ÀÖ°Ô Çϱâ À§Çؼ´Â
* stack¿¡ getter setter·Î Á¤ÀÇµÈ hashMap(¿©±â¿¡¼´Â reqMapÀ̸§À» ¾´´Ù)À̸§À» ÁöÁ¤Çϰí
* hashMap¿¡ ÀúÀåµÈ °ªÀ» ¸®ÅÏÇÑ´Ù.
*/
@Override
protected Object getFieldValue(String name, Object object)
throws ValidationException{
ValueStack stack = ActionContext.getContext().getValueStack();
boolean pop = false;
if (!(stack.getRoot().contains(object))) {
stack.push(object);
pop = true;
}
Object retVal = null;
// HashMap reqMapÀÇ °ªÀ» stack¿¡ ³Ö¾îÁØ´Ù.
Object obj = (Map)stack.findValue("reqMap");
// HashMap reqMapÀÌ nullÀÌ ¾Æ´Ò¶§
if(obj != null){
Map m = (Map)obj;
// stack¿¡ ÀÖ´Â HashMap reqMap°ªÀ» nameÀ¸·Î °¡Á®¿Í¼ valueStack¿¡ ¿Ã·ÁÁØ´Ù.
retVal = m.get(name);
}
// HashMap reqMapÀÌ nullÀ϶§
else{
// getter setterÀ» »ç¿ëÇÑ nameÀÇ °ªÀ» valueStack¿¡ ¿Ã·ÁÁØ´Ù.
retVal = stack.findValue(name);
}
if (pop) {
stack.pop();
}
return retVal;
}
}
| apache-2.0 |
FOC-framework/framework | focWebServer/src/com/foc/web/IServletDeclaror.java | 163 | package com.foc.web;
public interface IServletDeclaror {
public void addServlets(Object contextHandler);//org.eclipse.jetty.servlet.ServletContextHandler
}
| apache-2.0 |
0359xiaodong/XCL-Charts | XCL-Charts/src/org/xclcharts/chart/PieChart.java | 10763 | /**
* Copyright 2014 XCL-Charts
*
* 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.
*
* @Project XCL-Charts
* @Description Android图表基类库
* @author XiongChuanLiang<br/>(xcl_168@aliyun.com)
* @license http://www.apache.org/licenses/ Apache v2 License
* @version 1.0
*/
package org.xclcharts.chart;
import java.util.List;
import org.xclcharts.common.DrawHelper;
import org.xclcharts.common.MathHelper;
import org.xclcharts.event.click.ArcPosition;
import org.xclcharts.renderer.CirChart;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RadialGradient;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.Log;
/**
* @ClassName PieChart
* @Description 饼图基类
* @author XiongChuanLiang<br/>(xcl_168@aliyun.com)
*
*/
public class PieChart extends CirChart{
private static final String TAG = "PieChart";
//是否使用渲染来突出效果
private boolean mGradient = true;
//选中区偏移长度
protected static float SELECTED_OFFSET = 10.0f;
//数据源
private List<PieData> mDataset;
private Paint mPaintArc = null;
protected RectF mRectF = null;
protected RectF mArcRF0 = null;
public PieChart()
{
super();
//画笔初始化
mPaintArc = new Paint();
mPaintArc.setAntiAlias(true);
}
/**
* 开放饼图扇区的画笔
* @return 画笔
*/
public Paint geArcPaint()
{
return mPaintArc;
}
/**
* 设置图表的数据源
* @param piedata 来源数据集
*/
public void setDataSource( List<PieData> piedata)
{
if(null != mDataset)mDataset.clear();
this.mDataset = piedata;
}
/**
* 返回数据轴的数据源
* @return 数据源
*/
public List<PieData> getDataSource()
{
return mDataset;
}
/**
* 显示渲染效果(此函数对3D饼图无效)
*/
public void showGradient()
{
mGradient = true;
}
/**
* 隐藏渲染效果(此函数对3D饼图无效)
*/
public void hideGradient()
{
mGradient = false;
}
/**
* 确认是否可使用渲染效果(此函数对3D饼图无效)
* @return 是否使用渲染
*/
public boolean getGradient()
{
return mGradient;
}
/**
* 给画笔设置渲染颜色和效果
* @param paintArc 画笔
* @param cirX 中心点X坐标
* @param cirY 中心点Y坐标
* @param radius 半径
* @return 返回渲染效果类
*/
private RadialGradient renderRadialGradient(Paint paintArc,
float cirX,
float cirY,
float radius)
{
float radialRadius = (float) (radius * 0.8f);
int color = paintArc.getColor();
int darkerColor = DrawHelper.getInstance().getDarkerColor(color);
RadialGradient radialGradient = new RadialGradient(cirX, cirY, radialRadius,
darkerColor,color,
Shader.TileMode.MIRROR);
//返回环形渐变
return radialGradient;
}
/**
* 检查角度的合法性
* @param Angle 角度
* @return 是否正常
*/
protected boolean validateAngle(float Angle)
{
if(Float.compare(Angle, 0.0f) == 0
|| Float.compare(Angle, 0.0f) == -1)
{
Log.e(TAG, "扇区圆心角小于等于0度. 当前圆心角为:"+Float.toString(Angle));
return false;
}
return true;
}
/**
* 绘制指定角度扇区
* @param paintArc 画笔
* @param arcRF0 范围
* @param cData 数据集
* @param cirX 中心点X坐标
* @param cirY 中心点Y坐标
* @param radius 半径
* @param offsetAngle 偏移角度
* @param currentAngle 当前绘制角度
* @throws Exception 例外处理
*/
protected boolean drawSlice(Canvas canvas, Paint paintArc,RectF arcRF0,
PieData cData,
float cirX,
float cirY,
float radius,
float offsetAngle,
float currentAngle) throws Exception
{
try{
// 绘制环形渐变
if(getGradient())
paintArc.setShader(renderRadialGradient(paintArc,cirX,cirY,radius));
//在饼图中显示所占比例
canvas.drawArc(arcRF0, offsetAngle, currentAngle, true, paintArc);
}catch( Exception e){
throw e;
}
return true;
}
protected void initRectF(String type,float left,float top,float right,float bottom)
{
if(type.equalsIgnoreCase("mRectF"))
{
if(null == mRectF)
{
mRectF = new RectF(left ,top,right,bottom);
}else{
mRectF.set(left ,top,right,bottom);
}
}else if(type.equalsIgnoreCase("mArcRF0")){
if(null == mArcRF0)
{
mArcRF0 = new RectF(left ,top,right,bottom);
}else{
mArcRF0.set(left ,top,right,bottom);
}
}else{
Log.e(TAG,"未知的RectF.");
}
}
/**
* 绘制指定角度扇区
* @param paintArc 画笔
* @param cData 数据集
* @param cirX 中心点X坐标
* @param cirY 中心点Y坐标
* @param radius 半径
* @param offsetAngle 偏移角度
* @param currentAngle 当前绘制角度
* @throws Exception 例外处理
*/
protected boolean drawSelectedSlice(Canvas canvas, Paint paintArc,
PieData cData,
float cirX,
float cirY,
float radius,
float offsetAngle,
float currentAngle) throws Exception
{
try{
//偏移圆心点位置(默认偏移半径的1/10)
float newRadius = div(radius , SELECTED_OFFSET);
//计算百分比标签
PointF point = MathHelper.getInstance().calcArcEndPointXY(cirX,cirY,
newRadius,
add(offsetAngle , currentAngle/2f));
initRectF("mRectF",sub(point.x , radius) ,sub(point.y , radius),
add(point.x , radius),add(point.y , radius));
//绘制环形渐变
if(getGradient())
paintArc.setShader(renderRadialGradient(paintArc,cirX,cirY,radius));
//在饼图中显示所占比例
canvas.drawArc(mRectF, offsetAngle, currentAngle, true, paintArc);
return true;
}catch( Exception e){
throw e;
}
}
protected boolean renderLabels(Canvas canvas,float offset,float radius,PointF[] arrPoint )
{
int i = 0;
float currentAngle = 0.0f,offsetAngle = offset;
for(PieData cData : mDataset)
{
currentAngle = cData.getSliceAngle();
if(!validateAngle(currentAngle)) continue;
renderLabel(canvas,cData.getLabel(),
arrPoint[i].x,
arrPoint[i].y,
radius,offsetAngle,currentAngle);
//下次的起始角度
offsetAngle = add(offsetAngle, currentAngle);
i++;
}
return true;
}
/**
* 绘制图
*/
protected boolean renderPlot(Canvas canvas)
{
try{
if(null == mDataset)
{
Log.e(TAG,"数据源为空.");
return false;
}
//中心点坐标
float cirX = plotArea.getCenterX();
float cirY = plotArea.getCenterY();
float radius = getRadius();
//确定饼图范围
initRectF("mArcRF0",sub(cirX , radius) ,
sub(cirY , radius),
add(cirX , radius),
add(cirY , radius));
//用于存放当前百分比的圆心角度
float currentAngle = 0.0f;
float offsetAngle = mOffsetAngle;
int i = 0;
PointF[] arrPoint = new PointF[mDataset.size()];
for(PieData cData : mDataset)
{
currentAngle = cData.getSliceAngle();
if(!validateAngle(currentAngle)) continue;
mPaintArc.setColor(cData.getSliceColor());
if(cData.getSelected()) //指定突出哪个块
{
if(!drawSelectedSlice(canvas,mPaintArc,cData,
cirX,cirY,radius,
offsetAngle,currentAngle))return false;
arrPoint[i] = new PointF(MathHelper.getInstance().getPosX(),
MathHelper.getInstance().getPosY());
}else{
if(!drawSlice(canvas,mPaintArc,mArcRF0,cData,
cirX,cirY,radius,
offsetAngle,(float) currentAngle))return false;
arrPoint[i] = new PointF(cirX,cirY);
}
//保存角度
saveArcRecord(i,cirX,cirY,radius,offsetAngle,currentAngle);
//下次的起始角度
offsetAngle = add(offsetAngle, currentAngle);
i++;
}
//绘制Label
renderLabels(canvas,mOffsetAngle,radius,arrPoint );
//图KEY
plotLegend.renderPieKey(canvas,this.mDataset);
arrPoint = null;
}catch( Exception e){
Log.e(TAG,e.toString());
return false;
}
return true;
}
/**
* 检验传入参数,累加不能超过360度
* @return 是否通过效验
*/
protected boolean validateParams()
{
if(null == mDataset)return false;
float totalAngle = 0.0f,currentValue = 0.0f;
for(PieData cData : mDataset)
{
currentValue = cData.getSliceAngle();
totalAngle = add(totalAngle,currentValue);
if( Float.compare(totalAngle,0.0f) == -1)
{
Log.e(TAG,"传入参数不合理,圆心角总计小于等于0度. 现有圆心角合计:"
+Float.toString(totalAngle)
+" 当前圆心角:"+Float.toString( currentValue )
+" 当前百分比:"+Double.toString( cData.getPercentage() ));
return false;
}else if( Float.compare(totalAngle, 360.1f) == 1)
{
//圆心角总计大于360度
Log.e(TAG,"传入参数不合理,圆心角总计大于360.1度. 现有圆心角合计:"
+Float.toString(totalAngle));
return false;
}
}
return true;
}
/**
* 返回当前点击点的信息
* @param x 点击点X坐标
* @param y 点击点Y坐标
* @return 返回对应的位置记录
*/
public ArcPosition getPositionRecord(float x,float y)
{
return getArcRecord(x,y);
}
@Override
protected boolean postRender(Canvas canvas) throws Exception
{
try {
super.postRender(canvas);
//检查值是否合理
if(false == validateParams())return false;
//绘制图表
return renderPlot(canvas);
} catch (Exception e) {
throw e;
}
}
}
| apache-2.0 |
j4velin/HueNotifier | app/src/main/java/de/j4velin/huenotifier/RuleAdapter.java | 5618 | package de.j4velin.huenotifier;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
import androidx.recyclerview.widget.RecyclerView;
import static de.j4velin.huenotifier.R.layout.rule;
/**
* The UI adapter containing all the rules
*/
class RuleAdapter extends RecyclerView.Adapter<RuleAdapter.ViewHolder> {
private final MainActivity activity;
private final LayoutInflater inflater;
private final PackageManager pm;
private final View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
View edit = view.findViewById(R.id.edit);
edit.setMinimumHeight(view.findViewById(R.id.lights).getHeight());
MainActivity.fadeView(true, edit);
}
};
private final View.OnClickListener configureClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
View editView = (View) view.getParent();
if (activity.isConnected) {
View cardView = (View) editView.getParent();
final int itemPosition = activity.ruleList.getChildLayoutPosition(cardView);
activity.editRule(activity.rules.get(itemPosition));
} else {
Snackbar.make(activity.findViewById(android.R.id.content), R.string.not_connected,
Snackbar.LENGTH_SHORT).show();
}
MainActivity.fadeView(false, editView);
}
};
private final View.OnClickListener deleteClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
View cardView = (View) view.getParent().getParent();
final int itemPosition = activity.ruleList.getChildLayoutPosition(cardView);
Rule r = activity.rules.remove(itemPosition);
activity.ruleAdapter.notifyItemRemoved(itemPosition);
Database db = Database.getInstance(activity);
db.delete(r.appPkg, r.person);
db.close();
}
};
private final View.OnClickListener cancelClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
View editView = (View) view.getParent();
MainActivity.fadeView(false, editView);
}
};
RuleAdapter(MainActivity activity) {
this.activity = activity;
inflater = LayoutInflater.from(activity);
pm = activity.getPackageManager();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(rule, parent, false);
v.setOnClickListener(clickListener);
ViewHolder holder = new ViewHolder(v);
holder.edit.findViewById(R.id.configure).setOnClickListener(configureClickListener);
holder.edit.findViewById(R.id.delete).setOnClickListener(deleteClickListener);
holder.edit.findViewById(R.id.cancel).setOnClickListener(cancelClickListener);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Rule rule = activity.rules.get(position);
holder.text.setText(rule.appName);
holder.edit.setVisibility(View.GONE);
Drawable appIcon;
try {
appIcon = pm.getApplicationIcon(rule.appPkg);
appIcon.setBounds(0, 0, Util.dpToPx(activity, 25),
Util.dpToPx(activity, 25));
} catch (PackageManager.NameNotFoundException e) {
appIcon = null;
}
holder.text.setCompoundDrawables(appIcon, null, null, null);
holder.linearLayout.removeAllViews();
for (int i = 0; i < rule.lightSettings.lights.length; i++) {
TextView light = (TextView) inflater
.inflate(R.layout.light, holder.linearLayout, false);
int lightIcon;
if (activity.lights != null && activity.lights.containsKey(
String.valueOf(rule.lightSettings.lights[i]))) {
Light lightObject = activity.lights.get(
String.valueOf(rule.lightSettings.lights[i]));
light.setText(lightObject.name);
lightIcon = Util.getLightIcon(lightObject.modelid);
} else {
light.setText("Light #" + rule.lightSettings.lights[i]);
lightIcon = R.drawable.ic_light;
}
light.setCompoundDrawablesWithIntrinsicBounds(lightIcon, 0, 0, 0);
if (Build.VERSION.SDK_INT >= 23) {
API23Wrapper.setCompoundDrawableTintList(light, rule.lightSettings.colors[i]);
}
light.setTextColor(rule.lightSettings.colors[i]);
holder.linearLayout.addView(light);
}
}
@Override
public int getItemCount() {
return activity.rules.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
final TextView text;
final LinearLayout linearLayout;
final View edit;
private ViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.app);
linearLayout = (LinearLayout) itemView.findViewById(R.id.lights);
edit = itemView.findViewById(R.id.edit);
}
}
} | apache-2.0 |
Marczeeee/cachet-java-api | cachet-api/src/main/java/org/m323/cachet/api/v1/response/GroupResponse.java | 462 | package org.m323.cachet.api.v1.response;
import java.io.Serializable;
import org.m323.cachet.api.v1.entity.Group;
/**
* Response containing a single Cachet {@link Group}.
*
* @author Marczeeee
* @since 0.1
*/
public class GroupResponse implements Serializable {
/** {@link Group} object */
private Group data;
public Group getData() {
return data;
}
public void setData(final Group data) {
this.data = data;
}
}
| apache-2.0 |
rajeevanv89/developer-studio | esb/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/parts/FailoverEndPointInputConnector2EditPart.java | 11273 | package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Shape;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gef.editpolicies.NonResizableEditPolicy;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderItemEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.swt.graphics.Color;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractEndpointInputConnectorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.EastPointerShape;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.FailoverEndPointInputConnector2ItemSemanticEditPolicy;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes;
/**
* @generated NOT
*/
public class FailoverEndPointInputConnector2EditPart extends
AbstractEndpointInputConnectorEditPart {
/**
* @generated
*/
public static final int VISUAL_ID = 3650;
/**
* @generated
*/
protected IFigure contentPane;
/**
* @generated
*/
protected IFigure primaryShape;
/**
* @generated
*/
public FailoverEndPointInputConnector2EditPart(View view) {
super(view);
}
/**
* @generated
*/
protected void createDefaultEditPolicies() {
super.createDefaultEditPolicies();
installEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE,
getPrimaryDragEditPolicy());
installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
new FailoverEndPointInputConnector2ItemSemanticEditPolicy());
installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy());
// XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable editpolicies
// removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE);
}
/**
* @generated
*/
protected LayoutEditPolicy createLayoutEditPolicy() {
org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() {
protected EditPolicy createChildEditPolicy(EditPart child) {
EditPolicy result = child
.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE);
if (result == null) {
result = new NonResizableEditPolicy();
}
return result;
}
protected Command getMoveChildrenCommand(Request request) {
return null;
}
protected Command getCreateCommand(CreateRequest request) {
return null;
}
};
return lep;
}
/**
* @generated
*/
protected IFigure createNodeShape() {
return primaryShape = new EastPointerFigure();
}
/**
* @generated
*/
public EastPointerFigure getPrimaryShape() {
return (EastPointerFigure) primaryShape;
}
/**
* @generated
*/
protected NodeFigure createNodePlate() {
DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(12, 10);
//FIXME: workaround for #154536
result.getBounds().setSize(result.getPreferredSize());
return result;
}
/**
* Creates figure for this edit part.
*
* Body of this method does not depend on settings in generation model
* so you may safely remove <i>generated</i> tag and modify it.
*
* @generated NOT
*/
protected NodeFigure createNodeFigure() {
NodeFigure figure = createNodePlate();
figure.setLayoutManager(new StackLayout());
IFigure shape = createNodeShapeForward();
figure.add(shape);
contentPane = setupContentPane(shape);
figure_ = figure;
createNodeShapeReverse();
return figure;
}
/**
* Default implementation treats passed figure as content pane.
* Respects layout one may have set for generated figure.
* @param nodeShape instance of generated figure class
* @generated
*/
protected IFigure setupContentPane(IFigure nodeShape) {
return nodeShape; // use nodeShape itself as contentPane
}
/**
* @generated
*/
public IFigure getContentPane() {
if (contentPane != null) {
return contentPane;
}
return super.getContentPane();
}
/**
* @generated
*/
protected void setForegroundColor(Color color) {
if (primaryShape != null) {
primaryShape.setForegroundColor(color);
}
}
/**
* @generated
*/
protected void setBackgroundColor(Color color) {
if (primaryShape != null) {
primaryShape.setBackgroundColor(color);
}
}
/**
* @generated
*/
protected void setLineWidth(int width) {
if (primaryShape instanceof Shape) {
((Shape) primaryShape).setLineWidth(width);
}
}
/**
* @generated
*/
protected void setLineType(int style) {
if (primaryShape instanceof Shape) {
((Shape) primaryShape).setLineStyle(style);
}
}
/**
* @generated
*/
public List<IElementType> getMARelTypesOnTarget() {
ArrayList<IElementType> types = new ArrayList<IElementType>(1);
types.add(EsbElementTypes.EsbLink_4001);
return types;
}
/**
* @generated
*/
public List<IElementType> getMATypesForSource(IElementType relationshipType) {
LinkedList<IElementType> types = new LinkedList<IElementType>();
if (relationshipType == EsbElementTypes.EsbLink_4001) {
types.add(EsbElementTypes.ProxyOutputConnector_3002);
types.add(EsbElementTypes.PropertyMediatorOutputConnector_3034);
types.add(EsbElementTypes.ThrottleMediatorOutputConnector_3122);
types.add(EsbElementTypes.ThrottleMediatorOnAcceptOutputConnector_3581);
types.add(EsbElementTypes.ThrottleMediatorOnRejectOutputConnector_3582);
types.add(EsbElementTypes.FilterMediatorOutputConnector_3534);
types.add(EsbElementTypes.FilterMediatorPassOutputConnector_3011);
types.add(EsbElementTypes.FilterMediatorFailOutputConnector_3012);
types.add(EsbElementTypes.LogMediatorOutputConnector_3019);
types.add(EsbElementTypes.EnrichMediatorOutputConnector_3037);
types.add(EsbElementTypes.XSLTMediatorOutputConnector_3040);
types.add(EsbElementTypes.SwitchCaseBranchOutputConnector_3043);
types.add(EsbElementTypes.SwitchDefaultBranchOutputConnector_3044);
types.add(EsbElementTypes.SwitchMediatorOutputConnector_3499);
types.add(EsbElementTypes.SequenceOutputConnector_3050);
types.add(EsbElementTypes.EventMediatorOutputConnector_3053);
types.add(EsbElementTypes.EntitlementMediatorOutputConnector_3056);
types.add(EsbElementTypes.ClassMediatorOutputConnector_3059);
types.add(EsbElementTypes.SpringMediatorOutputConnector_3062);
types.add(EsbElementTypes.ScriptMediatorOutputConnector_3065);
types.add(EsbElementTypes.FaultMediatorOutputConnector_3068);
types.add(EsbElementTypes.XQueryMediatorOutputConnector_3071);
types.add(EsbElementTypes.CommandMediatorOutputConnector_3074);
types.add(EsbElementTypes.DBLookupMediatorOutputConnector_3077);
types.add(EsbElementTypes.DBReportMediatorOutputConnector_3080);
types.add(EsbElementTypes.SmooksMediatorOutputConnector_3083);
types.add(EsbElementTypes.SendMediatorOutputConnector_3086);
types.add(EsbElementTypes.SendMediatorEndpointOutputConnector_3539);
types.add(EsbElementTypes.HeaderMediatorOutputConnector_3101);
types.add(EsbElementTypes.CloneMediatorOutputConnector_3104);
types.add(EsbElementTypes.CloneMediatorTargetOutputConnector_3133);
types.add(EsbElementTypes.CacheMediatorOutputConnector_3107);
types.add(EsbElementTypes.CacheMediatorOnHitOutputConnector_3618);
types.add(EsbElementTypes.IterateMediatorOutputConnector_3110);
types.add(EsbElementTypes.IterateMediatorTargetOutputConnector_3606);
types.add(EsbElementTypes.CalloutMediatorOutputConnector_3116);
types.add(EsbElementTypes.TransactionMediatorOutputConnector_3119);
types.add(EsbElementTypes.RMSequenceMediatorOutputConnector_3125);
types.add(EsbElementTypes.RuleMediatorOutputConnector_3128);
types.add(EsbElementTypes.RuleMediatorChildMediatorsOutputConnector_3640);
types.add(EsbElementTypes.OAuthMediatorOutputConnector_3131);
types.add(EsbElementTypes.AggregateMediatorOutputConnector_3113);
types.add(EsbElementTypes.AggregateMediatorOnCompleteOutputConnector_3132);
types.add(EsbElementTypes.StoreMediatorOutputConnector_3590);
types.add(EsbElementTypes.BuilderMediatorOutputConector_3593);
types.add(EsbElementTypes.CallTemplateMediatorOutputConnector_3596);
types.add(EsbElementTypes.PayloadFactoryMediatorOutputConnector_3599);
types.add(EsbElementTypes.EnqueueMediatorOutputConnector_3602);
types.add(EsbElementTypes.URLRewriteMediatorOutputConnector_3622);
types.add(EsbElementTypes.ValidateMediatorOutputConnector_3625);
types.add(EsbElementTypes.ValidateMediatorOnFailOutputConnector_3626);
types.add(EsbElementTypes.RouterMediatorOutputConnector_3630);
types.add(EsbElementTypes.RouterMediatorTargetOutputConnector_3631);
types.add(EsbElementTypes.ConditionalRouterMediatorOutputConnector_3637);
types.add(EsbElementTypes.ConditionalRouterMediatorAdditionalOutputConnector_3638);
types.add(EsbElementTypes.DefaultEndPointOutputConnector_3022);
types.add(EsbElementTypes.AddressEndPointOutputConnector_3031);
types.add(EsbElementTypes.FailoverEndPointOutputConnector_3090);
types.add(EsbElementTypes.FailoverEndPointWestOutputConnector_3097);
types.add(EsbElementTypes.WSDLEndPointOutputConnector_3093);
types.add(EsbElementTypes.NamedEndpointOutputConnector_3662);
types.add(EsbElementTypes.LoadBalanceEndPointOutputConnector_3096);
types.add(EsbElementTypes.LoadBalanceEndPointWestOutputConnector_3098);
types.add(EsbElementTypes.APIResourceEndpointOutputConnector_3676);
types.add(EsbElementTypes.MessageOutputConnector_3047);
types.add(EsbElementTypes.MergeNodeOutputConnector_3016);
types.add(EsbElementTypes.SequencesOutputConnector_3617);
types.add(EsbElementTypes.DefaultEndPointOutputConnector_3645);
types.add(EsbElementTypes.AddressEndPointOutputConnector_3648);
types.add(EsbElementTypes.FailoverEndPointOutputConnector_3651);
types.add(EsbElementTypes.FailoverEndPointWestOutputConnector_3652);
types.add(EsbElementTypes.WSDLEndPointOutputConnector_3655);
types.add(EsbElementTypes.LoadBalanceEndPointOutputConnector_3658);
types.add(EsbElementTypes.LoadBalanceEndPointWestOutputConnector_3659);
types.add(EsbElementTypes.APIResourceOutputConnector_3671);
types.add(EsbElementTypes.ComplexEndpointsOutputConnector_3679);
}
return types;
}
/**
* @generated
*/
public class EastPointerFigure extends EastPointerShape {
/**
* @generated
*/
public EastPointerFigure() {
this.setBackgroundColor(THIS_BACK);
this.setPreferredSize(new Dimension(getMapMode().DPtoLP(12),
getMapMode().DPtoLP(10)));
}
}
/**
* @generated
*/
static final Color THIS_BACK = new Color(null, 50, 50, 50);
}
| apache-2.0 |
bikush/libgdxjam-space-seed-inc | core/src/com/starseed/screens/MainScreen.java | 852 | package com.starseed.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.starseed.stages.MainScreenStage;
import com.starseed.screens.AbstractScreen;
public class MainScreen extends AbstractScreen {
private MainScreenStage stage;
public MainScreen() {
super();
stage = new MainScreenStage(this);
}
@Override
public void show() {
goToNextScreen = false;
Gdx.input.setInputProcessor(stage);
}
@Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.draw();
stage.act(delta);
}
@Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
}
}
| apache-2.0 |
petrzelenka/sellcom-java-geotemporal | src/main/java/org/sellcom/geotemporal/internal/time/applicability/EvenIsoWeekNumberApplicability.java | 1183 | /*
* Copyright (c) 2015-2018 Petr Zelenka <petr.zelenka@sellcom.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.sellcom.geotemporal.internal.time.applicability;
import java.time.temporal.Temporal;
import org.sellcom.geotemporal.internal.Contract;
import org.sellcom.geotemporal.time.Temporals;
import org.sellcom.geotemporal.time.applicability.TemporalApplicability;
public final class EvenIsoWeekNumberApplicability extends TemporalApplicability {
@Override
public boolean test(Temporal temporal) {
Contract.checkArgument(temporal != null, "Temporal must not be null");
return (Temporals.getIsoWeekNumber(temporal) & 0x01) == 0x00;
}
}
| apache-2.0 |
torrances/swtk-commons | commons-dict-wordnet-indexbyname/src/main/java/org/swtk/commons/dict/wordnet/indexbyname/instance/a/d/y/WordnetNounIndexNameInstanceADY.java | 1107 | package org.swtk.commons.dict.wordnet.indexbyname.instance.a.d.y; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import java.util.TreeMap; import org.swtk.common.dict.dto.wordnet.IndexNoun; import com.trimc.blogger.commons.utils.GsonUtils; public final class WordnetNounIndexNameInstanceADY { private static Map<String, Collection<IndexNoun>> map = new TreeMap<String, Collection<IndexNoun>>(); static { add("{\"term\":\"adynamia\", \"synsetCount\":1, \"upperType\":\"NOUN\", \"ids\":[\"05047987\"]}");
} private static void add(final String JSON) { IndexNoun indexNoun = GsonUtils.toObject(JSON, IndexNoun.class); Collection<IndexNoun> list = (map.containsKey(indexNoun.getTerm())) ? map.get(indexNoun.getTerm()) : new ArrayList<IndexNoun>(); list.add(indexNoun); map.put(indexNoun.getTerm(), list); } public static Collection<IndexNoun> get(final String TERM) { return map.get(TERM); } public static boolean has(final String TERM) { return map.containsKey(TERM); } public static Collection<String> terms() { return map.keySet(); } } | apache-2.0 |
badvision/lawless-legends | Platform/Apple/tools/jace/src/main/java/jace/ide/CompileResult.java | 348 | package jace.ide;
import java.util.List;
import java.util.Map;
/**
*
* @author blurry
*/
public interface CompileResult<T> {
boolean isSuccessful();
T getCompiledAsset();
Map<Integer, String> getErrors();
Map<Integer, String> getWarnings();
List<String> getOtherMessages();
List<String> getRawOutput();
}
| apache-2.0 |
DaanHoogland/cloudstack | engine/schema/src/main/java/com/cloud/upgrade/DatabaseUpgradeChecker.java | 16974 | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.upgrade;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ObjectArrays.concat;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import javax.inject.Inject;
import org.apache.cloudstack.utils.CloudStackVersion;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.cloud.upgrade.dao.DbUpgrade;
import com.cloud.upgrade.dao.Upgrade217to218;
import com.cloud.upgrade.dao.Upgrade218to22;
import com.cloud.upgrade.dao.Upgrade218to224DomainVlans;
import com.cloud.upgrade.dao.Upgrade2210to2211;
import com.cloud.upgrade.dao.Upgrade2211to2212;
import com.cloud.upgrade.dao.Upgrade2212to2213;
import com.cloud.upgrade.dao.Upgrade2213to2214;
import com.cloud.upgrade.dao.Upgrade2214to30;
import com.cloud.upgrade.dao.Upgrade221to222;
import com.cloud.upgrade.dao.Upgrade222to224;
import com.cloud.upgrade.dao.Upgrade224to225;
import com.cloud.upgrade.dao.Upgrade225to226;
import com.cloud.upgrade.dao.Upgrade227to228;
import com.cloud.upgrade.dao.Upgrade228to229;
import com.cloud.upgrade.dao.Upgrade229to2210;
import com.cloud.upgrade.dao.Upgrade301to302;
import com.cloud.upgrade.dao.Upgrade302to303;
import com.cloud.upgrade.dao.Upgrade302to40;
import com.cloud.upgrade.dao.Upgrade303to304;
import com.cloud.upgrade.dao.Upgrade304to305;
import com.cloud.upgrade.dao.Upgrade305to306;
import com.cloud.upgrade.dao.Upgrade306to307;
import com.cloud.upgrade.dao.Upgrade307to410;
import com.cloud.upgrade.dao.Upgrade30to301;
import com.cloud.upgrade.dao.Upgrade40to41;
import com.cloud.upgrade.dao.Upgrade41000to41100;
import com.cloud.upgrade.dao.Upgrade410to420;
import com.cloud.upgrade.dao.Upgrade41100to41110;
import com.cloud.upgrade.dao.Upgrade41110to41120;
import com.cloud.upgrade.dao.Upgrade41120to41130;
import com.cloud.upgrade.dao.Upgrade41120to41200;
import com.cloud.upgrade.dao.Upgrade41200to41300;
import com.cloud.upgrade.dao.Upgrade41300to41310;
import com.cloud.upgrade.dao.Upgrade41310to41400;
import com.cloud.upgrade.dao.Upgrade420to421;
import com.cloud.upgrade.dao.Upgrade421to430;
import com.cloud.upgrade.dao.Upgrade430to440;
import com.cloud.upgrade.dao.Upgrade431to440;
import com.cloud.upgrade.dao.Upgrade432to440;
import com.cloud.upgrade.dao.Upgrade440to441;
import com.cloud.upgrade.dao.Upgrade441to442;
import com.cloud.upgrade.dao.Upgrade442to450;
import com.cloud.upgrade.dao.Upgrade443to444;
import com.cloud.upgrade.dao.Upgrade444to450;
import com.cloud.upgrade.dao.Upgrade450to451;
import com.cloud.upgrade.dao.Upgrade451to452;
import com.cloud.upgrade.dao.Upgrade452to453;
import com.cloud.upgrade.dao.Upgrade453to460;
import com.cloud.upgrade.dao.Upgrade460to461;
import com.cloud.upgrade.dao.Upgrade461to470;
import com.cloud.upgrade.dao.Upgrade470to471;
import com.cloud.upgrade.dao.Upgrade471to480;
import com.cloud.upgrade.dao.Upgrade480to481;
import com.cloud.upgrade.dao.Upgrade481to490;
import com.cloud.upgrade.dao.Upgrade490to4910;
import com.cloud.upgrade.dao.Upgrade4910to4920;
import com.cloud.upgrade.dao.Upgrade4920to4930;
import com.cloud.upgrade.dao.Upgrade4930to41000;
import com.cloud.upgrade.dao.UpgradeSnapshot217to224;
import com.cloud.upgrade.dao.UpgradeSnapshot223to224;
import com.cloud.upgrade.dao.VersionDao;
import com.cloud.upgrade.dao.VersionDaoImpl;
import com.cloud.upgrade.dao.VersionVO;
import com.cloud.upgrade.dao.VersionVO.Step;
import com.cloud.utils.component.SystemIntegrityChecker;
import com.cloud.utils.db.GlobalLock;
import com.cloud.utils.db.ScriptRunner;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.exception.CloudRuntimeException;
import com.google.common.annotations.VisibleForTesting;
public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
private static final Logger s_logger = Logger.getLogger(DatabaseUpgradeChecker.class);
private final DatabaseVersionHierarchy hierarchy;
@Inject
VersionDao _dao;
public DatabaseUpgradeChecker() {
_dao = new VersionDaoImpl();
hierarchy = DatabaseVersionHierarchy.builder()
// legacy
.next("2.1.7" , new Upgrade217to218())
.next("2.1.7.1" , new UpgradeSnapshot217to224())
.next("2.1.8" , new Upgrade218to22())
.next("2.1.8.1" , new Upgrade218to224DomainVlans())
.next("2.1.9" , new Upgrade218to22())
.next("2.2.1" , new Upgrade221to222())
.next("2.2.2" , new Upgrade222to224())
.next("2.2.3" , new Upgrade222to224())
.next("2.2.3.1" , new UpgradeSnapshot223to224())
.next("2.2.4" , new Upgrade224to225())
.next("2.2.5" , new Upgrade225to226())
.next("2.2.6" , new Upgrade227to228())
.next("2.2.7" , new Upgrade227to228())
.next("2.2.8" , new Upgrade228to229())
.next("2.2.9" , new Upgrade229to2210())
.next("2.2.10" , new Upgrade2210to2211())
.next("2.2.11" , new Upgrade2211to2212())
.next("2.2.12" , new Upgrade2212to2213())
.next("2.2.13" , new Upgrade2213to2214())
.next("2.2.14" , new Upgrade2214to30())
.next("2.2.15" , new Upgrade2214to30())
.next("2.2.16" , new Upgrade2214to30())
.next("3.0.0" , new Upgrade30to301())
.next("3.0.1" , new Upgrade301to302())
.next("3.0.2" , new Upgrade302to303())
.next("3.0.2.1" , new Upgrade302to40())
.next("3.0.3" , new Upgrade303to304())
.next("3.0.4" , new Upgrade304to305())
.next("3.0.5" , new Upgrade305to306())
.next("3.0.6" , new Upgrade306to307())
.next("3.0.7" , new Upgrade307to410())
// recent
.next("4.0.0" , new Upgrade40to41())
.next("4.0.1" , new Upgrade40to41())
.next("4.0.2" , new Upgrade40to41())
.next("4.1.0" , new Upgrade410to420())
.next("4.1.1" , new Upgrade410to420())
.next("4.2.0" , new Upgrade420to421())
.next("4.2.1" , new Upgrade421to430())
.next("4.3.0" , new Upgrade430to440())
.next("4.3.1" , new Upgrade431to440())
.next("4.3.2" , new Upgrade432to440())
.next("4.4.0" , new Upgrade440to441())
.next("4.4.1" , new Upgrade441to442())
.next("4.4.2" , new Upgrade442to450())
.next("4.4.3" , new Upgrade443to444())
.next("4.4.4" , new Upgrade444to450())
.next("4.5.0" , new Upgrade450to451())
.next("4.5.1" , new Upgrade451to452())
.next("4.5.2" , new Upgrade452to453())
.next("4.5.3" , new Upgrade453to460())
.next("4.6.0" , new Upgrade460to461())
.next("4.6.1" , new Upgrade461to470())
.next("4.6.2" , new Upgrade461to470())
.next("4.7.0" , new Upgrade470to471())
.next("4.7.1" , new Upgrade471to480())
.next("4.7.2" , new Upgrade471to480())
.next("4.8.0" , new Upgrade480to481())
.next("4.8.1" , new Upgrade481to490())
.next("4.8.2.0" , new Upgrade481to490())
.next("4.9.0" , new Upgrade490to4910())
.next("4.9.1.0" , new Upgrade4910to4920())
.next("4.9.2.0" , new Upgrade4920to4930())
.next("4.9.3.0" , new Upgrade4930to41000())
.next("4.9.3.1" , new Upgrade4930to41000())
.next("4.10.0.0", new Upgrade41000to41100())
.next("4.11.0.0", new Upgrade41100to41110())
.next("4.11.1.0", new Upgrade41110to41120())
.next("4.11.2.0", new Upgrade41120to41130())
.next("4.11.3.0", new Upgrade41120to41200())
.next("4.12.0.0", new Upgrade41200to41300())
.next("4.13.0.0", new Upgrade41300to41310())
.next("4.13.1.0", new Upgrade41310to41400())
.build();
}
protected void runScript(Connection conn, InputStream file) {
try (InputStreamReader reader = new InputStreamReader(file)) {
ScriptRunner runner = new ScriptRunner(conn, false, true);
runner.runScript(reader);
} catch (IOException e) {
s_logger.error("Unable to read upgrade script", e);
throw new CloudRuntimeException("Unable to read upgrade script", e);
} catch (SQLException e) {
s_logger.error("Unable to execute upgrade script", e);
throw new CloudRuntimeException("Unable to execute upgrade script", e);
}
}
@VisibleForTesting
DbUpgrade[] calculateUpgradePath(final CloudStackVersion dbVersion, final CloudStackVersion currentVersion) {
checkArgument(dbVersion != null);
checkArgument(currentVersion != null);
checkArgument(currentVersion.compareTo(dbVersion) > 0);
final DbUpgrade[] upgrades = hierarchy.getPath(dbVersion, currentVersion);
// When there is no upgrade defined for the target version, we assume that there were no schema changes or
// data migrations required. Based on that assumption, we add a noop DbUpgrade to the end of the list ...
final CloudStackVersion tailVersion = upgrades.length > 0 ? CloudStackVersion.parse(upgrades[upgrades.length - 1].getUpgradedVersion()) : dbVersion;
if (currentVersion.compareTo(tailVersion) != 0) {
return concat(upgrades, new NoopDbUpgrade(tailVersion, currentVersion));
}
return upgrades;
}
protected void upgrade(CloudStackVersion dbVersion, CloudStackVersion currentVersion) {
s_logger.info("Database upgrade must be performed from " + dbVersion + " to " + currentVersion);
final DbUpgrade[] upgrades = calculateUpgradePath(dbVersion, currentVersion);
for (DbUpgrade upgrade : upgrades) {
VersionVO version;
s_logger.debug("Running upgrade " + upgrade.getClass().getSimpleName() + " to upgrade from " + upgrade.getUpgradableVersionRange()[0] + "-" + upgrade
.getUpgradableVersionRange()[1] + " to " + upgrade.getUpgradedVersion());
TransactionLegacy txn = TransactionLegacy.open("Upgrade");
txn.start();
try {
Connection conn;
try {
conn = txn.getConnection();
} catch (SQLException e) {
String errorMessage = "Unable to upgrade the database";
s_logger.error(errorMessage, e);
throw new CloudRuntimeException(errorMessage, e);
}
InputStream[] scripts = upgrade.getPrepareScripts();
if (scripts != null) {
for (InputStream script : scripts) {
runScript(conn, script);
}
}
upgrade.performDataMigration(conn);
version = new VersionVO(upgrade.getUpgradedVersion());
version = _dao.persist(version);
txn.commit();
} catch (CloudRuntimeException e) {
String errorMessage = "Unable to upgrade the database";
s_logger.error(errorMessage, e);
throw new CloudRuntimeException(errorMessage, e);
} finally {
txn.close();
}
// Run the corresponding '-cleanup.sql' script
txn = TransactionLegacy.open("Cleanup");
try {
s_logger.info("Cleanup upgrade " + upgrade.getClass().getSimpleName() + " to upgrade from " + upgrade.getUpgradableVersionRange()[0] + "-" + upgrade
.getUpgradableVersionRange()[1] + " to " + upgrade.getUpgradedVersion());
txn.start();
Connection conn;
try {
conn = txn.getConnection();
} catch (SQLException e) {
s_logger.error("Unable to cleanup the database", e);
throw new CloudRuntimeException("Unable to cleanup the database", e);
}
InputStream[] scripts = upgrade.getCleanupScripts();
if (scripts != null) {
for (InputStream script : scripts) {
runScript(conn, script);
s_logger.debug("Cleanup script " + upgrade.getClass().getSimpleName() + " is executed successfully");
}
}
txn.commit();
txn.start();
version.setStep(Step.Complete);
version.setUpdated(new Date());
_dao.update(version.getId(), version);
txn.commit();
s_logger.debug("Upgrade completed for version " + version.getVersion());
} finally {
txn.close();
}
}
}
@Override
public void check() {
GlobalLock lock = GlobalLock.getInternLock("DatabaseUpgrade");
try {
s_logger.info("Grabbing lock to check for database upgrade.");
if (!lock.lock(20 * 60)) {
throw new CloudRuntimeException("Unable to acquire lock to check for database integrity.");
}
try {
final CloudStackVersion dbVersion = CloudStackVersion.parse(_dao.getCurrentVersion());
final String currentVersionValue = this.getClass().getPackage().getImplementationVersion();
if (StringUtils.isBlank(currentVersionValue)) {
return;
}
final CloudStackVersion currentVersion = CloudStackVersion.parse(currentVersionValue);
s_logger.info("DB version = " + dbVersion + " Code Version = " + currentVersion);
if (dbVersion.compareTo(currentVersion) > 0) {
throw new CloudRuntimeException("Database version " + dbVersion + " is higher than management software version " + currentVersionValue);
}
if (dbVersion.compareTo(currentVersion) == 0) {
s_logger.info("DB version and code version matches so no upgrade needed.");
return;
}
upgrade(dbVersion, currentVersion);
} finally {
lock.unlock();
}
} finally {
lock.releaseRef();
}
}
@VisibleForTesting
protected static final class NoopDbUpgrade implements DbUpgrade {
private final String upgradedVersion;
private final String[] upgradeRange;
private NoopDbUpgrade(final CloudStackVersion fromVersion, final CloudStackVersion toVersion) {
super();
upgradedVersion = toVersion.toString();
upgradeRange = new String[] {fromVersion.toString(), toVersion.toString()};
}
@Override
public String[] getUpgradableVersionRange() {
return Arrays.copyOf(upgradeRange, upgradeRange.length);
}
@Override
public String getUpgradedVersion() {
return upgradedVersion;
}
@Override
public boolean supportsRollingUpgrade() {
return false;
}
@Override
public InputStream[] getPrepareScripts() {
return new InputStream[0];
}
@Override
public void performDataMigration(Connection conn) {
}
@Override
public InputStream[] getCleanupScripts() {
return new InputStream[0];
}
}
}
| apache-2.0 |
googleads/google-ads-java | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/services/stub/GrpcCampaignFeedServiceStub.java | 6493 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ads.googleads.v10.services.stub;
import com.google.ads.googleads.v10.services.MutateCampaignFeedsRequest;
import com.google.ads.googleads.v10.services.MutateCampaignFeedsResponse;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.common.collect.ImmutableMap;
import com.google.longrunning.stub.GrpcOperationsStub;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC stub implementation for the CampaignFeedService service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public class GrpcCampaignFeedServiceStub extends CampaignFeedServiceStub {
private static final MethodDescriptor<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse>
mutateCampaignFeedsMethodDescriptor =
MethodDescriptor.<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.ads.googleads.v10.services.CampaignFeedService/MutateCampaignFeeds")
.setRequestMarshaller(
ProtoUtils.marshaller(MutateCampaignFeedsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(MutateCampaignFeedsResponse.getDefaultInstance()))
.build();
private final UnaryCallable<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse>
mutateCampaignFeedsCallable;
private final BackgroundResource backgroundResources;
private final GrpcOperationsStub operationsStub;
private final GrpcStubCallableFactory callableFactory;
public static final GrpcCampaignFeedServiceStub create(CampaignFeedServiceStubSettings settings)
throws IOException {
return new GrpcCampaignFeedServiceStub(settings, ClientContext.create(settings));
}
public static final GrpcCampaignFeedServiceStub create(ClientContext clientContext)
throws IOException {
return new GrpcCampaignFeedServiceStub(
CampaignFeedServiceStubSettings.newBuilder().build(), clientContext);
}
public static final GrpcCampaignFeedServiceStub create(
ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
return new GrpcCampaignFeedServiceStub(
CampaignFeedServiceStubSettings.newBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of GrpcCampaignFeedServiceStub, using the given settings. This is
* protected so that it is easy to make a subclass, but otherwise, the static factory methods
* should be preferred.
*/
protected GrpcCampaignFeedServiceStub(
CampaignFeedServiceStubSettings settings, ClientContext clientContext) throws IOException {
this(settings, clientContext, new GrpcCampaignFeedServiceCallableFactory());
}
/**
* Constructs an instance of GrpcCampaignFeedServiceStub, using the given settings. This is
* protected so that it is easy to make a subclass, but otherwise, the static factory methods
* should be preferred.
*/
protected GrpcCampaignFeedServiceStub(
CampaignFeedServiceStubSettings settings,
ClientContext clientContext,
GrpcStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory);
GrpcCallSettings<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse>
mutateCampaignFeedsTransportSettings =
GrpcCallSettings.<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse>newBuilder()
.setMethodDescriptor(mutateCampaignFeedsMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("customer_id", String.valueOf(request.getCustomerId()));
return params.build();
})
.build();
this.mutateCampaignFeedsCallable =
callableFactory.createUnaryCallable(
mutateCampaignFeedsTransportSettings,
settings.mutateCampaignFeedsSettings(),
clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
public GrpcOperationsStub getOperationsStub() {
return operationsStub;
}
@Override
public UnaryCallable<MutateCampaignFeedsRequest, MutateCampaignFeedsResponse>
mutateCampaignFeedsCallable() {
return mutateCampaignFeedsCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
| apache-2.0 |
an3m0na/hadoop | hadoop-tools/hadoop-posum/src/main/java/org/apache/hadoop/tools/posum/common/records/call/query/impl/pb/PropertyRangeQueryPBImpl.java | 5139 | package org.apache.hadoop.tools.posum.common.records.call.query.impl.pb;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.TextFormat;
import org.apache.hadoop.tools.posum.common.records.call.query.PropertyRangeQuery;
import org.apache.hadoop.tools.posum.common.records.payload.SimplePropertyPayload;
import org.apache.hadoop.tools.posum.common.records.payload.impl.pb.SimplePropertyPayloadPBImpl;
import org.apache.hadoop.tools.posum.common.records.pb.PayloadPB;
import org.apache.hadoop.yarn.proto.PosumProtos.PropertyRangeQueryProto;
import org.apache.hadoop.yarn.proto.PosumProtos.PropertyRangeQueryProtoOrBuilder;
import org.apache.hadoop.yarn.proto.PosumProtos.SimplePropertyPayloadProto;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class PropertyRangeQueryPBImpl extends PropertyRangeQuery implements PayloadPB {
private PropertyRangeQueryProto proto = PropertyRangeQueryProto.getDefaultInstance();
private PropertyRangeQueryProto.Builder builder = null;
private boolean viaProto = false;
private List<Object> values;
public PropertyRangeQueryPBImpl() {
builder = PropertyRangeQueryProto.newBuilder();
}
public PropertyRangeQueryPBImpl(PropertyRangeQueryProto proto) {
this.proto = proto;
viaProto = true;
}
public PropertyRangeQueryProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
@Override
public int hashCode() {
return getProto().hashCode();
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other.getClass().isAssignableFrom(this.getClass())) {
return this.getProto().equals(this.getClass().cast(other).getProto());
}
return false;
}
@Override
public String toString() {
return TextFormat.shortDebugString(getProto());
}
private void mergeLocalToBuilder() {
maybeInitBuilder();
if (values == null)
return;
builder.clearValues();
final Iterable<SimplePropertyPayloadProto> iterable =
new Iterable<SimplePropertyPayloadProto>() {
@Override
public Iterator<SimplePropertyPayloadProto> iterator() {
return new Iterator<SimplePropertyPayloadProto>() {
Iterator<?> iterator = values.iterator();
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public SimplePropertyPayloadProto next() {
SimplePropertyPayload propertyValue =
SimplePropertyPayload.newInstance("", iterator.next());
return ((SimplePropertyPayloadPBImpl) propertyValue).getProto();
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
};
}
};
builder.addAllValues(iterable);
}
private void mergeLocalToProto() {
if (viaProto)
maybeInitBuilder();
mergeLocalToBuilder();
proto = builder.build();
viaProto = true;
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = PropertyRangeQueryProto.newBuilder(proto);
}
viaProto = false;
}
@Override
public String getPropertyName() {
PropertyRangeQueryProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasPropertyName())
return null;
return p.getPropertyName();
}
@Override
public void setPropertyName(String propertyName) {
maybeInitBuilder();
if (propertyName == null) {
builder.clearPropertyName();
return;
}
builder.setPropertyName(propertyName);
}
@Override
public Type getType() {
PropertyRangeQueryProtoOrBuilder p = viaProto ? proto : builder;
if (!p.hasType())
return null;
return Type.valueOf(p.getType().name().substring("RQRY_".length()));
}
@Override
public void setType(Type type) {
maybeInitBuilder();
if (type == null) {
builder.clearType();
return;
}
builder.setType(PropertyRangeQueryProto.TypeProto.valueOf("RQRY_" + type.name()));
}
@Override
public <T> List<T> getValues() {
if (values == null) {
PropertyRangeQueryProtoOrBuilder p = viaProto ? proto : builder;
values = new ArrayList<>(p.getValuesCount());
for (SimplePropertyPayloadProto propertyProto : p.getValuesList()) {
values.add(new SimplePropertyPayloadPBImpl(propertyProto).getValueAs());
}
}
return (List<T>) values;
}
@Override
public void setValues(List<?> values) {
maybeInitBuilder();
if(values == null){
builder.clearValues();
this.values = null;
return;
}
this.values = new ArrayList<>(values);
}
@Override
public ByteString getProtoBytes() {
return getProto().toByteString();
}
@Override
public void populateFromProtoBytes(ByteString data) throws InvalidProtocolBufferException {
proto = PropertyRangeQueryProto.parseFrom(data);
viaProto = true;
}
}
| apache-2.0 |
hstoenescu/PracticalTest02 | PracticalTest2/app/src/main/java/practicaltest02/eim/systems/cs/pub/ro/practicaltest2/general/Utilities.java | 608 | package practicaltest02.eim.systems.cs.pub.ro.practicaltest2.general;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Created by student on 19.05.2017.
*/
public class Utilities {
public static BufferedReader getReader(Socket socket) throws IOException {
return new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
public static PrintWriter getWriter(Socket socket) throws IOException {
return new PrintWriter(socket.getOutputStream(), true);
}
}
| apache-2.0 |
josephmmhot/java-facelets | src/main/java/joe/SessionInfo.java | 706 | package joe;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
@ManagedBean
@SessionScoped
public class SessionInfo implements Serializable {
private static final long serialVersionUID = 1L;
public String getSessionId() {
HttpSession session = getHttpSession();
String sessionId = session.getId();
return sessionId;
}
private HttpSession getHttpSession() {
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
return session;
}
}
| apache-2.0 |
UniquePassive/JSteamKit | src/main/java/com/jsteamkit/internals/proto/SteammessagesOfflineSteamclient.java | 110790 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: steammessages_offline.steamclient.proto
package com.jsteamkit.internals.proto;
public final class SteammessagesOfflineSteamclient {
private SteammessagesOfflineSteamclient() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface COffline_GetOfflineLogonTicket_RequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:COffline_GetOfflineLogonTicket_Request)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional uint32 priority = 1;</code>
*/
boolean hasPriority();
/**
* <code>optional uint32 priority = 1;</code>
*/
int getPriority();
}
/**
* Protobuf type {@code COffline_GetOfflineLogonTicket_Request}
*/
public static final class COffline_GetOfflineLogonTicket_Request extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:COffline_GetOfflineLogonTicket_Request)
COffline_GetOfflineLogonTicket_RequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use COffline_GetOfflineLogonTicket_Request.newBuilder() to construct.
private COffline_GetOfflineLogonTicket_Request(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private COffline_GetOfflineLogonTicket_Request() {
priority_ = 0;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private COffline_GetOfflineLogonTicket_Request(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
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;
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
priority_ = input.readUInt32();
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 SteammessagesOfflineSteamclient.internal_static_COffline_GetOfflineLogonTicket_Request_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetOfflineLogonTicket_Request_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request.class, SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request.Builder.class);
}
private int bitField0_;
public static final int PRIORITY_FIELD_NUMBER = 1;
private int priority_;
/**
* <code>optional uint32 priority = 1;</code>
*/
public boolean hasPriority() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional uint32 priority = 1;</code>
*/
public int getPriority() {
return priority_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeUInt32(1, priority_);
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(1, priority_);
}
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 SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request)) {
return super.equals(obj);
}
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request other = (SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request) obj;
boolean result = true;
result = result && (hasPriority() == other.hasPriority());
if (hasPriority()) {
result = result && (getPriority()
== other.getPriority());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasPriority()) {
hash = (37 * hash) + PRIORITY_FIELD_NUMBER;
hash = (53 * hash) + getPriority();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request 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 SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request 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 SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
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;
}
/**
* Protobuf type {@code COffline_GetOfflineLogonTicket_Request}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:COffline_GetOfflineLogonTicket_Request)
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_RequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetOfflineLogonTicket_Request_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetOfflineLogonTicket_Request_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request.class, SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request.Builder.class);
}
// Construct using SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
priority_ = 0;
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetOfflineLogonTicket_Request_descriptor;
}
public SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request getDefaultInstanceForType() {
return SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request.getDefaultInstance();
}
public SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request build() {
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request buildPartial() {
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request result = new SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.priority_ = priority_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request) {
return mergeFrom((SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request other) {
if (other == SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request.getDefaultInstance()) return this;
if (other.hasPriority()) {
setPriority(other.getPriority());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private int priority_ ;
/**
* <code>optional uint32 priority = 1;</code>
*/
public boolean hasPriority() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional uint32 priority = 1;</code>
*/
public int getPriority() {
return priority_;
}
/**
* <code>optional uint32 priority = 1;</code>
*/
public Builder setPriority(int value) {
bitField0_ |= 0x00000001;
priority_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 priority = 1;</code>
*/
public Builder clearPriority() {
bitField0_ = (bitField0_ & ~0x00000001);
priority_ = 0;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:COffline_GetOfflineLogonTicket_Request)
}
// @@protoc_insertion_point(class_scope:COffline_GetOfflineLogonTicket_Request)
private static final SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request();
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated public static final com.google.protobuf.Parser<COffline_GetOfflineLogonTicket_Request>
PARSER = new com.google.protobuf.AbstractParser<COffline_GetOfflineLogonTicket_Request>() {
public COffline_GetOfflineLogonTicket_Request parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new COffline_GetOfflineLogonTicket_Request(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<COffline_GetOfflineLogonTicket_Request> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<COffline_GetOfflineLogonTicket_Request> getParserForType() {
return PARSER;
}
public SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Request getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface COffline_GetOfflineLogonTicket_ResponseOrBuilder extends
// @@protoc_insertion_point(interface_extends:COffline_GetOfflineLogonTicket_Response)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional bytes serialized_ticket = 1;</code>
*/
boolean hasSerializedTicket();
/**
* <code>optional bytes serialized_ticket = 1;</code>
*/
com.google.protobuf.ByteString getSerializedTicket();
/**
* <code>optional bytes signature = 2;</code>
*/
boolean hasSignature();
/**
* <code>optional bytes signature = 2;</code>
*/
com.google.protobuf.ByteString getSignature();
}
/**
* Protobuf type {@code COffline_GetOfflineLogonTicket_Response}
*/
public static final class COffline_GetOfflineLogonTicket_Response extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:COffline_GetOfflineLogonTicket_Response)
COffline_GetOfflineLogonTicket_ResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use COffline_GetOfflineLogonTicket_Response.newBuilder() to construct.
private COffline_GetOfflineLogonTicket_Response(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private COffline_GetOfflineLogonTicket_Response() {
serializedTicket_ = com.google.protobuf.ByteString.EMPTY;
signature_ = com.google.protobuf.ByteString.EMPTY;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private COffline_GetOfflineLogonTicket_Response(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
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;
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
bitField0_ |= 0x00000001;
serializedTicket_ = input.readBytes();
break;
}
case 18: {
bitField0_ |= 0x00000002;
signature_ = input.readBytes();
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 SteammessagesOfflineSteamclient.internal_static_COffline_GetOfflineLogonTicket_Response_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetOfflineLogonTicket_Response_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response.class, SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response.Builder.class);
}
private int bitField0_;
public static final int SERIALIZED_TICKET_FIELD_NUMBER = 1;
private com.google.protobuf.ByteString serializedTicket_;
/**
* <code>optional bytes serialized_ticket = 1;</code>
*/
public boolean hasSerializedTicket() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional bytes serialized_ticket = 1;</code>
*/
public com.google.protobuf.ByteString getSerializedTicket() {
return serializedTicket_;
}
public static final int SIGNATURE_FIELD_NUMBER = 2;
private com.google.protobuf.ByteString signature_;
/**
* <code>optional bytes signature = 2;</code>
*/
public boolean hasSignature() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional bytes signature = 2;</code>
*/
public com.google.protobuf.ByteString getSignature() {
return signature_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, serializedTicket_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, signature_);
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, serializedTicket_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, signature_);
}
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 SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response)) {
return super.equals(obj);
}
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response other = (SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response) obj;
boolean result = true;
result = result && (hasSerializedTicket() == other.hasSerializedTicket());
if (hasSerializedTicket()) {
result = result && getSerializedTicket()
.equals(other.getSerializedTicket());
}
result = result && (hasSignature() == other.hasSignature());
if (hasSignature()) {
result = result && getSignature()
.equals(other.getSignature());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasSerializedTicket()) {
hash = (37 * hash) + SERIALIZED_TICKET_FIELD_NUMBER;
hash = (53 * hash) + getSerializedTicket().hashCode();
}
if (hasSignature()) {
hash = (37 * hash) + SIGNATURE_FIELD_NUMBER;
hash = (53 * hash) + getSignature().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response 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 SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response 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 SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
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;
}
/**
* Protobuf type {@code COffline_GetOfflineLogonTicket_Response}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:COffline_GetOfflineLogonTicket_Response)
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_ResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetOfflineLogonTicket_Response_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetOfflineLogonTicket_Response_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response.class, SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response.Builder.class);
}
// Construct using SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
serializedTicket_ = com.google.protobuf.ByteString.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
signature_ = com.google.protobuf.ByteString.EMPTY;
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetOfflineLogonTicket_Response_descriptor;
}
public SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response getDefaultInstanceForType() {
return SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response.getDefaultInstance();
}
public SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response build() {
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response buildPartial() {
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response result = new SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.serializedTicket_ = serializedTicket_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.signature_ = signature_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response) {
return mergeFrom((SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response other) {
if (other == SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response.getDefaultInstance()) return this;
if (other.hasSerializedTicket()) {
setSerializedTicket(other.getSerializedTicket());
}
if (other.hasSignature()) {
setSignature(other.getSignature());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private com.google.protobuf.ByteString serializedTicket_ = com.google.protobuf.ByteString.EMPTY;
/**
* <code>optional bytes serialized_ticket = 1;</code>
*/
public boolean hasSerializedTicket() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional bytes serialized_ticket = 1;</code>
*/
public com.google.protobuf.ByteString getSerializedTicket() {
return serializedTicket_;
}
/**
* <code>optional bytes serialized_ticket = 1;</code>
*/
public Builder setSerializedTicket(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
serializedTicket_ = value;
onChanged();
return this;
}
/**
* <code>optional bytes serialized_ticket = 1;</code>
*/
public Builder clearSerializedTicket() {
bitField0_ = (bitField0_ & ~0x00000001);
serializedTicket_ = getDefaultInstance().getSerializedTicket();
onChanged();
return this;
}
private com.google.protobuf.ByteString signature_ = com.google.protobuf.ByteString.EMPTY;
/**
* <code>optional bytes signature = 2;</code>
*/
public boolean hasSignature() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional bytes signature = 2;</code>
*/
public com.google.protobuf.ByteString getSignature() {
return signature_;
}
/**
* <code>optional bytes signature = 2;</code>
*/
public Builder setSignature(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
signature_ = value;
onChanged();
return this;
}
/**
* <code>optional bytes signature = 2;</code>
*/
public Builder clearSignature() {
bitField0_ = (bitField0_ & ~0x00000002);
signature_ = getDefaultInstance().getSignature();
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:COffline_GetOfflineLogonTicket_Response)
}
// @@protoc_insertion_point(class_scope:COffline_GetOfflineLogonTicket_Response)
private static final SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response();
}
public static SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated public static final com.google.protobuf.Parser<COffline_GetOfflineLogonTicket_Response>
PARSER = new com.google.protobuf.AbstractParser<COffline_GetOfflineLogonTicket_Response>() {
public COffline_GetOfflineLogonTicket_Response parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new COffline_GetOfflineLogonTicket_Response(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<COffline_GetOfflineLogonTicket_Response> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<COffline_GetOfflineLogonTicket_Response> getParserForType() {
return PARSER;
}
public SteammessagesOfflineSteamclient.COffline_GetOfflineLogonTicket_Response getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface COffline_GetUnsignedOfflineLogonTicket_RequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:COffline_GetUnsignedOfflineLogonTicket_Request)
com.google.protobuf.MessageOrBuilder {
}
/**
* Protobuf type {@code COffline_GetUnsignedOfflineLogonTicket_Request}
*/
public static final class COffline_GetUnsignedOfflineLogonTicket_Request extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:COffline_GetUnsignedOfflineLogonTicket_Request)
COffline_GetUnsignedOfflineLogonTicket_RequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use COffline_GetUnsignedOfflineLogonTicket_Request.newBuilder() to construct.
private COffline_GetUnsignedOfflineLogonTicket_Request(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private COffline_GetUnsignedOfflineLogonTicket_Request() {
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private COffline_GetUnsignedOfflineLogonTicket_Request(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
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;
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 SteammessagesOfflineSteamclient.internal_static_COffline_GetUnsignedOfflineLogonTicket_Request_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetUnsignedOfflineLogonTicket_Request_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request.class, SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request.Builder.class);
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
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 SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request)) {
return super.equals(obj);
}
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request other = (SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request) obj;
boolean result = true;
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request 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 SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request 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 SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
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;
}
/**
* Protobuf type {@code COffline_GetUnsignedOfflineLogonTicket_Request}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:COffline_GetUnsignedOfflineLogonTicket_Request)
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_RequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetUnsignedOfflineLogonTicket_Request_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetUnsignedOfflineLogonTicket_Request_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request.class, SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request.Builder.class);
}
// Construct using SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetUnsignedOfflineLogonTicket_Request_descriptor;
}
public SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request getDefaultInstanceForType() {
return SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request.getDefaultInstance();
}
public SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request build() {
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request buildPartial() {
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request result = new SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request(this);
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request) {
return mergeFrom((SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request other) {
if (other == SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request.getDefaultInstance()) return this;
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:COffline_GetUnsignedOfflineLogonTicket_Request)
}
// @@protoc_insertion_point(class_scope:COffline_GetUnsignedOfflineLogonTicket_Request)
private static final SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request();
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated public static final com.google.protobuf.Parser<COffline_GetUnsignedOfflineLogonTicket_Request>
PARSER = new com.google.protobuf.AbstractParser<COffline_GetUnsignedOfflineLogonTicket_Request>() {
public COffline_GetUnsignedOfflineLogonTicket_Request parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new COffline_GetUnsignedOfflineLogonTicket_Request(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<COffline_GetUnsignedOfflineLogonTicket_Request> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<COffline_GetUnsignedOfflineLogonTicket_Request> getParserForType() {
return PARSER;
}
public SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Request getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface COffline_OfflineLogonTicketOrBuilder extends
// @@protoc_insertion_point(interface_extends:COffline_OfflineLogonTicket)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional uint32 accountid = 1;</code>
*/
boolean hasAccountid();
/**
* <code>optional uint32 accountid = 1;</code>
*/
int getAccountid();
/**
* <code>optional fixed32 rtime32_creation_time = 2;</code>
*/
boolean hasRtime32CreationTime();
/**
* <code>optional fixed32 rtime32_creation_time = 2;</code>
*/
int getRtime32CreationTime();
}
/**
* Protobuf type {@code COffline_OfflineLogonTicket}
*/
public static final class COffline_OfflineLogonTicket extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:COffline_OfflineLogonTicket)
COffline_OfflineLogonTicketOrBuilder {
private static final long serialVersionUID = 0L;
// Use COffline_OfflineLogonTicket.newBuilder() to construct.
private COffline_OfflineLogonTicket(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private COffline_OfflineLogonTicket() {
accountid_ = 0;
rtime32CreationTime_ = 0;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private COffline_OfflineLogonTicket(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
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;
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
accountid_ = input.readUInt32();
break;
}
case 21: {
bitField0_ |= 0x00000002;
rtime32CreationTime_ = input.readFixed32();
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 SteammessagesOfflineSteamclient.internal_static_COffline_OfflineLogonTicket_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return SteammessagesOfflineSteamclient.internal_static_COffline_OfflineLogonTicket_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.class, SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.Builder.class);
}
private int bitField0_;
public static final int ACCOUNTID_FIELD_NUMBER = 1;
private int accountid_;
/**
* <code>optional uint32 accountid = 1;</code>
*/
public boolean hasAccountid() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional uint32 accountid = 1;</code>
*/
public int getAccountid() {
return accountid_;
}
public static final int RTIME32_CREATION_TIME_FIELD_NUMBER = 2;
private int rtime32CreationTime_;
/**
* <code>optional fixed32 rtime32_creation_time = 2;</code>
*/
public boolean hasRtime32CreationTime() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional fixed32 rtime32_creation_time = 2;</code>
*/
public int getRtime32CreationTime() {
return rtime32CreationTime_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeUInt32(1, accountid_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeFixed32(2, rtime32CreationTime_);
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(1, accountid_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeFixed32Size(2, rtime32CreationTime_);
}
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 SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket)) {
return super.equals(obj);
}
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket other = (SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket) obj;
boolean result = true;
result = result && (hasAccountid() == other.hasAccountid());
if (hasAccountid()) {
result = result && (getAccountid()
== other.getAccountid());
}
result = result && (hasRtime32CreationTime() == other.hasRtime32CreationTime());
if (hasRtime32CreationTime()) {
result = result && (getRtime32CreationTime()
== other.getRtime32CreationTime());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasAccountid()) {
hash = (37 * hash) + ACCOUNTID_FIELD_NUMBER;
hash = (53 * hash) + getAccountid();
}
if (hasRtime32CreationTime()) {
hash = (37 * hash) + RTIME32_CREATION_TIME_FIELD_NUMBER;
hash = (53 * hash) + getRtime32CreationTime();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket 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 SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket 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 SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
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;
}
/**
* Protobuf type {@code COffline_OfflineLogonTicket}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:COffline_OfflineLogonTicket)
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicketOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return SteammessagesOfflineSteamclient.internal_static_COffline_OfflineLogonTicket_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return SteammessagesOfflineSteamclient.internal_static_COffline_OfflineLogonTicket_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.class, SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.Builder.class);
}
// Construct using SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
accountid_ = 0;
bitField0_ = (bitField0_ & ~0x00000001);
rtime32CreationTime_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return SteammessagesOfflineSteamclient.internal_static_COffline_OfflineLogonTicket_descriptor;
}
public SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket getDefaultInstanceForType() {
return SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.getDefaultInstance();
}
public SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket build() {
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket buildPartial() {
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket result = new SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.accountid_ = accountid_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.rtime32CreationTime_ = rtime32CreationTime_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket) {
return mergeFrom((SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket other) {
if (other == SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.getDefaultInstance()) return this;
if (other.hasAccountid()) {
setAccountid(other.getAccountid());
}
if (other.hasRtime32CreationTime()) {
setRtime32CreationTime(other.getRtime32CreationTime());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private int accountid_ ;
/**
* <code>optional uint32 accountid = 1;</code>
*/
public boolean hasAccountid() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional uint32 accountid = 1;</code>
*/
public int getAccountid() {
return accountid_;
}
/**
* <code>optional uint32 accountid = 1;</code>
*/
public Builder setAccountid(int value) {
bitField0_ |= 0x00000001;
accountid_ = value;
onChanged();
return this;
}
/**
* <code>optional uint32 accountid = 1;</code>
*/
public Builder clearAccountid() {
bitField0_ = (bitField0_ & ~0x00000001);
accountid_ = 0;
onChanged();
return this;
}
private int rtime32CreationTime_ ;
/**
* <code>optional fixed32 rtime32_creation_time = 2;</code>
*/
public boolean hasRtime32CreationTime() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional fixed32 rtime32_creation_time = 2;</code>
*/
public int getRtime32CreationTime() {
return rtime32CreationTime_;
}
/**
* <code>optional fixed32 rtime32_creation_time = 2;</code>
*/
public Builder setRtime32CreationTime(int value) {
bitField0_ |= 0x00000002;
rtime32CreationTime_ = value;
onChanged();
return this;
}
/**
* <code>optional fixed32 rtime32_creation_time = 2;</code>
*/
public Builder clearRtime32CreationTime() {
bitField0_ = (bitField0_ & ~0x00000002);
rtime32CreationTime_ = 0;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:COffline_OfflineLogonTicket)
}
// @@protoc_insertion_point(class_scope:COffline_OfflineLogonTicket)
private static final SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket();
}
public static SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated public static final com.google.protobuf.Parser<COffline_OfflineLogonTicket>
PARSER = new com.google.protobuf.AbstractParser<COffline_OfflineLogonTicket>() {
public COffline_OfflineLogonTicket parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new COffline_OfflineLogonTicket(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<COffline_OfflineLogonTicket> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<COffline_OfflineLogonTicket> getParserForType() {
return PARSER;
}
public SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
public interface COffline_GetUnsignedOfflineLogonTicket_ResponseOrBuilder extends
// @@protoc_insertion_point(interface_extends:COffline_GetUnsignedOfflineLogonTicket_Response)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
boolean hasTicket();
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket getTicket();
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicketOrBuilder getTicketOrBuilder();
}
/**
* Protobuf type {@code COffline_GetUnsignedOfflineLogonTicket_Response}
*/
public static final class COffline_GetUnsignedOfflineLogonTicket_Response extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:COffline_GetUnsignedOfflineLogonTicket_Response)
COffline_GetUnsignedOfflineLogonTicket_ResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use COffline_GetUnsignedOfflineLogonTicket_Response.newBuilder() to construct.
private COffline_GetUnsignedOfflineLogonTicket_Response(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private COffline_GetUnsignedOfflineLogonTicket_Response() {
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private COffline_GetUnsignedOfflineLogonTicket_Response(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
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;
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.Builder subBuilder = null;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
subBuilder = ticket_.toBuilder();
}
ticket_ = input.readMessage(SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.PARSER, extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(ticket_);
ticket_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000001;
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 SteammessagesOfflineSteamclient.internal_static_COffline_GetUnsignedOfflineLogonTicket_Response_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetUnsignedOfflineLogonTicket_Response_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response.class, SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response.Builder.class);
}
private int bitField0_;
public static final int TICKET_FIELD_NUMBER = 1;
private SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket ticket_;
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public boolean hasTicket() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket getTicket() {
return ticket_ == null ? SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.getDefaultInstance() : ticket_;
}
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public SteammessagesOfflineSteamclient.COffline_OfflineLogonTicketOrBuilder getTicketOrBuilder() {
return ticket_ == null ? SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.getDefaultInstance() : ticket_;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeMessage(1, getTicket());
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, getTicket());
}
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 SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response)) {
return super.equals(obj);
}
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response other = (SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response) obj;
boolean result = true;
result = result && (hasTicket() == other.hasTicket());
if (hasTicket()) {
result = result && getTicket()
.equals(other.getTicket());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasTicket()) {
hash = (37 * hash) + TICKET_FIELD_NUMBER;
hash = (53 * hash) + getTicket().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response 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 SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response 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 SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
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;
}
/**
* Protobuf type {@code COffline_GetUnsignedOfflineLogonTicket_Response}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:COffline_GetUnsignedOfflineLogonTicket_Response)
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_ResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetUnsignedOfflineLogonTicket_Response_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetUnsignedOfflineLogonTicket_Response_fieldAccessorTable
.ensureFieldAccessorsInitialized(
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response.class, SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response.Builder.class);
}
// Construct using SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getTicketFieldBuilder();
}
}
public Builder clear() {
super.clear();
if (ticketBuilder_ == null) {
ticket_ = null;
} else {
ticketBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return SteammessagesOfflineSteamclient.internal_static_COffline_GetUnsignedOfflineLogonTicket_Response_descriptor;
}
public SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response getDefaultInstanceForType() {
return SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response.getDefaultInstance();
}
public SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response build() {
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response buildPartial() {
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response result = new SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
if (ticketBuilder_ == null) {
result.ticket_ = ticket_;
} else {
result.ticket_ = ticketBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response) {
return mergeFrom((SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response other) {
if (other == SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response.getDefaultInstance()) return this;
if (other.hasTicket()) {
mergeTicket(other.getTicket());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket ticket_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket, SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.Builder, SteammessagesOfflineSteamclient.COffline_OfflineLogonTicketOrBuilder> ticketBuilder_;
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public boolean hasTicket() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket getTicket() {
if (ticketBuilder_ == null) {
return ticket_ == null ? SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.getDefaultInstance() : ticket_;
} else {
return ticketBuilder_.getMessage();
}
}
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public Builder setTicket(SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket value) {
if (ticketBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ticket_ = value;
onChanged();
} else {
ticketBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public Builder setTicket(
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.Builder builderForValue) {
if (ticketBuilder_ == null) {
ticket_ = builderForValue.build();
onChanged();
} else {
ticketBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public Builder mergeTicket(SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket value) {
if (ticketBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001) &&
ticket_ != null &&
ticket_ != SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.getDefaultInstance()) {
ticket_ =
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.newBuilder(ticket_).mergeFrom(value).buildPartial();
} else {
ticket_ = value;
}
onChanged();
} else {
ticketBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public Builder clearTicket() {
if (ticketBuilder_ == null) {
ticket_ = null;
onChanged();
} else {
ticketBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.Builder getTicketBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getTicketFieldBuilder().getBuilder();
}
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
public SteammessagesOfflineSteamclient.COffline_OfflineLogonTicketOrBuilder getTicketOrBuilder() {
if (ticketBuilder_ != null) {
return ticketBuilder_.getMessageOrBuilder();
} else {
return ticket_ == null ?
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.getDefaultInstance() : ticket_;
}
}
/**
* <code>optional .COffline_OfflineLogonTicket ticket = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket, SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.Builder, SteammessagesOfflineSteamclient.COffline_OfflineLogonTicketOrBuilder>
getTicketFieldBuilder() {
if (ticketBuilder_ == null) {
ticketBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket, SteammessagesOfflineSteamclient.COffline_OfflineLogonTicket.Builder, SteammessagesOfflineSteamclient.COffline_OfflineLogonTicketOrBuilder>(
getTicket(),
getParentForChildren(),
isClean());
ticket_ = null;
}
return ticketBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:COffline_GetUnsignedOfflineLogonTicket_Response)
}
// @@protoc_insertion_point(class_scope:COffline_GetUnsignedOfflineLogonTicket_Response)
private static final SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response();
}
public static SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated public static final com.google.protobuf.Parser<COffline_GetUnsignedOfflineLogonTicket_Response>
PARSER = new com.google.protobuf.AbstractParser<COffline_GetUnsignedOfflineLogonTicket_Response>() {
public COffline_GetUnsignedOfflineLogonTicket_Response parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new COffline_GetUnsignedOfflineLogonTicket_Response(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<COffline_GetUnsignedOfflineLogonTicket_Response> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<COffline_GetUnsignedOfflineLogonTicket_Response> getParserForType() {
return PARSER;
}
public SteammessagesOfflineSteamclient.COffline_GetUnsignedOfflineLogonTicket_Response getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_COffline_GetOfflineLogonTicket_Request_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_COffline_GetOfflineLogonTicket_Request_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_COffline_GetOfflineLogonTicket_Response_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_COffline_GetOfflineLogonTicket_Response_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_COffline_GetUnsignedOfflineLogonTicket_Request_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_COffline_GetUnsignedOfflineLogonTicket_Request_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_COffline_OfflineLogonTicket_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_COffline_OfflineLogonTicket_fieldAccessorTable;
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_COffline_GetUnsignedOfflineLogonTicket_Response_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_COffline_GetUnsignedOfflineLogonTicket_Response_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\'steammessages_offline.steamclient.prot" +
"o\032,steammessages_unified_base.steamclien" +
"t.proto\":\n&COffline_GetOfflineLogonTicke" +
"t_Request\022\020\n\010priority\030\001 \001(\r\"W\n\'COffline_" +
"GetOfflineLogonTicket_Response\022\031\n\021serial" +
"ized_ticket\030\001 \001(\014\022\021\n\tsignature\030\002 \001(\014\"0\n." +
"COffline_GetUnsignedOfflineLogonTicket_R" +
"equest\"O\n\033COffline_OfflineLogonTicket\022\021\n" +
"\taccountid\030\001 \001(\r\022\035\n\025rtime32_creation_tim" +
"e\030\002 \001(\007\"_\n/COffline_GetUnsignedOfflineLo",
"gonTicket_Response\022,\n\006ticket\030\001 \001(\0132\034.COf" +
"fline_OfflineLogonTicket2\243\003\n\007Offline\022\265\001\n" +
"\025GetOfflineLogonTicket\022\'.COffline_GetOff" +
"lineLogonTicket_Request\032(.COffline_GetOf" +
"flineLogonTicket_Response\"I\202\265\030EGet a ser" +
"ialized and signed offline logon ticket " +
"for the current user\022\301\001\n\035GetUnsignedOffl" +
"ineLogonTicket\022/.COffline_GetUnsignedOff" +
"lineLogonTicket_Request\0320.COffline_GetUn" +
"signedOfflineLogonTicket_Response\"=\202\265\0309G",
"et an unsigned offline logon ticket for " +
"the current user\032\034\202\265\030\030Offline settings s" +
"erviceB\003\200\001\001"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
SteammessagesUnifiedBaseSteamclient.getDescriptor(),
}, assigner);
internal_static_COffline_GetOfflineLogonTicket_Request_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_COffline_GetOfflineLogonTicket_Request_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_COffline_GetOfflineLogonTicket_Request_descriptor,
new java.lang.String[] { "Priority", });
internal_static_COffline_GetOfflineLogonTicket_Response_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_COffline_GetOfflineLogonTicket_Response_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_COffline_GetOfflineLogonTicket_Response_descriptor,
new java.lang.String[] { "SerializedTicket", "Signature", });
internal_static_COffline_GetUnsignedOfflineLogonTicket_Request_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_COffline_GetUnsignedOfflineLogonTicket_Request_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_COffline_GetUnsignedOfflineLogonTicket_Request_descriptor,
new java.lang.String[] { });
internal_static_COffline_OfflineLogonTicket_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_COffline_OfflineLogonTicket_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_COffline_OfflineLogonTicket_descriptor,
new java.lang.String[] { "Accountid", "Rtime32CreationTime", });
internal_static_COffline_GetUnsignedOfflineLogonTicket_Response_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_COffline_GetUnsignedOfflineLogonTicket_Response_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_COffline_GetUnsignedOfflineLogonTicket_Response_descriptor,
new java.lang.String[] { "Ticket", });
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(SteammessagesUnifiedBaseSteamclient.methodDescription);
registry.add(SteammessagesUnifiedBaseSteamclient.serviceDescription);
com.google.protobuf.Descriptors.FileDescriptor
.internalUpdateFileDescriptor(descriptor, registry);
SteammessagesUnifiedBaseSteamclient.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| apache-2.0 |
navyliu/aura | aura-impl/src/main/java/org/auraframework/impl/css/parser/StyleParser.java | 5228 | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.impl.css.parser;
import java.util.Set;
import org.auraframework.Aura;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.DefDescriptor.DefType;
import org.auraframework.def.Definition;
import org.auraframework.def.FlavoredStyleDef;
import org.auraframework.def.ResourceDef;
import org.auraframework.def.StyleDef;
import org.auraframework.impl.clientlibrary.handler.ResourceDefHandler;
import org.auraframework.impl.css.flavor.FlavoredStyleDefImpl;
import org.auraframework.impl.css.parser.CssPreprocessor.ParserConfiguration;
import org.auraframework.impl.css.parser.CssPreprocessor.ParserResult;
import org.auraframework.impl.css.style.StyleDefImpl;
import org.auraframework.impl.css.util.Styles;
import org.auraframework.system.Client;
import org.auraframework.system.Parser;
import org.auraframework.system.Source;
import org.auraframework.throwable.quickfix.QuickFixException;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
/**
*/
public final class StyleParser implements Parser {
private static final StyleParser INSTANCE = new StyleParser(true);
private static final StyleParser NON_VALIDATING_INSTANCE = new StyleParser(false);
public static final Set<String> ALLOWED_CONDITIONS;
private final boolean doValidation;
// build list of conditional permutations and allowed conditionals
static {
ImmutableSet.Builder<String> acBuilder = ImmutableSet.builder();
for (Client.Type type : Client.Type.values()) {
acBuilder.add(type.toString());
}
ALLOWED_CONDITIONS = acBuilder.build();
}
public static StyleParser getInstance() {
return Aura.getConfigAdapter().validateCss() ? INSTANCE : NON_VALIDATING_INSTANCE;
}
public static StyleParser getNonValidatingInstance() {
return NON_VALIDATING_INSTANCE;
}
protected StyleParser(boolean doValidation) {
this.doValidation = doValidation;
}
public boolean shouldValidate(String name) {
return name.toLowerCase().endsWith("template") ? false : doValidation;
}
@SuppressWarnings("unchecked")
@Override
public <D extends Definition> D parse(DefDescriptor<D> descriptor, Source<?> source) throws QuickFixException {
ParserConfiguration parserConfig = CssPreprocessor
.initial()
.source(source.getContents())
.resourceName(source.getSystemId())
.allowedConditions(Iterables.concat(ALLOWED_CONDITIONS, Aura.getStyleAdapter().getExtraAllowedConditions()));
if (descriptor.getDefType() == DefType.STYLE) {
DefDescriptor<StyleDef> styleDescriptor = (DefDescriptor<StyleDef>) descriptor;
String className = Styles.buildClassName(styleDescriptor);
StyleDefImpl.Builder builder = new StyleDefImpl.Builder();
builder.setDescriptor(styleDescriptor);
builder.setLocation(source.getSystemId(), source.getLastModified());
builder.setClassName(className);
builder.setOwnHash(source.getHash());
ParserResult result = parserConfig
.componentClass(className, shouldValidate(descriptor.getName()))
.tokens(styleDescriptor)
.parse();
builder.setContent(result.content());
builder.setTokenExpressions(result.expressions());
return (D) builder.build();
} else if (descriptor.getDefType() == DefType.FLAVORED_STYLE) {
DefDescriptor<FlavoredStyleDef> flavorDescriptor = (DefDescriptor<FlavoredStyleDef>) descriptor;
FlavoredStyleDefImpl.Builder builder = new FlavoredStyleDefImpl.Builder();
builder.setDescriptor(flavorDescriptor);
builder.setLocation(source.getSystemId(), source.getLastModified());
builder.setOwnHash(source.getHash());
ParserResult result = parserConfig
.tokens(flavorDescriptor)
.flavors(flavorDescriptor)
.parse();
builder.setContent(result.content());
builder.setTokenExpressions(result.expressions());
builder.setFlavorAnnotations(result.flavorAnnotations());
return (D) builder.build();
} else if (descriptor.getDefType() == DefType.RESOURCE) {
return (D) new ResourceDefHandler<>((DefDescriptor<ResourceDef>) descriptor,
(Source<ResourceDef>) source).createDefinition();
}
return null;
}
}
| apache-2.0 |
dgrove727/autopsy | Experimental/src/org/sleuthkit/autopsy/experimental/configuration/SharedConfiguration.java | 60350 | /*
* Autopsy Forensic Browser
*
* Copyright 2015 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> 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.sleuthkit.autopsy.experimental.configuration;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.zip.CRC32;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.prefs.BackingStoreException;
import org.apache.commons.io.FileUtils;
import org.sleuthkit.autopsy.core.UserPreferences;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.PlatformUtil;
import org.sleuthkit.autopsy.coreutils.FileUtil;
import org.sleuthkit.autopsy.ingest.IngestJobSettings;
import org.sleuthkit.autopsy.keywordsearch.KeywordListsManager;
import org.sleuthkit.autopsy.modules.hashdatabase.HashDbManager;
import org.sleuthkit.datamodel.TskCoreException;
import org.sleuthkit.autopsy.core.ServicesMonitor;
import org.sleuthkit.autopsy.modules.hashdatabase.HashDbManager.HashDb;
import org.sleuthkit.autopsy.experimental.configuration.AutoIngestSettingsPanel.UpdateConfigSwingWorker;
import org.sleuthkit.autopsy.coordinationservice.CoordinationService;
import org.sleuthkit.autopsy.coordinationservice.CoordinationService.CategoryNode;
import org.sleuthkit.autopsy.coordinationservice.CoordinationService.Lock;
import org.sleuthkit.autopsy.coordinationservice.CoordinationService.CoordinationServiceException;
/*
* A utility class for loading and saving shared configuration data
*/
public class SharedConfiguration {
// Files
private static final String AUTO_MODE_CONTEXT_FILE = "AutoModeContext.properties"; //NON-NLS
private static final String USER_DEFINED_TYPE_DEFINITIONS_FILE = "UserFileTypeDefinitions.settings"; //NON-NLS
private static final String USER_DEFINED_TYPE_DEFINITIONS_FILE_LEGACY = "UserFileTypeDefinitions.xml"; //NON-NLS
private static final String INTERESTING_FILES_SET_DEFS_FILE = "InterestingFileSets.settings"; //NON-NLS
private static final String INTERESTING_FILES_SET_DEFS_FILE_LEGACY = "InterestingFilesSetDefs.xml"; //NON-NLS
private static final String KEYWORD_SEARCH_SETTINGS = "keywords.settings"; //NON-NLS
private static final String KEYWORD_SEARCH_SETTINGS_LEGACY = "keywords.xml"; //NON-NLS
private static final String KEYWORD_SEARCH_GENERAL_LEGACY = "KeywordSearch.properties"; //NON-NLS
private static final String KEYWORD_SEARCH_NSRL_LEGACY = "KeywordSearch_NSRL.properties"; //NON-NLS
private static final String KEYWORD_SEARCH_OPTIONS_LEGACY = "KeywordSearch_Options.properties"; //NON-NLS
private static final String KEYWORD_SEARCH_SCRIPTS_LEGACY = "KeywordSearch_Scripts.properties"; //NON-NLS
private static final String FILE_EXT_MISMATCH_SETTINGS = "mismatch_config.settings"; //NON-NLS
private static final String FILE_EXT_MISMATCH_SETTINGS_LEGACY = "mismatch_config.xml"; //NON-NLS
private static final String ANDROID_TRIAGE = "AndroidTriage_Options.properties"; //NON-NLS
private static final String GENERAL_PROPERTIES = "core.properties"; //NON-NLS
private static final String AUTO_INGEST_PROPERTIES = "AutoIngest.properties"; //NON-NLS
private static final String HASHDB_CONFIG_FILE_NAME = "hashLookup.settings"; //NON-NLS
private static final String HASHDB_CONFIG_FILE_NAME_LEGACY = "hashsets.xml"; //NON-NLS
public static final String FILE_EXPORTER_SETTINGS_FILE = "fileexporter.settings"; //NON-NLS
private static final String CENTRAL_REPOSITORY_PROPERTIES_FILE = "CentralRepository.properties"; //NON-NLS
private static final String SHARED_CONFIG_VERSIONS = "SharedConfigVersions.txt"; //NON-NLS
// Folders
private static final String AUTO_MODE_FOLDER = "AutoModeContext"; //NON-NLS
private static final String REMOTE_HASH_FOLDER = "hashDb"; //NON-NLS
private static final String PREFERENCES_FOLDER = "Preferences"; //NON-NLS
public static final String FILE_EXPORTER_FOLDER = "Automated File Exporter"; //NON-NLS
private static final String UPLOAD_IN_PROGRESS_FILE = "uploadInProgress"; // NON-NLS
private static final String moduleDirPath = PlatformUtil.getUserConfigDirectory();
private static final Logger logger = Logger.getLogger(SharedConfiguration.class.getName());
private final UpdateConfigSwingWorker swingWorker;
private UserPreferences.SelectedMode mode;
private String sharedConfigFolder;
private int fileIngestThreads;
private boolean sharedConfigMaster;
private boolean showToolsWarning;
private boolean displayLocalTime;
private boolean hideKnownFilesInDataSource;
private boolean hideKnownFilesInViews;
private boolean hideSlackFilesInDataSource;
private boolean hideSlackFilesInViews;
private boolean keepPreferredViewer;
/**
* Exception type thrown by shared configuration.
*/
public final static class SharedConfigurationException extends Exception {
private static final long serialVersionUID = 1L;
private SharedConfigurationException(String message) {
super(message);
}
private SharedConfigurationException(String message, Throwable cause) {
super(message, cause);
}
}
// Using this so we can indicate whether a read/write failed because the lock file is present,
// which we need to know to display the correct message in the auto-ingest dashboard about why
// processing has been paused.
public enum SharedConfigResult {
SUCCESS, LOCKED
}
public SharedConfiguration() {
swingWorker = null;
}
/**
* Construct with a SwingWorker reference to allow status update messages to
* go to the GUI
*
* @param worker
*/
public SharedConfiguration(UpdateConfigSwingWorker worker) {
this.swingWorker = worker;
}
private void publishTask(String task) {
if (swingWorker != null) {
swingWorker.publishStatus(task);
}
}
/**
* Upload the current multi-user ingest settings to a shared folder.
*
* @throws SharedConfigurationException
* @throws CoordinationServiceException
* @throws InterruptedException
*/
public SharedConfigResult uploadConfiguration() throws SharedConfigurationException, CoordinationServiceException, InterruptedException {
publishTask("Starting shared configuration upload");
File remoteFolder = getSharedFolder();
try (Lock writeLock = CoordinationService.getInstance().tryGetExclusiveLock(CategoryNode.CONFIG, remoteFolder.getAbsolutePath(), 30, TimeUnit.MINUTES)) {
if (writeLock == null) {
logger.log(Level.INFO, String.format("Failed to lock %s - another node is currently uploading or downloading configuration", remoteFolder.getAbsolutePath()));
return SharedConfigResult.LOCKED;
}
// Make sure the local settings have been initialized
if (!isConfigFolderPopulated(new File(moduleDirPath), false)) {
logger.log(Level.INFO, "Local configuration has not been initialized.");
throw new SharedConfigurationException("Local configuration has not been initialized. Please verify/update and save the settings using the Ingest Module Settings button and then retry the upload.");
}
// Write a file to indicate that uploading is in progress. If we crash or
// have an error, this file will remain in the shared folder.
File uploadInProgress = new File(remoteFolder, UPLOAD_IN_PROGRESS_FILE);
if (!uploadInProgress.exists()) {
try {
Files.createFile(uploadInProgress.toPath());
} catch (IOException ex) {
throw new SharedConfigurationException(String.format("Failed to create %s", uploadInProgress.toPath()), ex);
}
}
// Make sure all recent changes are saved to the preference file
// Current testing suggests that we do not need to do this for the ingest settings
// because there is a longer delay between setting them and copying the files.
try {
// Make sure all recent changes are saved to the preference file
// Current testing suggests that we do not need to do this for the ingest settings
// because there is a longer delay between setting them and copying the files.
UserPreferences.saveToStorage();
} catch (BackingStoreException ex) {
throw new SharedConfigurationException("Failed to save shared configuration settings", ex);
}
uploadAutoModeContextSettings(remoteFolder);
uploadEnabledModulesSettings(remoteFolder);
uploadFileTypeSettings(remoteFolder);
uploadInterestingFilesSettings(remoteFolder);
uploadKeywordSearchSettings(remoteFolder);
uploadFileExtMismatchSettings(remoteFolder);
uploadAndroidTriageSettings(remoteFolder);
uploadMultiUserAndGeneralSettings(remoteFolder);
uploadHashDbSettings(remoteFolder);
uploadFileExporterSettings(remoteFolder);
uploadCentralRepositorySettings(remoteFolder);
try {
Files.deleteIfExists(uploadInProgress.toPath());
} catch (IOException ex) {
throw new SharedConfigurationException(String.format("Failed to delete %s", uploadInProgress.toPath()), ex);
}
}
return SharedConfigResult.SUCCESS;
}
/**
* Download the multi-user settings from a shared folder.
*
* @throws SharedConfigurationException
* @throws InterruptedException
*/
public synchronized SharedConfigResult downloadConfiguration() throws SharedConfigurationException, InterruptedException {
publishTask("Starting shared configuration download");
// Save local settings that should not get overwritten
saveNonSharedSettings();
File remoteFolder = getSharedFolder();
try (Lock readLock = CoordinationService.getInstance().tryGetSharedLock(CategoryNode.CONFIG, remoteFolder.getAbsolutePath(), 30, TimeUnit.MINUTES)) {
if (readLock == null) {
return SharedConfigResult.LOCKED;
}
// Make sure the shared configuration was last uploaded successfully
File uploadInProgress = new File(remoteFolder, UPLOAD_IN_PROGRESS_FILE);
if (uploadInProgress.exists()) {
logger.log(Level.INFO, String.format("Shared configuration folder %s is corrupt - re-upload configuration", remoteFolder.getAbsolutePath()));
throw new SharedConfigurationException(String.format("Shared configuration folder %s is corrupt - re-upload configuration", remoteFolder.getAbsolutePath()));
}
// Make sure the shared configuration folder isn't empty
if (!isConfigFolderPopulated(remoteFolder, true)) {
logger.log(Level.INFO, String.format("Shared configuration folder %s is missing files / may be empty. Aborting download.", remoteFolder.getAbsolutePath()));
throw new SharedConfigurationException(String.format("Shared configuration folder %s is missing files / may be empty. Aborting download.", remoteFolder.getAbsolutePath()));
}
try {
/* Make sure all recent changes are saved to the preference file.
This also releases open file handles to the preference files. If this
is not done, then occasionally downloading of shared configuration
fails silently, likely because Java/OS is still holding the file handle.
The problem manifests itself by some of the old/original configuration files
sticking around after shared configuration has seemingly been successfully
updated. */
UserPreferences.saveToStorage();
} catch (BackingStoreException ex) {
throw new SharedConfigurationException("Failed to save shared configuration settings", ex);
}
downloadAutoModeContextSettings(remoteFolder);
downloadEnabledModuleSettings(remoteFolder);
downloadFileTypeSettings(remoteFolder);
downloadInterestingFilesSettings(remoteFolder);
downloadKeywordSearchSettings(remoteFolder);
downloadFileExtMismatchSettings(remoteFolder);
downloadAndroidTriageSettings(remoteFolder);
downloadFileExporterSettings(remoteFolder);
downloadCentralRepositorySettings(remoteFolder);
// Download general settings, then restore the current
// values for the unshared fields
downloadMultiUserAndGeneralSettings(remoteFolder);
try {
UserPreferences.reloadFromStorage();
} catch (BackingStoreException ex) {
throw new SharedConfigurationException("Failed to read shared configuration settings", ex);
}
restoreNonSharedSettings();
downloadHashDbSettings(remoteFolder);
} catch (CoordinationServiceException ex) {
throw new SharedConfigurationException(String.format("Coordination service error acquiring exclusive lock on shared configuration source %s", remoteFolder.getAbsolutePath()), ex);
}
// Check Solr service
if (!isServiceUp(ServicesMonitor.Service.REMOTE_KEYWORD_SEARCH.toString())) {
throw new SharedConfigurationException("Keyword search service is down");
}
// Check PostgreSQL service
if (!isServiceUp(ServicesMonitor.Service.REMOTE_CASE_DATABASE.toString())) {
throw new SharedConfigurationException("Case database server is down");
}
// Check ActiveMQ service
if (!isServiceUp(ServicesMonitor.Service.MESSAGING.toString())) {
throw new SharedConfigurationException("Messaging service is down");
}
// Check input folder permissions
String inputFolder = AutoIngestUserPreferences.getAutoModeImageFolder();
if (!FileUtil.hasReadWriteAccess(Paths.get(inputFolder))) {
throw new SharedConfigurationException("Cannot read input folder " + inputFolder + ". Check that the folder exists and that you have permissions to access it.");
}
// Check output folder permissions
String outputFolder = AutoIngestUserPreferences.getAutoModeResultsFolder();
if (!FileUtil.hasReadWriteAccess(Paths.get(outputFolder))) {
throw new SharedConfigurationException("Cannot read output folder " + outputFolder + ". Check that the folder exists and that you have permissions to access it.");
}
return SharedConfigResult.SUCCESS;
}
/**
* Tests service of interest to verify that it is running.
*
* @param serviceName Name of the service.
*
* @return True if the service is running, false otherwise.
*/
private boolean isServiceUp(String serviceName) {
try {
return (ServicesMonitor.getInstance().getServiceStatus(serviceName).equals(ServicesMonitor.ServiceStatus.UP.toString()));
} catch (ServicesMonitor.ServicesMonitorException ex) {
logger.log(Level.SEVERE, String.format("Problem checking service status for %s", serviceName), ex);
return false;
}
}
/**
* Save any settings that should not be overwritten by the shared
* configuration.
*/
private void saveNonSharedSettings() {
sharedConfigMaster = AutoIngestUserPreferences.getSharedConfigMaster();
sharedConfigFolder = AutoIngestUserPreferences.getSharedConfigFolder();
showToolsWarning = AutoIngestUserPreferences.getShowToolsWarning();
displayLocalTime = UserPreferences.displayTimesInLocalTime();
hideKnownFilesInDataSource = UserPreferences.hideKnownFilesInDataSourcesTree();
hideKnownFilesInViews = UserPreferences.hideKnownFilesInViewsTree();
keepPreferredViewer = UserPreferences.keepPreferredContentViewer();
fileIngestThreads = UserPreferences.numberOfFileIngestThreads();
hideSlackFilesInDataSource = UserPreferences.hideSlackFilesInDataSourcesTree();
hideSlackFilesInViews = UserPreferences.hideSlackFilesInViewsTree();
}
/**
* Restore the settings that may have been overwritten.
*/
private void restoreNonSharedSettings() {
AutoIngestUserPreferences.setSharedConfigFolder(sharedConfigFolder);
AutoIngestUserPreferences.setSharedConfigMaster(sharedConfigMaster);
AutoIngestUserPreferences.setShowToolsWarning(showToolsWarning);
UserPreferences.setDisplayTimesInLocalTime(displayLocalTime);
UserPreferences.setHideKnownFilesInDataSourcesTree(hideKnownFilesInDataSource);
UserPreferences.setHideKnownFilesInViewsTree(hideKnownFilesInViews);
UserPreferences.setKeepPreferredContentViewer(keepPreferredViewer);
UserPreferences.setNumberOfFileIngestThreads(fileIngestThreads);
UserPreferences.setHideSlackFilesInDataSourcesTree(hideSlackFilesInDataSource);
UserPreferences.setHideSlackFilesInViewsTree(hideSlackFilesInViews);
}
/**
* Get the base folder being used to store the shared config settings.
*
* @return The shared configuration folder
*
* @throws SharedConfigurationException
*/
private static File getSharedFolder() throws SharedConfigurationException {
// Check that the shared folder is set and exists
String remoteConfigFolderPath = AutoIngestUserPreferences.getSharedConfigFolder();
if (remoteConfigFolderPath.isEmpty()) {
logger.log(Level.SEVERE, "Shared configuration folder is not set.");
throw new SharedConfigurationException("Shared configuration folder is not set.");
}
File remoteFolder = new File(remoteConfigFolderPath);
if (!remoteFolder.exists()) {
logger.log(Level.SEVERE, "Shared configuration folder {0} does not exist", remoteConfigFolderPath);
throw new SharedConfigurationException("Shared configuration folder " + remoteConfigFolderPath + " does not exist");
}
return remoteFolder;
}
/**
* Do a basic check to determine whether settings have been stored to the
* given folder. There may still be missing files/errors, but this will stop
* empty/corrupt settings from overwriting local settings or being uploaded.
*
* Currently we check for: - A non-empty AutoModeContext folder - An
* AutoModeContext properties file
*
* @param folder Folder to check the contents of
* @param isSharedFolder True if the folder being tested is the shared
* folder, false if its the local folder
*
* @return true if the folder appears to have been initialized, false
* otherwise
*/
private static boolean isConfigFolderPopulated(File folder, boolean isSharedFolder) {
if (!folder.exists()) {
return false;
}
// Check that the context directory exists and is not empty
File contextDir;
if (isSharedFolder) {
contextDir = new File(folder, AUTO_MODE_FOLDER);
} else {
IngestJobSettings ingestJobSettings = new IngestJobSettings(AutoIngestUserPreferences.getAutoModeIngestModuleContextString());
contextDir = ingestJobSettings.getSavedModuleSettingsFolder().toFile();
}
if ((!contextDir.exists()) || (!contextDir.isDirectory())) {
return false;
}
if (contextDir.listFiles().length == 0) {
return false;
}
// Check that the automode context properties file exists
File contextProperties = new File(folder, AUTO_MODE_CONTEXT_FILE);
return contextProperties.exists();
}
/**
* Copy a local settings file to the remote folder.
*
* @param fileName Name of the file to copy
* @param localFolder Local settings folder
* @param remoteFolder Shared settings folder
* @param missingFileOk True if it's not an error if the source file is not
* found
*
* @throws SharedConfigurationException
*/
private static void copyToRemoteFolder(String fileName, String localFolder, File remoteFolder, boolean missingFileOk) throws SharedConfigurationException {
logger.log(Level.INFO, "Uploading {0} to {1}", new Object[]{fileName, remoteFolder.getAbsolutePath()});
File localFile = new File(localFolder, fileName);
if (!localFile.exists()) {
Path deleteRemote = Paths.get(remoteFolder.toString(), fileName);
try {
if (deleteRemote.toFile().exists()) {
deleteRemote.toFile().delete();
}
} catch (SecurityException ex) {
logger.log(Level.SEVERE, "Shared configuration {0} does not exist on local node, but unable to remove remote copy", fileName);
throw new SharedConfigurationException("Shared configuration file " + deleteRemote.toString() + " could not be deleted.");
}
if (!missingFileOk) {
logger.log(Level.SEVERE, "Local configuration file {0} does not exist", localFile.getAbsolutePath());
throw new SharedConfigurationException("Local configuration file " + localFile.getAbsolutePath() + " does not exist");
} else {
logger.log(Level.INFO, "Local configuration file {0} does not exist", localFile.getAbsolutePath());
return;
}
}
try {
FileUtils.copyFileToDirectory(localFile, remoteFolder);
} catch (IOException ex) {
throw new SharedConfigurationException(String.format("Failed to copy %s to %s", localFile.getAbsolutePath(), remoteFolder.getAbsolutePath()), ex);
}
}
/**
* Copy a shared settings file to the local settings folder.
*
* @param fileName Name of the file to copy
* @param localFolder Local settings folder
* @param remoteFolder Shared settings folder
* @param missingFileOk True if it's not an error if the source file is not
* found
*
* @throws SharedConfigurationException
*/
private static void copyToLocalFolder(String fileName, String localFolder, File remoteFolder, boolean missingFileOk) throws SharedConfigurationException {
logger.log(Level.INFO, "Downloading {0} from {1}", new Object[]{fileName, remoteFolder.getAbsolutePath()});
File remoteFile = new File(remoteFolder, fileName);
if (!remoteFile.exists()) {
Path deleteLocal = Paths.get(localFolder, fileName);
try {
if (deleteLocal.toFile().exists()) {
deleteLocal.toFile().delete();
}
} catch (SecurityException ex) {
logger.log(Level.SEVERE, "Shared configuration {0} does not exist on remote node, but unable to remove local copy", fileName);
throw new SharedConfigurationException("Shared configuration file " + deleteLocal.toString() + " could not be deleted.");
}
if (!missingFileOk) {
logger.log(Level.SEVERE, "Shared configuration file {0} does not exist", remoteFile.getAbsolutePath());
throw new SharedConfigurationException("Shared configuration file " + remoteFile.getAbsolutePath() + " does not exist");
} else {
logger.log(Level.INFO, "Shared configuration file {0} does not exist", remoteFile.getAbsolutePath());
return;
}
}
File localSettingsFolder = new File(localFolder);
try {
FileUtils.copyFileToDirectory(remoteFile, localSettingsFolder);
} catch (IOException ex) {
throw new SharedConfigurationException(String.format("Failed to copy %s to %s", remoteFile.getAbsolutePath(), localSettingsFolder.getAbsolutePath()), ex);
}
}
/**
* Upload the basic set of auto-ingest settings to the shared folder.
*
* @param remoteFolder Shared settings folder
*
* @throws Exception
*/
private void uploadAutoModeContextSettings(File remoteFolder) throws SharedConfigurationException {
logger.log(Level.INFO, "Uploading shared configuration to {0}", remoteFolder.getAbsolutePath());
publishTask("Uploading AutoModeContext configuration files");
// Make a subfolder
File remoteAutoConfFolder = new File(remoteFolder, AUTO_MODE_FOLDER);
try {
if (remoteAutoConfFolder.exists()) {
FileUtils.deleteDirectory(remoteAutoConfFolder);
}
Files.createDirectories(remoteAutoConfFolder.toPath());
} catch (IOException | SecurityException ex) {
logger.log(Level.SEVERE, "Failed to create clean shared configuration subfolder " + remoteAutoConfFolder.getAbsolutePath(), ex); //NON-NLS
throw new SharedConfigurationException("Failed to create clean shared configuration subfolder " + remoteAutoConfFolder.getAbsolutePath());
}
IngestJobSettings ingestJobSettings = new IngestJobSettings(AutoIngestUserPreferences.getAutoModeIngestModuleContextString());
File localFolder = ingestJobSettings.getSavedModuleSettingsFolder().toFile();
if (!localFolder.exists()) {
logger.log(Level.SEVERE, "Local configuration folder {0} does not exist", localFolder.getAbsolutePath());
throw new SharedConfigurationException("Local configuration folder " + localFolder.getAbsolutePath() + " does not exist");
}
try {
FileUtils.copyDirectory(localFolder, remoteAutoConfFolder);
} catch (IOException ex) {
throw new SharedConfigurationException(String.format("Failed to copy %s to %s", localFolder.getAbsolutePath(), remoteAutoConfFolder.getAbsolutePath()), ex);
}
}
/**
* Download the basic set of auto-ingest settings from the shared folder
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadAutoModeContextSettings(File remoteFolder) throws SharedConfigurationException {
logger.log(Level.INFO, "Downloading shared configuration from {0}", remoteFolder.getAbsolutePath());
publishTask("Downloading AutoModeContext configuration files");
// Check that the remote subfolder exists
File remoteAutoConfFolder = new File(remoteFolder, AUTO_MODE_FOLDER);
if (!remoteAutoConfFolder.exists()) {
logger.log(Level.SEVERE, "Shared configuration folder {0} does not exist", remoteAutoConfFolder.getAbsolutePath());
throw new SharedConfigurationException("Shared configuration folder " + remoteAutoConfFolder.getAbsolutePath() + " does not exist");
}
// Get/create the local subfolder
IngestJobSettings ingestJobSettings = new IngestJobSettings(AutoIngestUserPreferences.getAutoModeIngestModuleContextString());
File localFolder = ingestJobSettings.getSavedModuleSettingsFolder().toFile();
try {
if (localFolder.exists()) {
FileUtils.deleteDirectory(localFolder);
}
Files.createDirectories(localFolder.toPath());
} catch (IOException | SecurityException ex) {
logger.log(Level.SEVERE, "Failed to create clean local configuration folder " + localFolder.getAbsolutePath(), ex); //NON-NLS
throw new SharedConfigurationException("Failed to create clean local configuration folder " + localFolder.getAbsolutePath());
}
try {
FileUtils.copyDirectory(remoteAutoConfFolder, localFolder);
} catch (IOException ex) {
throw new SharedConfigurationException(String.format("Failed to copy %s to %s", remoteFolder.getAbsolutePath(), localFolder.getAbsolutePath()), ex);
}
}
/**
* Upload settings file containing enabled ingest modules.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void uploadEnabledModulesSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Uploading enabled module configuration");
copyToRemoteFolder(AUTO_MODE_CONTEXT_FILE, moduleDirPath, remoteFolder, false);
}
/**
* Download settings file containing enabled ingest modules.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadEnabledModuleSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Downloading enabled module configuration");
copyToLocalFolder(AUTO_MODE_CONTEXT_FILE, moduleDirPath, remoteFolder, false);
}
/**
* Upload settings file containing file type settings.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void uploadFileTypeSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Uploading FileType module configuration");
copyToRemoteFolder(USER_DEFINED_TYPE_DEFINITIONS_FILE, moduleDirPath, remoteFolder, true);
copyToRemoteFolder(USER_DEFINED_TYPE_DEFINITIONS_FILE_LEGACY, moduleDirPath, remoteFolder, true);
}
/**
* Download settings file containing file type settings.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadFileTypeSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Downloading FileType module configuration");
copyToLocalFolder(USER_DEFINED_TYPE_DEFINITIONS_FILE, moduleDirPath, remoteFolder, true);
copyToLocalFolder(USER_DEFINED_TYPE_DEFINITIONS_FILE_LEGACY, moduleDirPath, remoteFolder, true);
}
/**
* Upload settings for the interesting files module.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void uploadInterestingFilesSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Uploading InterestingFiles module configuration");
copyToRemoteFolder(INTERESTING_FILES_SET_DEFS_FILE_LEGACY, moduleDirPath, remoteFolder, true);
copyToRemoteFolder(INTERESTING_FILES_SET_DEFS_FILE, moduleDirPath, remoteFolder, true);
}
/**
* Download settings for the interesting files module.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadInterestingFilesSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Downloading InterestingFiles module configuration");
copyToLocalFolder(INTERESTING_FILES_SET_DEFS_FILE_LEGACY, moduleDirPath, remoteFolder, true);
copyToLocalFolder(INTERESTING_FILES_SET_DEFS_FILE, moduleDirPath, remoteFolder, true);
}
/**
* Upload settings for the keyword search module.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void uploadKeywordSearchSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Uploading KeywordSearch module configuration");
copyToRemoteFolder(KEYWORD_SEARCH_SETTINGS, moduleDirPath, remoteFolder, true);
copyToRemoteFolder(KEYWORD_SEARCH_SETTINGS_LEGACY, moduleDirPath, remoteFolder, true);
copyToRemoteFolder(KEYWORD_SEARCH_GENERAL_LEGACY, moduleDirPath, remoteFolder, true);
copyToRemoteFolder(KEYWORD_SEARCH_NSRL_LEGACY, moduleDirPath, remoteFolder, true);
copyToRemoteFolder(KEYWORD_SEARCH_OPTIONS_LEGACY, moduleDirPath, remoteFolder, true);
copyToRemoteFolder(KEYWORD_SEARCH_SCRIPTS_LEGACY, moduleDirPath, remoteFolder, true);
}
/**
* Download settings for the keyword search module.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadKeywordSearchSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Downloading KeywordSearch module configuration");
copyToLocalFolder(KEYWORD_SEARCH_SETTINGS, moduleDirPath, remoteFolder, true);
copyToLocalFolder(KEYWORD_SEARCH_SETTINGS_LEGACY, moduleDirPath, remoteFolder, true);
copyToLocalFolder(KEYWORD_SEARCH_GENERAL_LEGACY, moduleDirPath, remoteFolder, true);
copyToLocalFolder(KEYWORD_SEARCH_NSRL_LEGACY, moduleDirPath, remoteFolder, true);
copyToLocalFolder(KEYWORD_SEARCH_OPTIONS_LEGACY, moduleDirPath, remoteFolder, true);
copyToLocalFolder(KEYWORD_SEARCH_SCRIPTS_LEGACY, moduleDirPath, remoteFolder, true);
KeywordListsManager.reloadKeywordLists();
}
/**
* Upload settings for the file extension mismatch module.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void uploadFileExtMismatchSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Uploading File Extension Mismatch module configuration");
copyToRemoteFolder(FILE_EXT_MISMATCH_SETTINGS, moduleDirPath, remoteFolder, true);
copyToRemoteFolder(FILE_EXT_MISMATCH_SETTINGS_LEGACY, moduleDirPath, remoteFolder, false);
}
/**
* Download settings for the file extension mismatch module.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadFileExtMismatchSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Downloading File Extension Mismatch module configuration");
copyToLocalFolder(FILE_EXT_MISMATCH_SETTINGS, moduleDirPath, remoteFolder, true);
copyToLocalFolder(FILE_EXT_MISMATCH_SETTINGS_LEGACY, moduleDirPath, remoteFolder, false);
}
/**
* Upload settings for the android triage module.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void uploadAndroidTriageSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Uploading Android Triage module configuration");
copyToRemoteFolder(ANDROID_TRIAGE, moduleDirPath, remoteFolder, true);
}
/**
* Download settings for the android triage module.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadAndroidTriageSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Downloading Android Triage module configuration");
copyToLocalFolder(ANDROID_TRIAGE, moduleDirPath, remoteFolder, true);
}
/**
* Upload File Exporter settings.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void uploadFileExporterSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Uploading File Exporter configuration");
File fileExporterFolder = new File(moduleDirPath, FILE_EXPORTER_FOLDER);
copyToRemoteFolder(FILE_EXPORTER_SETTINGS_FILE, fileExporterFolder.getAbsolutePath(), remoteFolder, true);
}
/**
* Download File Exporter settings.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadFileExporterSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Downloading File Exporter configuration");
File fileExporterFolder = new File(moduleDirPath, FILE_EXPORTER_FOLDER);
copyToLocalFolder(FILE_EXPORTER_SETTINGS_FILE, fileExporterFolder.getAbsolutePath(), remoteFolder, true);
}
/**
* Upload central repository settings.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void uploadCentralRepositorySettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Uploading central repository configuration");
copyToRemoteFolder(CENTRAL_REPOSITORY_PROPERTIES_FILE, moduleDirPath, remoteFolder, true);
}
/**
* Download central repository settings.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadCentralRepositorySettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Downloading central repository configuration");
copyToLocalFolder(CENTRAL_REPOSITORY_PROPERTIES_FILE, moduleDirPath, remoteFolder, true);
}
/**
* Upload multi-user settings and other general Autopsy settings
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void uploadMultiUserAndGeneralSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Uploading multi user configuration");
File generalSettingsFolder = Paths.get(moduleDirPath, PREFERENCES_FOLDER, "org", "sleuthkit", "autopsy").toFile();
copyToRemoteFolder(GENERAL_PROPERTIES, generalSettingsFolder.getAbsolutePath(), remoteFolder, false);
copyToRemoteFolder(AUTO_INGEST_PROPERTIES, moduleDirPath, remoteFolder, false);
}
/**
* Download multi-user settings and other general Autopsy settings
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadMultiUserAndGeneralSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Downloading multi user configuration");
File generalSettingsFolder = Paths.get(moduleDirPath, PREFERENCES_FOLDER, "org", "sleuthkit", "autopsy").toFile();
copyToLocalFolder(GENERAL_PROPERTIES, generalSettingsFolder.getAbsolutePath(), remoteFolder, false);
copyToLocalFolder(AUTO_INGEST_PROPERTIES, moduleDirPath, remoteFolder, false);
}
/**
* Upload settings and hash databases to the shared folder. The general
* algorithm is: - Copy the general settings in hashsets.xml - For each hash
* database listed in hashsets.xml: - Calculate the CRC of the database - If
* the CRC does not match the one listed for that database in the shared
* folder, (or if no entry exists), copy the database - Store the CRCs for
* each database in the shared folder and locally
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void uploadHashDbSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Uploading HashDb module configuration");
// Keep track of everything being uploaded
File localVersionFile = new File(moduleDirPath, SHARED_CONFIG_VERSIONS);
File sharedVersionFile = new File(remoteFolder, SHARED_CONFIG_VERSIONS);
Map<String, String> newVersions = new HashMap<>();
Map<String, String> sharedVersions = readVersionsFromFile(sharedVersionFile);
// Copy the settings file
copyToRemoteFolder(HASHDB_CONFIG_FILE_NAME, moduleDirPath, remoteFolder, true);
copyToRemoteFolder(HASHDB_CONFIG_FILE_NAME_LEGACY, moduleDirPath, remoteFolder, true);
// Get the list of databases from the file
List<String> databases = getHashFileNamesFromSettingsFile();
for (String fullPathToDbFile : databases) {
// Compare the CRC of the local copy with what is stored in the shared folder
publishTask("Deciding whether to upload " + fullPathToDbFile);
String crc = calculateCRC(fullPathToDbFile);
// Determine full path to db file in remote folder
String sharedName = convertLocalDbPathToShared(fullPathToDbFile);
File sharedDbBaseFolder = new File(remoteFolder, REMOTE_HASH_FOLDER);
File sharedDb = new File(sharedDbBaseFolder, sharedName);
if (!(sharedVersions.containsKey(fullPathToDbFile)
&& sharedVersions.get(fullPathToDbFile).equals(crc)
&& sharedDb.exists())) {
publishTask("Uploading " + fullPathToDbFile);
File sharedDbPath = sharedDb.getParentFile();
if (!sharedDbPath.exists()) {
if (!sharedDbPath.mkdirs()) {
throw new SharedConfigurationException("Error creating shared hash database directory " + sharedDbPath.getAbsolutePath());
}
}
File dbFile = new File(fullPathToDbFile);
// copy hash db file to the remote folder
copyFile(sharedDbPath, dbFile);
// check whether the hash db has an index file (.idx) that should also be copied.
// NOTE: only text hash databases (.txt, .hash, .Hash) can have index file.
// it is possible that the hash db file itself is the index file
String fullPathToIndexFile = "";
if (fullPathToDbFile.endsWith(".txt") || fullPathToDbFile.endsWith(".hash") || fullPathToDbFile.endsWith(".Hash")) {
// check whether index file for this text database is present
// For example, if text db name is "hash_db.txt" then index file name will be "hash_db.txt-md5.idx"
fullPathToIndexFile = fullPathToDbFile + "-md5.idx";
// if index file exists, copy it to the remote location
File dbIndexFile = new File(fullPathToIndexFile);
if (dbIndexFile.exists()) {
// copy index file to the remote folder
copyFile(sharedDbPath, dbIndexFile);
} else {
fullPathToIndexFile = "";
}
} else if (fullPathToDbFile.endsWith(".idx")) {
// hash db file itself is the index file and it has already been copied to the remote location
fullPathToIndexFile = fullPathToDbFile;
}
// check whether "index of the index" file exists for this hash DB's index file.
// NOTE: "index of the index" file may only exist
// for text hash database index files (i.e ".idx" extension). The index of the
// index file will always have the same name as the index file,
// distinguished only by the "2" in the extension. "index of the index" file
// is optional and may not be present.
if (fullPathToIndexFile.endsWith(".idx")) {
String fullPathToIndexOfIndexFile = fullPathToIndexFile + "2"; // "index of the index" file has same file name and extension ".idx2"
File dbIndexOfIndexFile = new File(fullPathToIndexOfIndexFile);
if (dbIndexOfIndexFile.exists()) {
// copy index of the index file to the remote folder
copyFile(sharedDbPath, dbIndexOfIndexFile);
}
}
}
newVersions.put(fullPathToDbFile, crc);
}
// Write the versions of all uploaded files to a file (make local and shared copies)
writeVersionsToFile(localVersionFile, newVersions);
writeVersionsToFile(sharedVersionFile, newVersions);
}
/**
* Utility method to copy a file
*
* @param sharedDbPath File object of the folder to copy to
* @param dbFile File object of the file to copy
*
* @throws
* org.sleuthkit.autopsy.configuration.SharedConfiguration.SharedConfigurationException
*/
private void copyFile(File sharedDbPath, File dbFile) throws SharedConfigurationException {
try {
Path path = Paths.get(sharedDbPath.toString(), dbFile.getName());
if (path.toFile().exists()) {
path.toFile().delete();
}
FileUtils.copyFileToDirectory(dbFile, sharedDbPath);
} catch (IOException | SecurityException ex) {
throw new SharedConfigurationException(String.format("Failed to copy %s to %s", dbFile.getAbsolutePath(), sharedDbPath.getAbsolutePath()), ex);
}
}
/**
* Upload settings and hash databases to the shared folder. The general
* algorithm is: - Copy the general settings in hashsets.xml - For each hash
* database listed in hashsets.xml: - Compare the recorded CRC in the shared
* directory with the one in the local directory - If different, download
* the database - Update the local list of database CRCs Note that databases
* are downloaded to the exact path they were uploaded from.
*
* @param remoteFolder Shared settings folder
*
* @throws SharedConfigurationException
*/
private void downloadHashDbSettings(File remoteFolder) throws SharedConfigurationException {
publishTask("Downloading HashDb module configuration");
// Read in the current local and shared database versions
File localVersionFile = new File(moduleDirPath, SHARED_CONFIG_VERSIONS);
File remoteVersionFile = new File(remoteFolder, SHARED_CONFIG_VERSIONS);
Map<String, String> localVersions = readVersionsFromFile(localVersionFile);
Map<String, String> remoteVersions = readVersionsFromFile(remoteVersionFile);
/*
Iterate through remote list
If local needs it, download
Download remote settings files to local
Download remote versions file to local
HashDbManager reload
*/
File localDb = new File("");
File sharedDb = new File("");
try {
for (String path : remoteVersions.keySet()) {
localDb = new File(path);
if ((!localVersions.containsKey(path))
|| (!localVersions.get(path).equals(remoteVersions.get(path)))
|| !localDb.exists()) {
// Need to download a new copy if
// - We have no entry for the database in the local versions file
// - The CRC in the local versions file does not match the one in the shared file
// - Local copy of the database does not exist
if (localDb.exists()) {
String crc = calculateCRC(path);
if (crc.equals(remoteVersions.get(path))) {
// Can skip the download if the local disk has it
// but it's just not in the versions file. This will
// be populated just before refreshing HashDbManager.
continue;
}
}
publishTask("Downloading " + path);
String sharedName = convertLocalDbPathToShared(path);
File sharedDbBaseFolder = new File(remoteFolder, REMOTE_HASH_FOLDER);
sharedDb = new File(sharedDbBaseFolder, sharedName);
if (!localDb.getParentFile().exists()) {
if (!localDb.getParentFile().mkdirs()) {
throw new SharedConfigurationException("Error creating hash database directory " + localDb.getParentFile().getAbsolutePath());
}
}
// If a copy of the database is loaded, close it before deleting and copying.
if (localDb.exists()) {
List<HashDbManager.HashDb> hashDbs = HashDbManager.getInstance().getAllHashSets();
HashDbManager.HashDb matchingDb = null;
for (HashDbManager.HashDb db : hashDbs) {
try {
if (localDb.getAbsolutePath().equals(db.getDatabasePath()) || localDb.getAbsolutePath().equals(db.getIndexPath())) {
matchingDb = db;
break;
}
} catch (TskCoreException ex) {
throw new SharedConfigurationException(String.format("Error getting hash database path info for %s", localDb.getParentFile().getAbsolutePath()), ex);
}
}
if (matchingDb != null) {
try {
HashDbManager.getInstance().removeHashDatabase(matchingDb);
} catch (HashDbManager.HashDbManagerException ex) {
throw new SharedConfigurationException(String.format("Error updating hash database info for %s", localDb.getAbsolutePath()), ex);
}
}
if (localDb.exists()) {
localDb.delete();
}
}
FileUtils.copyFile(sharedDb, localDb);
// check whether the hash db has an index file (.idx) that should also be copied.
// NOTE: only text hash databases (.txt, .hash, .Hash) can have index file.
// it is possible that the hash db file itself is the index file
String fullPathToRemoteDbFile = sharedDb.getPath();
String fullPathToRemoteIndexFile = "";
String fullPathToLocalIndexFile = "";
if (fullPathToRemoteDbFile.endsWith(".txt") || fullPathToRemoteDbFile.toLowerCase().endsWith(".hash")) {
// check whether index file for this text database is present
// For example, if text db name is "hash_db.txt" then index file name will be "hash_db.txt-md5.idx"
fullPathToRemoteIndexFile = fullPathToRemoteDbFile + "-md5.idx";
// if index file exists, copy it to the remote location
File remoteDbIndexFile = new File(fullPathToRemoteIndexFile);
if (remoteDbIndexFile.exists()) {
// delete local copy of "index of the index" file if one exists
fullPathToLocalIndexFile = localDb.getPath() + "-md5.idx";
File localIndexFile = new File(fullPathToLocalIndexFile);
if (localIndexFile.exists()) {
localIndexFile.delete();
}
// copy index file to the remote folder
FileUtils.copyFile(remoteDbIndexFile, localIndexFile);
} else {
// index file doesn't exist at remote location
fullPathToRemoteIndexFile = "";
}
} else if (fullPathToRemoteDbFile.endsWith(".idx")) {
// hash db file itself is the index file and it has already been copied to the remote location
fullPathToRemoteIndexFile = fullPathToRemoteDbFile;
fullPathToLocalIndexFile = localDb.getPath();
}
// check whether "index of the index" file exists for this hash DB index file.
// NOTE: "index of the index" file may only exist for hash database index files (.idx files).
// For example, hash_db.txt-md5.idx index file will have hash_db.txt-md5.idx2 "index of the index" file.
// "index of the index" file is optional and may not be present.
if (fullPathToRemoteIndexFile.endsWith(".idx")) {
// check if "index of the index" file exists in remote shared config folder
String fullPathToRemoteIndexOfIndexFile = fullPathToRemoteIndexFile + "2"; // "index of the index" file has same file name with extension ".idx2"
File remoteIndexOfIndexFile = new File(fullPathToRemoteIndexOfIndexFile);
if (remoteIndexOfIndexFile.exists()) {
// delete local copy of "index of the index" file if one exists
String fullPathToLocalIndexOfIndexFile = fullPathToLocalIndexFile + "2"; // "index of the index" file has same file name with extension ".idx2"
File localIndexOfIndexFile = new File(fullPathToLocalIndexOfIndexFile);
if (localIndexOfIndexFile.exists()) {
localIndexOfIndexFile.delete();
}
// copy index of the index file to the local folder
FileUtils.copyFile(remoteIndexOfIndexFile, localIndexOfIndexFile);
}
}
}
}
} catch (IOException | SecurityException ex) {
throw new SharedConfigurationException(String.format("Failed to copy %s to %s", sharedDb.getAbsolutePath(), localDb.getAbsolutePath()), ex);
}
// Copy the settings filey
copyToLocalFolder(HASHDB_CONFIG_FILE_NAME, moduleDirPath, remoteFolder, true);
copyToLocalFolder(HASHDB_CONFIG_FILE_NAME_LEGACY, moduleDirPath, remoteFolder, true);
copyToLocalFolder(SHARED_CONFIG_VERSIONS, moduleDirPath, remoteFolder, true);
// Refresh HashDbManager with the new settings
HashDbManager.getInstance().loadLastSavedConfiguration();
}
/**
* Read in the hashsets settings to pull out the names of the databases.
*
* @return List of all hash databases
*
* @throws SharedConfigurationException
*/
private static List<String> getHashFileNamesFromSettingsFile() throws SharedConfigurationException {
List<String> results = new ArrayList<>();
try {
HashDbManager hashDbManager = HashDbManager.getInstance();
hashDbManager.loadLastSavedConfiguration();
for (HashDb hashDb : hashDbManager.getAllHashSets()) {
if (hashDb.hasIndexOnly()) {
results.add(hashDb.getIndexPath());
} else {
results.add(hashDb.getDatabasePath());
}
}
} catch (TskCoreException ex) {
throw new SharedConfigurationException("Unable to read hash databases", ex);
}
return results;
}
/**
* Change the database path into a form that can be used to create
* subfolders in the shared folder.
*
* @param localName Database name from the XML file
*
* @return Path with the initial colon removed
*/
private static String convertLocalDbPathToShared(String localName) {
// Replace the colon
String sharedName = localName.replace(":", "__colon__");
return sharedName;
}
/**
* Write the list of database paths and versions to a file.
*
* @param versionFile File to write to
* @param versions Map of database name -> version (current using CRCs as
* versions)
*
* @throws SharedConfigurationException
*/
private static void writeVersionsToFile(File versionFile, Map<String, String> versions) throws SharedConfigurationException {
try (PrintWriter writer = new PrintWriter(versionFile.getAbsoluteFile(), "UTF-8")) {
for (String filename : versions.keySet()) {
writer.println(versions.get(filename) + " " + filename);
}
} catch (FileNotFoundException | UnsupportedEncodingException ex) {
throw new SharedConfigurationException(String.format("Failed to write version info to %s", versionFile), ex);
}
}
/**
* Read the map of database paths to versions from a file.
*
* @param versionFile File containing the version information
*
* @return Map of database name -> version
*
* @throws SharedConfigurationException
*/
private static Map<String, String> readVersionsFromFile(File versionFile) throws SharedConfigurationException {
Map<String, String> versions = new HashMap<>();
// If the file does not exist, return an empty map
if (!versionFile.exists()) {
return versions;
}
// Read in and store each pair
try (BufferedReader reader = new BufferedReader(new FileReader(versionFile))) {
String currentLine = reader.readLine();
while (null != currentLine) {
if (!currentLine.isEmpty()) {
int index = currentLine.indexOf(' '); // Find the first space
String crc = currentLine.substring(0, index);
String path = currentLine.substring(index + 1);
versions.put(path, crc);
}
currentLine = reader.readLine();
}
} catch (FileNotFoundException ex) {
throw new SharedConfigurationException(String.format("Failed to find version file %s", versionFile), ex);
} catch (IOException ex) {
throw new SharedConfigurationException(String.format("Failed to read version info from %s", versionFile), ex);
}
return versions;
}
/**
* Calculate the CRC of a file to use to determine if it has changed.
*
* @param filePath File to get the CRC for
*
* @return String containing the CRC
*
* @throws SharedConfigurationException
*/
private static String calculateCRC(String filePath) throws SharedConfigurationException {
File file = new File(filePath);
try {
FileInputStream fileStream = new FileInputStream(file);
CRC32 crc = new CRC32();
byte[] buffer = new byte[65536];
int bytesRead = fileStream.read(buffer);
while (-1 != bytesRead) {
crc.update(buffer, 0, bytesRead);
bytesRead = fileStream.read(buffer);
}
return String.valueOf(crc.getValue());
} catch (IOException ex) {
throw new SharedConfigurationException(String.format("Failed to calculate CRC for %s", file.getAbsolutePath()), ex);
}
}
}
| apache-2.0 |
xtien/motogymkhana-server-ui | src/main/java/eu/motogymkhana/server/api/request/TokenRequest.java | 325 | package eu.motogymkhana.server.api.request;
public class TokenRequest extends GymkhanaRequest {
private String email;
private String token;
public TokenRequest() {
}
public TokenRequest(String userName, String password, String token) {
this.email = userName;
this.password = password;
this.token = token;
}
}
| apache-2.0 |
gdefias/JavaDemo | InitJava/base/src/main/java/FileIO/NIO/TestNIOChannel_FileChannel.java | 4799 | package FileIO.NIO;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* Created by Defias on 2017/3/8.
*
* FileChannel
*
* 一个连接到文件的通道。可以通过文件通道读写文件
* FileChannel不可以设置为非阻塞模式,他只能在阻塞模式下运行
*
* public final FileChannel getChannel() {
* synchronized (this) {
* if (channel == null) {
* channel = FileChannelImpl.open(fd, path, true, rw, this);
* }
* return channel;
* }
* } //由于synchronized ,并发时只有一个线程能够初始化FileChannel
*
*
* FileChannel部分方法:
* abstract long transferFrom(ReadableByteChannel src, long position, long count)
* 将字节从给定的可读取字节通道传输到此通道的文件中
* 从源通道中最多读取count个字节,并将其写入到此通道的文件中从给定position处开始的位置
* 参数position和count表示目标文件的写入位置和最多写入的数据量
*
* abstract long transferTo(long position, long count, WritableByteChannel target)
* 将字节从此通道的文件传输到给定的可写入字节通道
* 读取从此通道的文件中给定position处开始的count个字节,并将其写入目标通道
*
* abstract FileChannel truncate(long size)
* 将此通道的文件截取为给定大小
*
* abstract void force(boolean metaData)
* 强制将所有对此通道的文件更新写入包含该文件的存储设备中
* 会把所有未写磁盘的数据都强制写入磁盘。这是因为在操作系统中出于性能考虑会把数据放入缓冲区,所以不能保证数据在调用write写入文件通道
* 后就及时写到磁盘上了,除非手动调用force方法。force方法需要一个布尔参数,代表是否把meta data也一并强制写入
*
* abstract long size()
* 返回此通道的文件的当前大小
*/
public class TestNIOChannel_FileChannel {
public static void main(String[] args) throws IOException {
test0();
//test1();
//test2();
//test3
}
public static void test0() throws IOException {
//基本使用
RandomAccessFile aFile = new RandomAccessFile("base/src/nio-data.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48); //分配48字节的Buffer
int bytesRead = inChannel.read(buf); //读取数据写到Buffer中,返回写了多少数据
while (bytesRead!= -1) {
System.out.println("Read " + bytesRead);
buf.flip();//反转buffer
while (buf.hasRemaining()) { //hasRemaining: 是否读已经达到缓冲区的上界
System.out.print((char) buf.get()); //一次读一个字节
}
buf.clear(); //清除buffer
//继续从Channel读取数据写到Buffer中
bytesRead = inChannel.read(buf);
}
aFile.close();
}
public static void test1() throws IOException {
//把test.txt文件中的数据拷贝到out.txt中
FileChannel in = new FileInputStream("base/src/outnio.txt").getChannel();
FileChannel out = new FileOutputStream("base/src/outnio.txt").getChannel();
final int BSIZE = 1024;
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
while(in.read(buff) != -1) { //buff为写模式(从in中读取到然后写入到buff中)
buff.flip();
out.write(buff); //buff为读模式(从buff中读取到然后写入out中)
buff.clear();
}
in.close();
out.close();
}
public static void test2() throws IOException {
//transferFrom
RandomAccessFile fromFile = new RandomAccessFile("base/src/fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("base/src/toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
toChannel.transferFrom(fromChannel, position, count);
}
public static void test3() throws IOException {
//transferTo
RandomAccessFile fromFile = new RandomAccessFile("base/src/fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("base/src/toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
fromChannel.transferTo(position, count, toChannel);
}
}
| apache-2.0 |
GEBIT/mamute | src/main/java/org/mamute/auth/LDAPApi.java | 10735 | package org.mamute.auth;
import static org.apache.commons.lang.StringUtils.isEmpty;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import static org.mamute.model.SanitizedText.fromTrustedText;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.naming.directory.InvalidAttributeValueException;
import org.apache.directory.api.ldap.model.cursor.CursorException;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.entry.Attribute;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.entry.Value;
import org.apache.directory.api.ldap.model.exception.LdapAuthenticationException;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.mamute.dao.LoginMethodDAO;
import org.mamute.dao.UserDAO;
import org.mamute.filesystem.ImageStore;
import org.mamute.infra.ClientIp;
import org.mamute.model.Attachment;
import org.mamute.model.LoginMethod;
import org.mamute.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import br.com.caelum.vraptor.environment.Environment;
import br.com.caelum.vraptor.observer.upload.DefaultUploadedFile;
/**
* LDAP authentication API
*/
public class LDAPApi {
private static final Logger logger = LoggerFactory.getLogger(LDAPApi.class);
public static final String LDAP_AUTH = "ldap";
public static final String LDAP_HOST = "ldap.host";
public static final String LDAP_PORT = "ldap.port";
public static final String LDAP_USER = "ldap.user";
public static final String LDAP_PASS = "ldap.pass";
public static final String LDAP_USER_DN = "ldap.userDn";
public static final String LDAP_EMAIL = "ldap.emailAttr";
public static final String LDAP_NAME = "ldap.nameAttr";
public static final String LDAP_SURNAME = "ldap.surnameAttr";
public static final String LDAP_GROUP = "ldap.groupAttr";
public static final String LDAP_LOOKUP = "ldap.lookupAttr";
public static final String LDAP_MODERATOR_GROUP = "ldap.moderatorGroup";
public static final String PLACHOLDER_PASSWORD = "ldap-password-ignore-me";
public static final String LDAP_USE_SSL = "ldap.useSSL";
public static final String LDAP_AVATAR_IMAGE = "ldap.avatarImageAttr";
@Inject private Environment env;
@Inject private UserDAO users;
@Inject private LoginMethodDAO loginMethods;
@Inject private ImageStore imageStore;
@Inject private ClientIp clientIp;
private String host;
private Integer port;
private String user;
private String pass;
private String userDn;
private String emailAttr;
private String nameAttr;
private String surnameAttr;
private String groupAttr;
private String[] lookupAttrs;
private String moderatorGroup;
private Boolean useSsl;
private String avatarImageAttr;
/**
* Ensure that required variables are set if LDAP auth
* is enabled
*/
@PostConstruct
public void init() {
if (env.supports("feature.auth.ldap")) {
//required
host = assertValuePresent(LDAP_HOST);
port = Integer.parseInt(assertValuePresent(LDAP_PORT));
user = assertValuePresent(LDAP_USER);
pass = assertValuePresent(LDAP_PASS);
userDn = assertValuePresent(LDAP_USER_DN);
emailAttr = assertValuePresent(LDAP_EMAIL);
nameAttr = assertValuePresent(LDAP_NAME);
//optional
surnameAttr = env.get(LDAP_SURNAME, "");
groupAttr = env.get(LDAP_GROUP, "");
moderatorGroup = env.get(LDAP_MODERATOR_GROUP, "");
lookupAttrs = env.get(LDAP_LOOKUP, "").split(",");
useSsl = env.supports(LDAP_USE_SSL);
avatarImageAttr = env.get(LDAP_AVATAR_IMAGE, "");
}
}
/**
* Attempt to authenticate against LDAP directory. Accepts email addresses
* as well as plain usernames; emails will have the '@mail.com' portion
* stripped off before read.
*
* @param username
* @param password
* @return
*/
public boolean authenticate(String username, String password) {
try (LDAPResource ldap = new LDAPResource()) {
String cn = userCn(username);
ldap.verifyCredentials(cn, password);
createUserIfNeeded(ldap, cn);
logger.info("Successful LDAP login: " + username);
return true;
} catch (LdapAuthenticationException e) {
logger.info("LDAP auth attempt failed");
return false;
} catch (LdapException | IOException e) {
logger.warn("LDAP connection error", e);
throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e);
}
}
/**
* Find the email address for a given username
*
* @param username
* @return
*/
public String getEmail(String username) {
try (LDAPResource ldap = new LDAPResource()) {
Entry ldapUser = ldap.getUser(userCn(username));
return ldap.getAttribute(ldapUser, emailAttr);
} catch (LdapException | IOException e) {
logger.warn("LDAP connection error", e);
throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e);
}
}
private String userCn(String username) {
if (lookupAttrs.length > 0) {
try (LDAPResource ldap = new LDAPResource()) {
Entry user = ldap.lookupUser(username);
if (user != null) {
return user.getDn().getName();
}
} catch (LdapException | IOException e) {
logger.warn("LDAP connection error", e);
throw new AuthenticationException(LDAP_AUTH, "LDAP connection error", e);
}
}
// fallback: assume lookup by CN
String sanitizedUser = username.replaceAll("[,=]", "");
String cn = "cn=" + sanitizedUser + "," + userDn;
return cn;
}
private void updateAvatarImage(LDAPResource ldap, Entry entry, User user) {
try {
byte[] jpegBytes = getAvatarImage(ldap, entry);
if (jpegBytes != null) {
String fileName = user.getEmail() + ".jpg";
DefaultUploadedFile avatar = new DefaultUploadedFile(new ByteArrayInputStream(jpegBytes), fileName, "image/jpeg", jpegBytes.length);
Attachment attachment = imageStore.processAndStore(avatar, user, clientIp);
Attachment old = user.getAvatar();
if (old != null) {
imageStore.delete(old);
}
user.setAvatar(attachment);
}
} catch (LdapException | IOException e) {
// problems with avatar processing are non-fatal
logger.warn("Error updating user avatar from LDAP: " + user.getName(), e);
}
}
private byte[] getAvatarImage(LDAPResource ldap, Entry entry) throws LdapException {
if (avatarImageAttr != null && avatarImageAttr.length() > 0) {
try {
return ldap.getByteAttribute(entry, avatarImageAttr);
} catch (InvalidAttributeValueException ex) {
throw new LdapException("Invalid attribute value while looking up " + avatarImageAttr, ex);
}
}
return null;
}
private void createUserIfNeeded(LDAPResource ldap, String cn) throws LdapException {
Entry ldapUser = ldap.getUser(cn);
String email = ldap.getAttribute(ldapUser, emailAttr);
User user = email != null ? users.findByEmail(email) : null;
if (user == null) {
String fullName = ldap.getAttribute(ldapUser, nameAttr);
if (isNotEmpty(surnameAttr)) {
fullName += " " + ldap.getAttribute(ldapUser, surnameAttr);
}
user = new User(fromTrustedText(fullName.trim()), email);
LoginMethod brutalLogin = LoginMethod.brutalLogin(user, email, PLACHOLDER_PASSWORD);
user.add(brutalLogin);
users.save(user);
loginMethods.save(brutalLogin);
}
//update moderator status
if (isNotEmpty(moderatorGroup) && ldap.getGroups(ldapUser).contains(moderatorGroup)) {
user = user.asModerator();
} else {
user.removeModerator();
}
updateAvatarImage(ldap, ldapUser, user);
users.save(user);
}
private String assertValuePresent(String field) {
String value = env.get(field, "");
if (isEmpty(value)) {
throw new RuntimeException("Field [" + field + "] is required when using LDAP authentication");
}
return value;
}
/**
* Acts as a session-level LDAP connection.
*/
private class LDAPResource implements AutoCloseable {
LdapConnection connection;
private LDAPResource() throws LdapException {
connection = connection(user, pass);
}
private void verifyCredentials(String userCn, String password) throws LdapException, IOException {
try (LdapConnection conn = connection(userCn, password)) {
logger.debug("LDAP login from [" + userCn + "]");
}
}
private LdapConnection connection(String username, String password) throws LdapException {
LdapNetworkConnection conn = new LdapNetworkConnection(host, port, useSsl);
conn.bind(username, password);
return conn;
}
private List<String> getGroups(Entry user) {
List<String> groupCns = new ArrayList<>();
if (isNotEmpty(groupAttr)) {
Attribute grpEntry = user.get(groupAttr);
if (grpEntry != null) {
for (Value grp : grpEntry) {
groupCns.add(grp.getString());
}
}
}
return groupCns;
}
private Entry getUser(String cn) throws LdapException {
return connection.lookup(cn);
}
private Entry lookupUser(String username) throws LdapException {
StringBuilder userQuery = new StringBuilder();
userQuery.append("(&(objectclass=user)(|");
boolean hasCondition = false;
for (String lookupAttr : lookupAttrs) {
String attrName = lookupAttr.trim();
if (!attrName.isEmpty()) {
userQuery.append('(').append(attrName).append('=').append(username).append(')');
hasCondition = true;
}
}
userQuery.append("))");
if (!hasCondition) {
return null;
}
logger.debug("LDAP user query " + userQuery.toString());
EntryCursor responseCursor = connection.search(userDn, userQuery.toString(), SearchScope.SUBTREE);
try {
try {
if (responseCursor != null && responseCursor.next()) {
Entry match = responseCursor.get();
logger.debug("LDAP user query result: " + match.getDn());
return match;
}
} catch (CursorException e) {
logger.debug("LDAP search error", e);
return null;
}
} finally {
responseCursor.close();
}
return null;
}
private String getAttribute(Entry entry, String attribute) throws LdapException {
Attribute value = entry.get(attribute);
if (value != null) {
return value.getString();
}
return null;
}
private byte[] getByteAttribute(Entry entry, String attribute) throws LdapException, InvalidAttributeValueException {
Attribute value = entry.get(attribute);
if (value != null) {
return value.getBytes();
}
return null;
}
@Override
public void close() throws IOException {
connection.close();
}
}
}
| apache-2.0 |
googleads/googleads-java-lib | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202108/PublisherQueryLanguageService.java | 1350 | // 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
//
// 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.
/**
* PublisherQueryLanguageService.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.admanager.axis.v202108;
public interface PublisherQueryLanguageService extends javax.xml.rpc.Service {
public java.lang.String getPublisherQueryLanguageServiceInterfacePortAddress();
public com.google.api.ads.admanager.axis.v202108.PublisherQueryLanguageServiceInterface getPublisherQueryLanguageServiceInterfacePort() throws javax.xml.rpc.ServiceException;
public com.google.api.ads.admanager.axis.v202108.PublisherQueryLanguageServiceInterface getPublisherQueryLanguageServiceInterfacePort(java.net.URL portAddress) throws javax.xml.rpc.ServiceException;
}
| apache-2.0 |
Mohammad2416/android-obd-reader-master | src/main/java/com/ahmadi/android/obd/reader/activity/TripListActivity.java | 4910 | package com.ahmadi.android.obd.reader.activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.ahmadi.android.obd.reader.R;
import com.ahmadi.android.obd.reader.trips.TripListAdapter;
import com.ahmadi.android.obd.reader.trips.TripLog;
import com.ahmadi.android.obd.reader.trips.TripRecord;
import java.util.List;
import roboguice.activity.RoboActivity;
import static com.ahmadi.android.obd.reader.activity.ConfirmDialog.createDialog;
/**
* Some code taken from https://github.com/wdkapps/FillUp
*/
public class TripListActivity
extends RoboActivity
implements ConfirmDialog.Listener {
private List<TripRecord> records;
private TripLog triplog = null;
private TripListAdapter adapter = null;
/// the currently selected row from the list of records
private int selectedRow;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trips_list);
ListView lv = (ListView) findViewById(R.id.tripList);
triplog = TripLog.getInstance(this.getApplicationContext());
records = triplog.readAllRecords();
adapter = new TripListAdapter(this, records);
lv.setAdapter(adapter);
registerForContextMenu(lv);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.menu_trips_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
// create the menu
getMenuInflater().inflate(R.menu.context_trip_list, menu);
// get index of currently selected row
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
selectedRow = (int) info.id;
// get record that is currently selected
TripRecord record = records.get(selectedRow);
}
private void deleteTrip() {
// get the record to delete from our list of records
TripRecord record = records.get(selectedRow);
// attempt to remove the record from the log
if (triplog.deleteTrip(record.getID())) {
// remove the record from our list of records
records.remove(selectedRow);
// update the list view
adapter.notifyDataSetChanged();
} else {
//Utilities.toast(this,getString(R.string.toast_delete_failed));
}
}
public boolean onContextItemSelected(MenuItem item) {
// get index of currently selected row
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
selectedRow = (int) info.id;
switch (item.getItemId()) {
case R.id.itemDelete:
showDialog(ConfirmDialog.DIALOG_CONFIRM_DELETE_ID);
return true;
default:
return super.onContextItemSelected(item);
}
}
protected Dialog onCreateDialog(int id) {
return createDialog(id, this, this);
}
/**
* DESCRIPTION:
* Called when the user has selected a gasoline record to delete
* from the log and has confirmed deletion.
*/
protected void deleteRow() {
// get the record to delete from our list of records
TripRecord record = records.get(selectedRow);
// attempt to remove the record from the log
if (triplog.deleteTrip(record.getID())) {
records.remove(selectedRow);
adapter.notifyDataSetChanged();
} else {
//Utilities.toast(this,getString(R.string.toast_delete_failed));
}
}
@Override
public void onConfirmationDialogResponse(int id, boolean confirmed) {
removeDialog(id);
if (!confirmed) return;
switch (id) {
case ConfirmDialog.DIALOG_CONFIRM_DELETE_ID:
deleteRow();
break;
default:
//Utilities.toast(this,"Invalid dialog id.");
}
}
}
| apache-2.0 |
camelinaction/camelinaction2 | chapter4/bean/src/main/java/camelinaction/InvokeWithBeanRoute.java | 408 | package camelinaction;
import org.apache.camel.builder.RouteBuilder;
/**
* Using a bean in the route to invoke HelloBean.
*/
public class InvokeWithBeanRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:hello")
// instantiate HelloBean once, and reuse and invoke the hello bean
.bean(HelloBean.class, "hello");
}
}
| apache-2.0 |
itchix/TestMVPAndroid | app/src/main/java/com/scrachx/foodfacts/checker/ui/history/HistoryPresenter.java | 3113 | /*
* Copyright (C) 20/05/2017 Scot Scriven
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.scrachx.foodfacts.checker.ui.history;
import com.androidnetworking.error.ANError;
import com.scrachx.foodfacts.checker.data.DataManager;
import com.scrachx.foodfacts.checker.ui.base.BasePresenter;
import javax.inject.Inject;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
public class HistoryPresenter<V extends HistoryMvpView> extends BasePresenter<V> implements HistoryMvpPresenter<V> {
@Inject
public HistoryPresenter(DataManager dataManager, CompositeDisposable compositeDisposable) {
super(dataManager, compositeDisposable);
}
@Override
public void onLoadProducts(int page, String grade) {
getMvpView().showLoading();
getCompositeDisposable().add(getDataManager()
.getHistory(page, grade)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(historyItem -> {
if (!isViewAttached()) {
return;
}
if (historyItem != null) {
getMvpView().loadHistory(historyItem.getProductsHistory(), historyItem.getCount());
}
getMvpView().hideLoading();
}));
}
@Override
public void loadProduct(String barcode) {
getMvpView().showLoading();
getCompositeDisposable().add(getDataManager()
.searchProductByBarcode(barcode)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(stateProduct -> {
if (!isViewAttached()) {
return;
}
if (stateProduct != null) {
getMvpView().openPageProduct(stateProduct);
}
getMvpView().hideLoading();
}, throwable -> {
if (!isViewAttached()) {
return;
}
getMvpView().hideLoading();
// handle the login error here
if (throwable instanceof ANError) {
ANError anError = (ANError) throwable;
handleApiError(anError);
}
}));
}
}
| apache-2.0 |
dbourdette/otto | otto-web/src/test/java/com/github/dbourdette/otto/source/config/DummyOperation.java | 1035 | /*
* Copyright 2011 Damien Bourdette
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.dbourdette.otto.source.config;
import com.github.dbourdette.otto.source.config.transform.TransformOperation;
public class DummyOperation implements TransformOperation {
public int callCount;
@Override
public String getShortName() {
return "dummy";
}
@Override
public Object apply(Object value) {
callCount++;
return value;
}
}
| apache-2.0 |
karussell/fastutil | src/it/unimi/dsi/fastutil/floats/Float2CharFunction.java | 4321 | /* Generic definitions */
/* Assertions (useful to generate conditional code) */
/* Current type and class (and size, if applicable) */
/* Value methods */
/* Interfaces (keys) */
/* Interfaces (values) */
/* Abstract implementations (keys) */
/* Abstract implementations (values) */
/* Static containers (keys) */
/* Static containers (values) */
/* Implementations */
/* Synchronized wrappers */
/* Unmodifiable wrappers */
/* Other wrappers */
/* Methods (keys) */
/* Methods (values) */
/* Methods (keys/values) */
/* Methods that have special names depending on keys (but the special names depend on values) */
/* Equality */
/* Object/Reference-only definitions (keys) */
/* Primitive-type-only definitions (keys) */
/* Object/Reference-only definitions (values) */
/* Primitive-type-only definitions (values) */
/*
* Copyright (C) 2002-2013 Sebastiano Vigna
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package it.unimi.dsi.fastutil.floats;
import it.unimi.dsi.fastutil.Function;
/** A type-specific {@link Function}; provides some additional methods that use polymorphism to avoid (un)boxing.
*
* <P>Type-specific versions of <code>get()</code>, <code>put()</code> and
* <code>remove()</code> cannot rely on <code>null</code> to denote absence of
* a key. Rather, they return a {@linkplain #defaultReturnValue() default
* return value}, which is set to 0 cast to the return type (<code>false</code>
* for booleans) at creation, but can be changed using the
* <code>defaultReturnValue()</code> method.
*
* <P>For uniformity reasons, even maps returning objects implement the default
* return value (of course, in this case the default return value is
* initialized to <code>null</code>).
*
* <P><strong>Warning:</strong> to fall in line as much as possible with the
* {@linkplain java.util.Map standard map interface}, it is strongly suggested
* that standard versions of <code>get()</code>, <code>put()</code> and
* <code>remove()</code> for maps with primitive-type values <em>return
* <code>null</code> to denote missing keys</em> rather than wrap the default
* return value in an object (of course, for maps with object keys and values
* this is not possible, as there is no type-specific version).
*
* @see Function
*/
public interface Float2CharFunction extends Function<Float, Character> {
/** Adds a pair to the map.
*
* @param key the key.
* @param value the value.
* @return the old value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key.
* @see Function#put(Object,Object)
*/
char put( float key, char value );
/** Returns the value to which the given key is mapped.
*
* @param key the key.
* @return the corresponding value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key.
* @see Function#get(Object)
*/
char get( float key );
/** Removes the mapping with the given key.
* @param key
* @return the old value, or the {@linkplain #defaultReturnValue() default return value} if no value was present for the given key.
* @see Function#remove(Object)
*/
char remove( float key );
/**
* @see Function#containsKey(Object)
*/
boolean containsKey( float key );
/** Sets the default return value.
*
* This value must be returned by type-specific versions of
* <code>get()</code>, <code>put()</code> and <code>remove()</code> to
* denote that the map does not contain the specified key. It must be
* 0/<code>false</code>/<code>null</code> by default.
*
* @param rv the new default return value.
* @see #defaultReturnValue()
*/
void defaultReturnValue( char rv );
/** Gets the default return value.
*
* @return the current default return value.
*/
char defaultReturnValue();
}
| apache-2.0 |
pitchpoint-solutions/sfs | sfs-server/src/main/java/org/sfs/elasticsearch/object/LoadAccountAndContainerAndObject.java | 2423 | /*
* Copyright 2016 The Simple File Server Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sfs.elasticsearch.object;
import org.sfs.Server;
import org.sfs.VertxContext;
import org.sfs.elasticsearch.account.LoadAccount;
import org.sfs.elasticsearch.container.LoadContainer;
import org.sfs.validate.ValidatePersistentAccountExists;
import org.sfs.validate.ValidatePersistentContainerExists;
import org.sfs.validate.ValidatePersistentObjectExists;
import org.sfs.vo.ObjectPath;
import org.sfs.vo.PersistentObject;
import rx.Observable;
import rx.functions.Func1;
import static rx.Observable.just;
public class LoadAccountAndContainerAndObject implements Func1<ObjectPath, Observable<PersistentObject>> {
private final VertxContext<Server> vertxContext;
public LoadAccountAndContainerAndObject(VertxContext<Server> vertxContext) {
this.vertxContext = vertxContext;
}
@Override
public Observable<PersistentObject> call(ObjectPath objectPath) {
String accountId = objectPath.accountPath().get();
String containerId = objectPath.containerPath().get();
String objectId = objectPath.objectPath().get();
return just(accountId)
.flatMap(new LoadAccount(vertxContext))
.map(new ValidatePersistentAccountExists())
.flatMap(persistentAccount ->
just(containerId)
.flatMap(new LoadContainer(vertxContext, persistentAccount))
.map(new ValidatePersistentContainerExists())
.flatMap(persistentContainer ->
just(objectId)
.flatMap(new LoadObject(vertxContext, persistentContainer))
.map(new ValidatePersistentObjectExists())));
}
}
| apache-2.0 |
arscyper/adan | src/com/google/code/appengine/awt/PageAttributes.java | 23806 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Igor A. Pyankov
*/
package com.google.code.appengine.awt;
import java.util.Locale;
import org.apache.harmony.awt.internal.nls.Messages;
public final class PageAttributes implements Cloneable {
private MediaType media;
private ColorType color;
private OrientationRequestedType orientationRequested;
private OriginType origin;
private PrintQualityType printQuality;
private int[] printerResolution;
/*----------------- section of the nested classes --------------------*/
public static final class ColorType {
private final String name;
public static final ColorType COLOR
= new ColorType(0, "COLOR"); //$NON-NLS-1$
public static final ColorType MONOCHROME
= new ColorType(1, "MONOCHROME"); //$NON-NLS-1$
private ColorType(int i, String n){
super();
name = n;
}
private ColorType(){
this(1, "MONOCHROME"); //$NON-NLS-1$
}
}
public static final class MediaType {
private final String name;
public static final MediaType ISO_4A0 = new MediaType(71, "ISO_4A0"); //$NON-NLS-1$
public static final MediaType ISO_2A0 = new MediaType(70, "ISO_2A0"); //$NON-NLS-1$
public static final MediaType ISO_A0 = new MediaType(0, "ISO_A0"); //$NON-NLS-1$
public static final MediaType ISO_A1 = new MediaType(1, "ISO_A1"); //$NON-NLS-1$
public static final MediaType ISO_A2 = new MediaType(2, "ISO_A2"); //$NON-NLS-1$
public static final MediaType ISO_A3 = new MediaType(3, "ISO_A3"); //$NON-NLS-1$
public static final MediaType ISO_A4 = new MediaType(4, "ISO_A4"); //$NON-NLS-1$
public static final MediaType ISO_A5 = new MediaType(5, "ISO_A5"); //$NON-NLS-1$
public static final MediaType ISO_A6 = new MediaType(6, "ISO_A6"); //$NON-NLS-1$
public static final MediaType ISO_A7 = new MediaType(7, "ISO_A7"); //$NON-NLS-1$
public static final MediaType ISO_A8 = new MediaType(8, "ISO_A8"); //$NON-NLS-1$
public static final MediaType ISO_A9 = new MediaType(9, "ISO_A9"); //$NON-NLS-1$
public static final MediaType ISO_A10 = new MediaType(10, "ISO_A10"); //$NON-NLS-1$
public static final MediaType ISO_B0 = new MediaType(10, "ISO_B0"); //$NON-NLS-1$
public static final MediaType ISO_B1 = new MediaType(11, "ISO_B1"); //$NON-NLS-1$
public static final MediaType ISO_B2 = new MediaType(12, "ISO_B2"); //$NON-NLS-1$
public static final MediaType ISO_B3 = new MediaType(13, "ISO_B3"); //$NON-NLS-1$
public static final MediaType ISO_B4 = new MediaType(14, "ISO_B4"); //$NON-NLS-1$
public static final MediaType ISO_B5 = new MediaType(15, "ISO_B5"); //$NON-NLS-1$
public static final MediaType ISO_B6 = new MediaType(16, "ISO_B6"); //$NON-NLS-1$
public static final MediaType ISO_B7 = new MediaType(17, "ISO_B7"); //$NON-NLS-1$
public static final MediaType ISO_B8 = new MediaType(18, "ISO_B8"); //$NON-NLS-1$
public static final MediaType ISO_B9 = new MediaType(19, "ISO_B9"); //$NON-NLS-1$
public static final MediaType ISO_B10 = new MediaType(20, "ISO_B10"); //$NON-NLS-1$
public static final MediaType JIS_B0 = new MediaType(30, "JIS_B0"); //$NON-NLS-1$
public static final MediaType JIS_B1 = new MediaType(31, "JIS_B1"); //$NON-NLS-1$
public static final MediaType JIS_B2 = new MediaType(32, "JIS_B2"); //$NON-NLS-1$
public static final MediaType JIS_B3 = new MediaType(33, "JIS_B3"); //$NON-NLS-1$
public static final MediaType JIS_B4 = new MediaType(34, "JIS_B4"); //$NON-NLS-1$
public static final MediaType JIS_B5 = new MediaType(35, "JIS_B5"); //$NON-NLS-1$
public static final MediaType JIS_B6 = new MediaType(36, "JIS_B6"); //$NON-NLS-1$
public static final MediaType JIS_B7 = new MediaType(37, "JIS_B7"); //$NON-NLS-1$
public static final MediaType JIS_B8 = new MediaType(38, "JIS_B8"); //$NON-NLS-1$
public static final MediaType JIS_B9 = new MediaType(39, "JIS_B9"); //$NON-NLS-1$
public static final MediaType JIS_B10 = new MediaType(40, "JIS_B10"); //$NON-NLS-1$
public static final MediaType ISO_C0 = new MediaType(50, "ISO_C0"); //$NON-NLS-1$
public static final MediaType ISO_C1 = new MediaType(51, "ISO_C1"); //$NON-NLS-1$
public static final MediaType ISO_C2 = new MediaType(52, "ISO_C2"); //$NON-NLS-1$
public static final MediaType ISO_C3 = new MediaType(53, "ISO_C3"); //$NON-NLS-1$
public static final MediaType ISO_C4 = new MediaType(54, "ISO_C4"); //$NON-NLS-1$
public static final MediaType ISO_C5 = new MediaType(55, "ISO_C5"); //$NON-NLS-1$
public static final MediaType ISO_C6 = new MediaType(56, "ISO_C6"); //$NON-NLS-1$
public static final MediaType ISO_C7 = new MediaType(57, "ISO_C7"); //$NON-NLS-1$
public static final MediaType ISO_C8 = new MediaType(58, "ISO_C8"); //$NON-NLS-1$
public static final MediaType ISO_C9 = new MediaType(59, "ISO_C9"); //$NON-NLS-1$
public static final MediaType ISO_C10 = new MediaType(60, "ISO_C10"); //$NON-NLS-1$
public static final MediaType ISO_DESIGNATED_LONG = new MediaType(100,
"ISO_DESIGNATED_LONG"); //$NON-NLS-1$
public static final MediaType EXECUTIVE = new MediaType(101,
"EXECUTIVE"); //$NON-NLS-1$
public static final MediaType FOLIO = new MediaType(102, "FOLIO"); //$NON-NLS-1$
public static final MediaType INVOICE = new MediaType(103, "INVOICE"); //$NON-NLS-1$
public static final MediaType LEDGER = new MediaType(104, "LEDGER"); //$NON-NLS-1$
public static final MediaType NA_LETTER = new MediaType(105,
"NA_LETTER"); //$NON-NLS-1$
public static final MediaType NA_LEGAL = new MediaType(106, "NA_LEGAL"); //$NON-NLS-1$
public static final MediaType QUARTO = new MediaType(107, "QUARTO"); //$NON-NLS-1$
public static final MediaType A = new MediaType(200, "A"); //$NON-NLS-1$
public static final MediaType B = new MediaType(201, "B"); //$NON-NLS-1$
public static final MediaType C = new MediaType(202, "C"); //$NON-NLS-1$
public static final MediaType D = new MediaType(203, "D"); //$NON-NLS-1$
public static final MediaType E = new MediaType(204, "E"); //$NON-NLS-1$
public static final MediaType NA_10X15_ENVELOPE = new MediaType(311,
"NA_10X15_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_10X14_ENVELOPE = new MediaType(310,
"NA_10X14_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_10X13_ENVELOPE = new MediaType(309,
"NA_10X13_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_9X12_ENVELOPE = new MediaType(308,
"NA_9X12_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_9X11_ENVELOPE = new MediaType(307,
"NA_9X11_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_7X9_ENVELOPE = new MediaType(306,
"NA_7X9_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_6X9_ENVELOPE = new MediaType(305,
"NA_6X9_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_NUMBER_9_ENVELOPE = new MediaType(
312, "NA_NUMBER_9_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_NUMBER_10_ENVELOPE = new MediaType(
313, "NA_NUMBER_10_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_NUMBER_11_ENVELOPE = new MediaType(
314, "NA_NUMBER_11_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_NUMBER_12_ENVELOPE = new MediaType(
315, "NA_NUMBER_12_ENVELOPE"); //$NON-NLS-1$
public static final MediaType NA_NUMBER_14_ENVELOPE = new MediaType(
316, "NA_NUMBER_14_ENVELOPE"); //$NON-NLS-1$
public static final MediaType INVITE_ENVELOPE = new MediaType(300,
"INVITE_ENVELOPE"); //$NON-NLS-1$
public static final MediaType ITALY_ENVELOPE = new MediaType(301,
"ITALY_ENVELOPE"); //$NON-NLS-1$
public static final MediaType MONARCH_ENVELOPE = new MediaType(302,
"MONARCH_ENVELOPE"); //$NON-NLS-1$
public static final MediaType PERSONAL_ENVELOPE = new MediaType(304,
"PERSONAL_ENVELOPE"); //$NON-NLS-1$
/*aliases*/
public static final MediaType A0 = ISO_A0;
public static final MediaType A1 = ISO_A1;
public static final MediaType A2 = ISO_A2;
public static final MediaType A3 = ISO_A3;
public static final MediaType A4 = ISO_A4;
public static final MediaType A5 = ISO_A5;
public static final MediaType A6 = ISO_A6;
public static final MediaType A7 = ISO_A7;
public static final MediaType A8 = ISO_A8;
public static final MediaType A9 = ISO_A9;
public static final MediaType A10 = ISO_A10;
public static final MediaType B0 = ISO_B0;
public static final MediaType B1 = ISO_B1;
public static final MediaType B2 = ISO_B2;
public static final MediaType B3 = ISO_B3;
public static final MediaType B4 = ISO_B4;
public static final MediaType B5 = ISO_B5;
public static final MediaType B6 = ISO_B6;
public static final MediaType B7 = ISO_B7;
public static final MediaType B8 = ISO_B8;
public static final MediaType B9 = ISO_B9;
public static final MediaType B10 = ISO_B10;
public static final MediaType ISO_B4_ENVELOPE = ISO_B4;
public static final MediaType ISO_B5_ENVELOPE = ISO_B5;
public static final MediaType ISO_C0_ENVELOPE = ISO_C0;
public static final MediaType ISO_C1_ENVELOPE = ISO_C1;
public static final MediaType ISO_C2_ENVELOPE = ISO_C2;
public static final MediaType ISO_C3_ENVELOPE = ISO_C3;
public static final MediaType ISO_C4_ENVELOPE = ISO_C4;
public static final MediaType ISO_C5_ENVELOPE = ISO_C5;
public static final MediaType ISO_C6_ENVELOPE = ISO_C6;
public static final MediaType ISO_C7_ENVELOPE = ISO_C7;
public static final MediaType ISO_C8_ENVELOPE = ISO_C8;
public static final MediaType ISO_C9_ENVELOPE = ISO_C9;
public static final MediaType ISO_C10_ENVELOPE = ISO_C10;
public static final MediaType C0 = ISO_C0;
public static final MediaType C1 = ISO_C1;
public static final MediaType C2 = ISO_C2;
public static final MediaType C3 = ISO_C3;
public static final MediaType C4 = ISO_C4;
public static final MediaType C5 = ISO_C5;
public static final MediaType C6 = ISO_C6;
public static final MediaType C7 = ISO_C7;
public static final MediaType C8 = ISO_C8;
public static final MediaType C9 = ISO_C9;
public static final MediaType C10 = ISO_C10;
public static final MediaType ISO_DESIGNATED_LONG_ENVELOPE
= ISO_DESIGNATED_LONG;
public static final MediaType STATEMENT = INVOICE;
public static final MediaType TABLOID = LEDGER;
public static final MediaType LETTER = NA_LETTER;
public static final MediaType NOTE = NA_LETTER;
public static final MediaType LEGAL = NA_LEGAL;
public static final MediaType ENV_10X15 = NA_10X15_ENVELOPE;
public static final MediaType ENV_10X14 = NA_10X14_ENVELOPE;
public static final MediaType ENV_10X13 = NA_10X13_ENVELOPE;
public static final MediaType ENV_9X12 = NA_9X12_ENVELOPE;
public static final MediaType ENV_9X11 = NA_9X11_ENVELOPE;
public static final MediaType ENV_7X9 = NA_7X9_ENVELOPE;
public static final MediaType ENV_6X9 = NA_6X9_ENVELOPE;
public static final MediaType ENV_9 = NA_NUMBER_9_ENVELOPE;
public static final MediaType ENV_10 = NA_NUMBER_10_ENVELOPE;
public static final MediaType ENV_11 = NA_NUMBER_11_ENVELOPE;
public static final MediaType ENV_12 = NA_NUMBER_12_ENVELOPE;
public static final MediaType ENV_14 = NA_NUMBER_14_ENVELOPE;
public static final MediaType ENV_INVITE = INVITE_ENVELOPE;
public static final MediaType ENV_ITALY = ITALY_ENVELOPE;
public static final MediaType ENV_MONARCH = MONARCH_ENVELOPE;
public static final MediaType ENV_PERSONAL = PERSONAL_ENVELOPE;
public static final MediaType INVITE = INVITE_ENVELOPE;
public static final MediaType ITALY = ITALY_ENVELOPE;
public static final MediaType MONARCH = MONARCH_ENVELOPE;
public static final MediaType PERSONAL = PERSONAL_ENVELOPE;
private MediaType(int i, String n){
super();
name = n;
}
private MediaType(){
this(4, "ISO_A4"); //$NON-NLS-1$
}
}
public static final class OrientationRequestedType {
private final String name;
public static final OrientationRequestedType PORTRAIT
= new OrientationRequestedType(0, "PORTRAIT"); //$NON-NLS-1$
public static final OrientationRequestedType LANDSCAPE
= new OrientationRequestedType(1, "LANDSCAPE"); //$NON-NLS-1$
private OrientationRequestedType(int i, String n){
super();
name = n;
}
private OrientationRequestedType(){
this(0, "PORTRAIT"); //$NON-NLS-1$
}
}
public static final class OriginType {
private final String name;
public static final OriginType PHYSICAL
= new OriginType(0, "PHYSICAL"); //$NON-NLS-1$
public static final OriginType PRINTABLE
= new OriginType(1, "PRINTABLE"); //$NON-NLS-1$
private OriginType(int i, String n){
super();
name = n;
}
private OriginType(){
this(0, "PHYSICAL"); //$NON-NLS-1$
}
}
public static final class PrintQualityType {
private final String name;
public static final PrintQualityType HIGH = new PrintQualityType(5,
"HIGH"); //$NON-NLS-1$
public static final PrintQualityType NORMAL = new PrintQualityType(4,
"NORMAL"); //$NON-NLS-1$
public static final PrintQualityType DRAFT = new PrintQualityType(2,
"DRAFT"); //$NON-NLS-1$
private PrintQualityType(int i, String n){
name = n;
}
private PrintQualityType(){
this(4, "NORMAL"); //$NON-NLS-1$
}
}
/*--------------- end of section of the nested classes ------------------*/
public PageAttributes() {
setColor(ColorType.MONOCHROME);
setMediaToDefault();
setOrientationRequestedToDefault();
setOrigin(OriginType.PHYSICAL);
setPrintQualityToDefault();
setPrinterResolutionToDefault();
}
public PageAttributes(PageAttributes.ColorType color,
PageAttributes.MediaType media,
PageAttributes.OrientationRequestedType orientationRequested,
PageAttributes.OriginType origin,
PageAttributes.PrintQualityType printQuality,
int[] printerResolution) {
setColor(color);
setMedia(media);
setOrientationRequested(orientationRequested);
setOrigin(origin);
setPrintQuality(printQuality);
setPrinterResolution(printerResolution);
}
public PageAttributes(PageAttributes pageAttributes) {
set(pageAttributes);
}
@Override
public Object clone() {
PageAttributes pa = new PageAttributes(this);
return pa;
}
@Override
public boolean equals(Object obj) {
PageAttributes pa;
if (!(obj instanceof PageAttributes)) {
return false;
}
pa = (PageAttributes) obj;
if (color != pa.color) {
return false;
}
if (media != pa.media) {
return false;
}
if (orientationRequested != pa.orientationRequested) {
return false;
}
if (origin != pa.origin) {
return false;
}
if (printQuality != pa.printQuality) {
return false;
}
if (origin != pa.origin) {
return false;
}
if (!(printerResolution[0] == pa.printerResolution[0]
&& printerResolution[1] == pa.printerResolution[1]
&& printerResolution[2] == pa.printerResolution[2])) {
return false;
}
return true;
}
@Override
public String toString(){
/* The format is based on 1.5 release behavior
* which can be revealed by the following code:
* System.out.println(new PageAttributes());
*/
String s;
s = "color=" + getColor().name + ",media=" + getMedia().name //$NON-NLS-1$ //$NON-NLS-2$
+ ",orientation-requested=" + getOrientationRequested().name //$NON-NLS-1$
+ ",origin=" + getOrigin().name //$NON-NLS-1$
+ ",print-quality=" + getPrintQuality().name //$NON-NLS-1$
+ ",printer-resolution=" + printerResolution[0] + "x" //$NON-NLS-1$ //$NON-NLS-2$
+ printerResolution[1] + (printerResolution[2]==3?"dpi":"dpcm"); //$NON-NLS-1$ //$NON-NLS-2$
return s;
}
@Override
public int hashCode() {
int hash = this.toString().hashCode();
return hash;
}
public void set(PageAttributes obj) {
color = obj.color;
media = obj.media;
orientationRequested = obj.orientationRequested;
origin = obj.origin;
printQuality = obj.printQuality;
printerResolution = obj.printerResolution;
}
public void setColor(PageAttributes.ColorType color) {
if (color == null) {
// awt.11C=Invalid value for color
throw new IllegalArgumentException(Messages.getString("awt.11C")); //$NON-NLS-1$
}
this.color = color;
}
public PageAttributes.ColorType getColor() {
return color;
}
public void setMedia(PageAttributes.MediaType media) {
if(media == null) {
// awt.116=Invalid value for media
throw new IllegalArgumentException(Messages.getString("awt.116")); //$NON-NLS-1$
}
this.media = media;
}
public PageAttributes.MediaType getMedia() {
return media;
}
public void setOrientationRequested(
PageAttributes.OrientationRequestedType orientationRequested) {
if (orientationRequested == null) {
// awt.117=Invalid value for orientationRequested
throw new IllegalArgumentException(Messages.getString("awt.117")); //$NON-NLS-1$
}
this.orientationRequested = orientationRequested;
}
public void setOrientationRequested(int i_orientationRequested) {
if(i_orientationRequested == 3) {
setOrientationRequested(OrientationRequestedType.PORTRAIT);
return;
}
if(i_orientationRequested == 4) {
setOrientationRequested(OrientationRequestedType.LANDSCAPE);
return;
}
// awt.117=Invalid value for orientationRequested
throw new IllegalArgumentException(Messages.getString("awt.117")); //$NON-NLS-1$
}
public PageAttributes.OrientationRequestedType getOrientationRequested() {
return orientationRequested;
}
public void setOrigin(PageAttributes.OriginType origin) {
if (origin == null) {
// awt.119=Invalid value for origin
throw new IllegalArgumentException(Messages.getString("awt.119")); //$NON-NLS-1$
}
this.origin = origin;
}
public PageAttributes.OriginType getOrigin() {
return origin;
}
public void setPrintQuality(PageAttributes.PrintQualityType printQuality) {
if (printQuality == null) {
// awt.11A=Invalid value for printQuality
throw new IllegalArgumentException(Messages.getString("awt.11A")); //$NON-NLS-1$
}
this.printQuality = printQuality;
}
public void setPrintQuality(int iprintQuality) {
if (iprintQuality == 3) {
setPrintQuality(PrintQualityType.DRAFT);
return;
}
if (iprintQuality == 4) {
setPrintQuality(PrintQualityType.NORMAL);
return;
}
if (iprintQuality == 5) {
setPrintQuality(PrintQualityType.HIGH);
return;
}
// awt.11A=Invalid value for printQuality
throw new IllegalArgumentException(Messages.getString("awt.11A")); //$NON-NLS-1$
}
public PageAttributes.PrintQualityType getPrintQuality() {
return printQuality;
}
public void setPrinterResolution(int[] aprinterResolution) {
if (aprinterResolution == null
|| aprinterResolution.length != 3
|| aprinterResolution[0] <= 0
|| aprinterResolution[1] <= 0
|| (aprinterResolution[2] != 3 && aprinterResolution[2] != 4)) {
// awt.11B=Invalid value for printerResolution[]
throw new IllegalArgumentException(Messages.getString("awt.11B")); //$NON-NLS-1$
}
printerResolution = new int[3];
printerResolution[0] = aprinterResolution[0];
printerResolution[1] = aprinterResolution[1];
printerResolution[2] = aprinterResolution[2];
}
public void setPrinterResolution(int iprinterResolution) {
if (iprinterResolution <= 0) {
// awt.118=Invalid value for printerResolution
throw new IllegalArgumentException(Messages.getString("awt.118")); //$NON-NLS-1$
}
printerResolution = new int[3];
printerResolution[0] = iprinterResolution;
printerResolution[1] = iprinterResolution;
printerResolution[2] = 3;
}
public int[] getPrinterResolution() {
return printerResolution;
}
public void setMediaToDefault() {
Locale loc = Locale.getDefault();
if (loc.equals(Locale.CANADA) || loc.equals(Locale.US)) {
setMedia(MediaType.NA_LETTER);
return;
}
setMedia(MediaType.ISO_A4);
return;
}
public void setOrientationRequestedToDefault() {
setOrientationRequested(OrientationRequestedType.PORTRAIT);
return;
}
public void setPrintQualityToDefault() {
setPrintQuality(PrintQualityType.NORMAL);
return;
}
public void setPrinterResolutionToDefault() {
setPrinterResolution(72);
return;
}
}
| apache-2.0 |
Mahoney/wiremock | src/main/java/com/github/tomakehurst/wiremock/admin/tasks/GetAllRequestsTask.java | 2436 | /*
* Copyright (C) 2011 Thomas Akehurst
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.tomakehurst.wiremock.admin.tasks;
import com.github.tomakehurst.wiremock.admin.AdminTask;
import com.github.tomakehurst.wiremock.admin.LimitAndSinceDatePaginator;
import com.github.tomakehurst.wiremock.admin.model.GetServeEventsResult;
import com.github.tomakehurst.wiremock.admin.model.PathParams;
import com.github.tomakehurst.wiremock.common.InvalidInputException;
import com.github.tomakehurst.wiremock.common.Json;
import com.github.tomakehurst.wiremock.core.Admin;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import static com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder.jsonResponse;
import static com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder.responseDefinition;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_OK;
public class GetAllRequestsTask implements AdminTask {
@Override
public ResponseDefinition execute(Admin admin, Request request, PathParams pathParams) {
GetServeEventsResult serveEventsResult = admin.getServeEvents();
LimitAndSinceDatePaginator paginator;
try {
paginator = LimitAndSinceDatePaginator.fromRequest(
serveEventsResult.getRequests(),
request
);
} catch (InvalidInputException e) {
return jsonResponse(e.getErrors(), HTTP_BAD_REQUEST);
}
GetServeEventsResult result = new GetServeEventsResult(paginator,
serveEventsResult.isRequestJournalDisabled()
);
return responseDefinition()
.withStatus(HTTP_OK)
.withBody(Json.write(result))
.withHeader("Content-Type", "application/json")
.build();
}
}
| apache-2.0 |
pubudu538/carbon-apimgt | components/apimgt/org.wso2.carbon.apimgt.impl/src/test/java/org/wso2/carbon/apimgt/impl/AbstractAPIManagerWrapperExtended.java | 3227 | /*
* Copyright (c) 2017, 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.carbon.apimgt.impl;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.Identifier;
import org.wso2.carbon.governance.api.generic.GenericArtifactManager;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.ResourceImpl;
import org.wso2.carbon.registry.core.jdbc.dataobjects.ResourceDO;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.tenant.TenantManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class AbstractAPIManagerWrapperExtended extends AbstractAPIManagerWrapper{
public AbstractAPIManagerWrapperExtended(GenericArtifactManager genericArtifactManager,
RegistryService registryService, Registry registry, TenantManager tenantManager)
throws APIManagementException {
super(genericArtifactManager, registryService, registry, tenantManager);
}
@Override
protected String getTenantDomain(Identifier identifier) {
return "abc.com";
}
@Override
public Resource getCustomMediationResourceFromUuid(String mediationPolicyId){
return new ResourceImpl("/apimgt/apis", new ResourceDO());
}
@Override
public Resource getApiSpecificMediationResourceFromUuid(String uuid, String resourcePath){
return new ResourceImpl("/apimgt/apis", new ResourceDO());
}
public Map<String, Object> searchPaginatedAPIs(Registry registry, String searchQuery, int start, int end,
boolean limitAttributes) throws APIManagementException {
if (searchQuery.equalsIgnoreCase("api_meta.secured=*true*")) {
return new HashMap<String, Object>() {{
put("apis", new ArrayList() {{
add(new API(new APIIdentifier("admin", "sxy", "1.0.0")));
}});
put("length", 1);
}};
} else if (searchQuery.equalsIgnoreCase("name=*test*&api_meta.secured=*true*")) {
return new HashMap<String, Object>() {{
put("apis", new ArrayList() {{
add(new API(new APIIdentifier("admin", "sxy12", "1.0.0")));
}});
put("length", 1);
}};
} else {
return super.searchPaginatedAPIs(registry, searchQuery, start, end, limitAttributes);
}
}
}
| apache-2.0 |
cowthan/JavaAyo | src-nutz/org/nutz/dao/impl/DaoRunner.java | 858 | package org.nutz.dao.impl;
import javax.sql.DataSource;
import org.nutz.dao.ConnCallback;
/**
* 这个接口是一个扩展点。通过修改这个接口,你可以为 Dao 的默认实现类 NutDao 彻底定制事务行为
* <p>
* 你需要面对的只是
* <ul>
* <li>DataSource - 数据源
* <li>ConnCallback - 数据操作细节
* </ul>
* 你的事务行为据此来扩展。 默认的,DefaultDaoRunner 类为你提供了 Nutz 的事务模板解决方案
* <p>
* 如果你不喜欢事务模板的方式,你可以实现一个新的 DaoRunner 并通过 NutDao 的 setRunner 方法 设置进来,你的 Dao
* 的数据执行行为将焕然一新。
*
* @author zozoh(zozohtnt@gmail.com)
*
* @see org.nutz.dao.impl.sql.run.NutDaoRunner
*/
public interface DaoRunner {
void run(DataSource dataSource, ConnCallback callback);
}
| apache-2.0 |
quarkusio/quarkus | integration-tests/injectmock/src/main/java/io/quarkus/it/mockbean/DummyService1.java | 172 | package io.quarkus.it.mockbean;
public class DummyService1 implements DummyService {
@Override
public String returnDummyValue() {
return "first";
}
}
| apache-2.0 |
oliversalmon/sandpit | domain/src/main/java/com/example/datagrid/projects/domain/Venue.java | 2099 | package com.example.datagrid.projects.domain;
import com.example.datagrid.projects.domain.enums.VenueTypeEnum;
import com.google.gson.Gson;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.Portable;
import com.hazelcast.nio.serialization.PortableReader;
import com.hazelcast.nio.serialization.PortableWriter;
import java.io.IOException;
/**
* Created by oliverbuckley-salmon on 10/08/2016.
*/
public class Venue implements Portable{
public static final int ID = 2;
private String venueId
, name;
private VenueTypeEnum venueType;
public Venue(){
}
public Venue(String venueId, String name, VenueTypeEnum venueType) {
this.venueId = venueId;
this.name = name;
this.venueType = venueType;
}
public String getVenueId() {
return venueId;
}
public void setVenueId(String venueId) {
this.venueId = venueId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public VenueTypeEnum getVenueType() {
return venueType;
}
public void setVenueType(VenueTypeEnum venueType) {
this.venueType = venueType;
}
public int getFactoryId() {
return 1;
}
public int getClassId() {
return ID;
}
public void writePortable(PortableWriter out) throws IOException {
out.writeUTF("venueId", venueId);
out.writeUTF("name", name);
ObjectDataOutput rawDataOutput = out.getRawDataOutput();
rawDataOutput.writeObject(venueType);
}
public void readPortable(PortableReader in) throws IOException {
this.venueId = in.readUTF("venueId");
this.name = in.readUTF("name");
ObjectDataInput rawDataInput = in.getRawDataInput();
this.venueType = rawDataInput.readObject();
}
public String toJSON(){
Gson gson = new Gson();
//String json = gson.toJson(obj);
return gson.toJson(this);
}
}
| apache-2.0 |
lolnetnz/Equity | src/main/java/io/github/lxgaming/equity/util/PacketUtil.java | 6307 | /*
* Copyright 2017 Alex Thomson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.lxgaming.equity.util;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.github.lxgaming.equity.Equity;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
public class PacketUtil {
public static ByteBuf getByteBuf(ByteBufAllocator byteBufAllocator, ByteBuf byteBuf, int length) {
if (byteBuf.hasMemoryAddress()) {
return byteBuf.readRetainedSlice(length);
}
return byteBufAllocator.directBuffer(length, length).writeBytes(byteBuf, length);
}
public static boolean safeRelease(ByteBuf byteBuf) {
try {
if (byteBuf.refCnt() > 0) {
byteBuf.release(byteBuf.refCnt());
}
return true;
} catch (RuntimeException ex) {
Equity.getInstance().getLogger().error("Encountered an error processing PacketUtil::safeRelease", ex);
return false;
}
}
public static void writeString(ByteBuf byteBuf, String string) {
if (string.length() > Short.MAX_VALUE) {
throw new UnsupportedOperationException("Cannot send string longer than Short.MAX_VALUE (got " + string.length() + " characters)");
}
byte[] bytes = string.getBytes(StandardCharsets.UTF_8);
writeVarInt(byteBuf, bytes.length);
byteBuf.writeBytes(bytes);
}
public static String readString(ByteBuf byteBuf) {
int length = readVarInt(byteBuf);
if (length > Short.MAX_VALUE) {
throw new UnsupportedOperationException("Cannot receive string longer than Short.MAX_VALUE (got " + length + " characters)");
}
byte[] bytes = new byte[length];
byteBuf.readBytes(bytes);
return new String(bytes, StandardCharsets.UTF_8);
}
public static void writeArray(ByteBuf byteBuf, byte[] bytes) {
if (bytes.length > Short.MAX_VALUE) {
throw new UnsupportedOperationException("Cannot send byte array longer than Short.MAX_VALUE (got " + bytes.length + " bytes)");
}
writeVarInt(byteBuf, bytes.length);
byteBuf.writeBytes(bytes);
}
public static byte[] toArray(ByteBuf byteBuf) {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
return bytes;
}
public static byte[] readArray(ByteBuf byteBuf) {
return readArray(byteBuf, byteBuf.readableBytes());
}
public static byte[] readArray(ByteBuf byteBuf, int limit) {
int length = readVarInt(byteBuf);
if (length > limit) {
throw new UnsupportedOperationException("Cannot receive byte array longer than " + limit + " (got " + length + " bytes)");
}
byte[] bytes = new byte[length];
byteBuf.readBytes(bytes);
return bytes;
}
public static void writeStringArray(ByteBuf byteBuf, List<String> list) {
writeVarInt(byteBuf, list.size());
for (String string : list) {
writeString(byteBuf, string);
}
}
public static List<String> readStringArray(ByteBuf byteBuf) {
int length = readVarInt(byteBuf);
List<String> list = Toolbox.newArrayList();
for (int index = 0; index < length; index++) {
list.add(readString(byteBuf));
}
return list;
}
public static int getVarIntSize(ByteBuf byteBuf, int input) {
for (int index = 1; index < 5; ++index) {
if ((input & -1 << index * 7) == 0) {
return index;
}
}
return 5;
}
public static int readVarInt(ByteBuf byteBuf) {
return readVarInt(byteBuf, 5);
}
public static int readVarInt(ByteBuf byteBuf, int maxBytes) {
int result = 0;
int bytesRead = 0;
while (byteBuf.readableBytes() != 0) {
byte read = byteBuf.readByte();
result |= (read & 0x7F) << (bytesRead++ * 7);
if (bytesRead > maxBytes) {
throw new RuntimeException("VarInt too big");
}
if ((read & 0x80) != 0x80) {
break;
}
}
return result;
}
public static void writeVarInt(ByteBuf byteBuf, int value) {
while (byteBuf.isWritable()) {
int part = value & 0x7F;
value >>>= 7;
if (value != 0) {
part |= 0x80;
}
byteBuf.writeByte(part);
if (value == 0) {
break;
}
}
}
public static int readVarShort(ByteBuf byteBuf) {
int low = byteBuf.readUnsignedShort();
int high = 0;
if ((low & 0x8000) != 0) {
low = low & 0x7FFF;
high = byteBuf.readUnsignedByte();
}
return ((high & 0xFF) << 15) | low;
}
public static void writeVarShort(ByteBuf byteBuf, int value) {
int low = value & 0x7FFF;
int high = (value & 0x7F8000) >> 15;
if (high != 0) {
low = low | 0x8000;
}
byteBuf.writeShort(low);
if (high != 0) {
byteBuf.writeByte(high);
}
}
public static UUID readUUID(ByteBuf byteBuf) {
return new UUID(byteBuf.readLong(), byteBuf.readLong());
}
public static void writeUUID(ByteBuf byteBuf, UUID uuid) {
byteBuf.writeLong(uuid.getMostSignificantBits());
byteBuf.writeLong(uuid.getLeastSignificantBits());
}
} | apache-2.0 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/CNN2DFormat.java | 1058 | package org.deeplearning4j.nn.conf;
/**
* CNN2DFormat defines the format of the activations (including input images) in to and out of all 2D convolution layers in
* Deeplearning4j. Default value is NCHW.<br>
* <br>
* NCHW = "channels first" - arrays of shape [minibatch, channels, height, width]<br>
* NHWC = "channels last" - arrays of shape [minibatch, height, width, channels]<br>
*
* @author Alex Black
*/
public enum CNN2DFormat implements DataFormat {
NCHW,
NHWC;
/**
* Returns a string that explains the dimensions:<br>
* NCHW -> returns "[minibatch, channels, height, width]"<br>
* NHWC -> returns "[minibatch, height, width, channels]"
*/
public String dimensionNames(){
switch (this){
case NCHW:
return "[minibatch, channels, height, width]";
case NHWC:
return "[minibatch, height, width, channels]";
default:
throw new IllegalStateException("Unknown enum: " + this); //Should never happen
}
}
}
| apache-2.0 |
jmptrader/Strata | examples/src/test/java/com/opengamma/strata/examples/finance/credit/CdsPricingCompany01TminusOneTests.java | 2696 | /**
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.examples.finance.credit;
import static com.opengamma.strata.examples.finance.credit.harness.TestHarness.TradeFactory.withCompany01;
import java.time.LocalDate;
import org.testng.annotations.Test;
import com.opengamma.strata.examples.finance.credit.harness.TestHarness;
import com.opengamma.strata.product.common.BuySell;
@Test
public class CdsPricingCompany01TminusOneTests {
final LocalDate valuationDate = LocalDate.of(2014, 10, 16);
final LocalDate cashSettleDate = LocalDate.of(2014, 10, 20);
final double feeAmount = -3_694_117.73D;
final BuySell buySell = BuySell.SELL;
private TestHarness.TradeFactory onTrade() {
return withCompany01(buySell, feeAmount, cashSettleDate);
}
public void test_pvs_on_company_01_t_minus_1() {
onTrade().pvShouldBe(7_388_093.704033349).on(valuationDate);
}
public void test_par_rate_on_company_01_t_minus_1() {
onTrade().parRateShouldBe(0.002800000823400466).on(valuationDate);
}
public void test_recovery01_on_company_01_minus_1() {
onTrade().recovery01ShouldBe(-7.254387963563204).on(valuationDate);
}
public void test_jump_to_default_on_company_01_minus_1() {
onTrade().jumpToDefaultShouldBe(-67_388_093.70403334).on(valuationDate);
}
public void test_ir01_parallel_par_on_company_01_t_minus_1() {
onTrade().ir01ParallelParShouldBe(-972.8116886373609).on(valuationDate);
}
public void test_ir01_bucketed_par_on_company_01_t_minus_1() {
onTrade()
.ir01BucketedParShouldBe(
-8.2257817937061190,
-3.1341894399374723,
-1.5775036029517650,
-12.7210429105907680,
-52.7185466177761550,
-138.1065479721874000,
-206.8782773185521400,
-275.0521688470617000,
-257.4313263930380300,
-17.1471436154097320,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0)
.on(valuationDate);
}
public void test_cs01_parallel_par_on_company_01_t_minus_1() {
onTrade().cs01ParallelParShouldBe(-51873.837977122515).on(valuationDate);
}
public void test_cs01_bucketed_par_on_company_01_t_minus_1() {
onTrade()
.cs01BucketedParShouldBe(
-46.6094936728477500,
-103.8638124940916900,
-252.1060386206954700,
-364.7911099912599000,
-484.2151752971113000,
-50640.1112342365100000)
.on(valuationDate);
}
}
| apache-2.0 |
pjworkspace/wscs | wscs-web-admin/src/main/java/com/xxx/market/web/core/render/chart/funshion/PieChart.java | 3018 | /**
* Copyright (c) 2011-2013, kidzhou 周磊 (zhouleib1412@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xxx.market.web.core.render.chart.funshion;
import java.util.List;
import com.xxx.market.web.core.render.KeyLabel;
public class PieChart {
/**
* 标题
*/
private String caption;
/**
* x坐标说明
*/
private String xAxisName;
/**
* y坐标说明
*/
private String yAxisName;
/**
* 数据源
*/
private List<KeyLabel> list;
/**
* FLASH位置
*/
private String charUrl;
/**
* FLASH宽
*/
private String charWidth;
/**
* FLASH高
*/
private String charHigh;
/**
* freemaker模板路径
*/
private String fltPath;
private String mapRoot;
public String getCharWidth() {
return charWidth;
}
public void setCharWidth(String charWidth) {
this.charWidth = charWidth;
}
public String getCharHigh() {
return charHigh;
}
public void setCharHigh(String charHigh) {
this.charHigh = charHigh;
}
public String getxAxisName() {
return xAxisName;
}
public void setxAxisName(String xAxisName) {
this.xAxisName = xAxisName;
}
public String getyAxisName() {
return yAxisName;
}
public void setyAxisName(String yAxisName) {
this.yAxisName = yAxisName;
}
public String getCharUrl() {
return charUrl;
}
public void setCharUrl(String charUrl) {
this.charUrl = charUrl;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getXAxisName() {
return xAxisName;
}
public void setXAxisName(String axisName) {
xAxisName = axisName;
}
public String getYAxisName() {
return yAxisName;
}
public void setYAxisName(String axisName) {
yAxisName = axisName;
}
public String getFltPath() {
return fltPath;
}
public void setFltPath(String fltPath) {
this.fltPath = fltPath;
}
public String getMapRoot() {
return mapRoot;
}
public void setMapRoot(String mapRoot) {
this.mapRoot = mapRoot;
}
public List<KeyLabel> getList() {
return list;
}
public void setList(List<KeyLabel> list) {
this.list = list;
}
}
| apache-2.0 |
projectbuendia/client | third_party/odkcollect/src/main/java/org/odk/collect/android/activities/FormEntryActivity.java | 111672 | /*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.provider.MediaStore.Images;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.exception.JavaRosaException;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.listeners.FormSavedListener;
import org.odk.collect.android.listeners.SavePointListener;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.logic.FormController.FailedConstraint;
import org.odk.collect.android.logic.FormTraverser;
import org.odk.collect.android.logic.FormVisitor;
import org.odk.collect.android.model.Patient;
import org.odk.collect.android.model.Preset;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.FormsProviderAPI.FormsColumns;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.tasks.FormLoaderTask;
import org.odk.collect.android.tasks.SavePointTask;
import org.odk.collect.android.tasks.SaveResult;
import org.odk.collect.android.tasks.SaveToDiskTask;
import org.odk.collect.android.utilities.CompatibilityUtils;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import org.odk.collect.android.utilities.Utils;
import org.odk.collect.android.views.ODKView;
import org.odk.collect.android.widgets.QuestionWidget;
import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;
import static org.odk.collect.android.utilities.Utils.eq;
//import android.view.GestureDetector;
//import android.view.GestureDetector.OnGestureListener;
/**
* FormEntryActivity is responsible for displaying questions, animating
* transitions between questions, and allowing the user to enter data.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Thomas Smyth, Sassafras Tech Collective (tom@sassafrastech.com; constraint behavior option)
*/
public class FormEntryActivity
extends Activity implements FormLoaderListener, FormSavedListener, SavePointListener {
private static final String TAG = FormEntryActivity.class.getName();
// save with every swipe forward or back. Timings indicate this takes .25
// seconds.
// if it ever becomes an issue, this value can be changed to save every n'th
// screen.
// private static final int SAVEPOINT_INTERVAL = 1;
// Defines for FormEntryActivity
private static final boolean EXIT = true;
private static final boolean DO_NOT_EXIT = false;
private static final boolean EVALUATE_CONSTRAINTS = true;
private static final boolean DO_NOT_EVALUATE_CONSTRAINTS = false;
// Request codes for returning data from specified intent.
public static final int IMAGE_CAPTURE = 1;
public static final int BARCODE_CAPTURE = 2;
public static final int AUDIO_CAPTURE = 3;
public static final int VIDEO_CAPTURE = 4;
public static final int LOCATION_CAPTURE = 5;
// public static final int HIERARCHY_ACTIVITY = 6;
public static final int IMAGE_CHOOSER = 7;
public static final int AUDIO_CHOOSER = 8;
public static final int VIDEO_CHOOSER = 9;
public static final int EX_STRING_CAPTURE = 10;
public static final int EX_INT_CAPTURE = 11;
public static final int EX_DECIMAL_CAPTURE = 12;
public static final int DRAW_IMAGE = 13;
public static final int SIGNATURE_CAPTURE = 14;
public static final int ANNOTATE_IMAGE = 15;
public static final int ALIGNED_IMAGE = 16;
public static final int BEARING_CAPTURE = 17;
public static final int EX_GROUP_CAPTURE = 18;
// Extra returned from gp activity
public static final String LOCATION_RESULT = "LOCATION_RESULT";
public static final String BEARING_RESULT = "BEARING_RESULT";
public static final String KEY_INSTANCES = "instances";
public static final String KEY_SUCCESS = "success";
public static final String KEY_ERROR = "error";
// Identifies the gp of the form used to launch form entry
public static final String KEY_FORMPATH = "formpath";
// Identifies whether this is a new form, or reloading a form after a screen
// rotation (or similar)
private static final String NEWFORM = "newform";
// these are only processed if we shut down and are restoring after an
// external intent fires
public static final String KEY_INSTANCEPATH = "instancepath";
public static final String KEY_XPATH = "xpath";
public static final String KEY_XPATH_WAITING_FOR_DATA = "xpathwaiting";
// Tracks whether we are autosaving
public static final String KEY_AUTO_SAVED = "autosaved";
// private static final int MENU_LANGUAGES = Menu.FIRST;
// private static final int MENU_HIERARCHY_VIEW = Menu.FIRST + 1;
// private static final int MENU_CANCEL = Menu.FIRST;
// private static final int MENU_SAVE = MENU_CANCEL + 1;
// private static final int MENU_PREFERENCES = Menu.FIRST + 3;
private static final int PROGRESS_DIALOG = 1;
private static final int SAVING_DIALOG = 2;
// Alert dialog styling.
private static final float ALERT_DIALOG_TEXT_SIZE = 32.0f;
private static final float ALERT_DIALOG_TITLE_TEXT_SIZE = 34.0f;
private static final int ALERT_DIALOG_PADDING = 32;
private boolean mAutoSaved;
// Random ID
private static final int DELETE_REPEAT = 654321;
private String mFormPath;
// private GestureDetector mGestureDetector;
//
// private Animation mInAnimation;
// private Animation mOutAnimation;
// private View mStaleView = null;
private ScrollView mScrollView;
private LinearLayout mQuestionHolder;
private View mCurrentView;
private ImageButton mUpButton;
private ImageButton mDownButton;
private Button mCancelButton;
private Button mDoneButton;
private AlertDialog mAlertDialog;
private ProgressDialog mProgressDialog;
private String mErrorMessage;
// used to limit forward/backward swipes to one per question
// private boolean mBeenSwiped = false;
private final Object saveDialogLock = new Object();
private int viewCount = 0;
private FormLoaderTask mFormLoaderTask;
private SaveToDiskTask mSaveToDiskTask;
private String stepMessage = "";
private ODKView mTargetView;
private Map<FormIndex, IAnswerData> mOriginalAnswerData;
private static final double MAX_SCROLL_FRACTION = 0.9; // fraction of mScrollView height
private View mBottomPaddingView;
// ScrollY values that we try to scroll to when paging up and down.
private List<Integer> mPageBreaks = new ArrayList<>();
private enum ScrollDirection {UP, DOWN}
public static Locale locale;
// enum AnimationType {
// LEFT, RIGHT, FADE
// }
// private SharedPreferences mAdminPreferences;
@Override protected void attachBaseContext(Context base) {
super.attachBaseContext(applyLocaleSetting(base));
}
public Context applyLocaleSetting(Context base) {
Locale.setDefault(locale);
Resources resources = base.getResources();
Configuration config = resources.getConfiguration();
config.setLocale(locale);
config.setLayoutDirection(locale);
return base.createConfigurationContext(config);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// must be at the beginning of any activity that can be called from an
// external intent
try {
Collect.getInstance().createODKDirs();
} catch (RuntimeException e) {
createErrorDialog(e.getMessage(), EXIT);
return;
}
setContentView(R.layout.form_entry);
setTitle(getString(R.string.title_loading_form));
// Turn the action bar icon into a "back" arrow that goes back in the activity stack.
getActionBar().setIcon(R.drawable.ic_back_36dp);
getActionBar().setDisplayHomeAsUpEnabled(true);
//
// setTitle(getString(R.string.app_name) + " > "
// + getString(R.string.loading_form));
mErrorMessage = null;
// mBeenSwiped = false;
mAlertDialog = new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(getString(R.string.title_discard_observations))
//.setMessage(R.string.observations_are_you_sure)
.setPositiveButton(
R.string.yes,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
finish();
}
}
)
.setNegativeButton(R.string.no, null)
.create();
mCurrentView = null;
// mInAnimation = null;
// mOutAnimation = null;
// mGestureDetector = new GestureDetector(this, this);
mScrollView = (ScrollView) findViewById(R.id.question_holder_scroller);
mQuestionHolder = (LinearLayout) findViewById(R.id.questionholder);
findViewById(R.id.button_up).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
scrollPage(ScrollDirection.UP);
}
});
findViewById(R.id.button_down).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
scrollPage(ScrollDirection.DOWN);
}
});
mCancelButton = (Button) findViewById(R.id.form_entry_button_cancel);
mCancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (allContentsUnchanged()) {
finish();
} else {
showAlertDialog();
}
}
});
mDoneButton = (Button) findViewById(R.id.form_entry_button_done);
mDoneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onOptionsItemSelected",
"MENU_SAVE");
InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(findViewById(android.R.id.content).getWindowToken(), 0);
saveDataToDisk(EXIT, true /*complete*/, null);
}
});
// get admin preference settings
// mAdminPreferences = getSharedPreferences(
// AdminPreferencesActivity.ADMIN_PREFERENCES, 0);
String startingXPath = null;
String waitingXPath = null;
String instancePath = null;
Boolean newForm = true;
mAutoSaved = false;
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(KEY_FORMPATH)) {
mFormPath = savedInstanceState.getString(KEY_FORMPATH);
}
if (savedInstanceState.containsKey(KEY_INSTANCEPATH)) {
instancePath = savedInstanceState.getString(KEY_INSTANCEPATH);
}
if (savedInstanceState.containsKey(KEY_XPATH)) {
startingXPath = savedInstanceState.getString(KEY_XPATH);
Log.i(TAG, "startingXPath is: " + startingXPath);
}
if (savedInstanceState.containsKey(KEY_XPATH_WAITING_FOR_DATA)) {
waitingXPath = savedInstanceState
.getString(KEY_XPATH_WAITING_FOR_DATA);
Log.i(TAG, "waitingXPath is: " + waitingXPath);
}
if (savedInstanceState.containsKey(NEWFORM)) {
newForm = savedInstanceState.getBoolean(NEWFORM, true);
}
if (savedInstanceState.containsKey(KEY_ERROR)) {
mErrorMessage = savedInstanceState.getString(KEY_ERROR);
}
if (savedInstanceState.containsKey(KEY_AUTO_SAVED)) {
mAutoSaved = savedInstanceState.getBoolean(KEY_AUTO_SAVED);
}
}
// If a parse error message is showing then nothing else is loaded
// Dialogs mid form just disappear on rotation.
if (mErrorMessage != null) {
createErrorDialog(mErrorMessage, EXIT);
return;
}
// Check to see if this is a screen flip or a new form load.
Object data = getLastNonConfigurationInstance();
if (data instanceof FormLoaderTask) {
mFormLoaderTask = (FormLoaderTask) data;
} else if (data instanceof SaveToDiskTask) {
mSaveToDiskTask = (SaveToDiskTask) data;
} else if (data == null) {
if (!newForm) {
if (Collect.getInstance().getFormController() != null) {
populateViews((Preset) getIntent().getParcelableExtra("fields"));
} else {
Log.w(TAG, "Reloading form and restoring state.");
// we need to launch the form loader to load the form
// controller...
mFormLoaderTask = new FormLoaderTask(instancePath,
startingXPath, waitingXPath);
Collect.getInstance().getActivityLogger()
.logAction(this, "formReloaded", mFormPath);
// TODO: this doesn't work (dialog does not get removed):
// showDialog(PROGRESS_DIALOG);
// show dialog before we execute...
mFormLoaderTask.execute(mFormPath);
}
return;
}
// Not a restart from a screen orientation change (or other).
Collect.getInstance().setFormController(null);
CompatibilityUtils.invalidateOptionsMenu(this);
Intent intent = getIntent();
if (intent != null) {
Uri uri = intent.getData();
if (getContentResolver().getType(uri).equals(InstanceColumns.CONTENT_ITEM_TYPE)) {
// get the formId and version for this instance...
String jrFormId = null;
String jrVersion = null;
{
Cursor instanceCursor = null;
try {
instanceCursor = getContentResolver().query(uri,
null, null, null, null);
if (instanceCursor.getCount() != 1) {
Log.w(TAG, "No form instance found for URI " + uri);
this.createErrorDialog("Bad URI: " + uri, EXIT);
return;
} else {
instanceCursor.moveToFirst();
instancePath = instanceCursor
.getString(instanceCursor
.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
Collect.getInstance()
.getActivityLogger()
.logAction(this, "instanceLoaded",
instancePath);
jrFormId = instanceCursor
.getString(instanceCursor
.getColumnIndex(InstanceColumns.JR_FORM_ID));
int idxJrVersion = instanceCursor
.getColumnIndex(InstanceColumns.JR_VERSION);
jrVersion = instanceCursor.isNull(idxJrVersion) ? null
: instanceCursor
.getString(idxJrVersion);
}
} finally {
if (instanceCursor != null) {
instanceCursor.close();
}
}
}
String[] selectionArgs;
String selection;
if (jrVersion == null) {
selectionArgs = new String[] { jrFormId };
selection = FormsColumns.JR_FORM_ID + "=? AND "
+ FormsColumns.JR_VERSION + " IS NULL";
} else {
selectionArgs = new String[] { jrFormId, jrVersion };
selection = FormsColumns.JR_FORM_ID + "=? AND "
+ FormsColumns.JR_VERSION + "=?";
}
{
Cursor formCursor = null;
try {
formCursor = getContentResolver().query(
FormsColumns.CONTENT_URI, null, selection,
selectionArgs, null);
if (formCursor.getCount() == 1) {
formCursor.moveToFirst();
mFormPath = formCursor
.getString(formCursor
.getColumnIndex(FormsColumns.FORM_FILE_PATH));
} else if (formCursor.getCount() < 1) {
this.createErrorDialog(
getString(
R.string.parent_form_not_present,
jrFormId)
+ ((jrVersion == null) ? ""
: "\n"
+ getString(R.string.version)
+ " "
+ jrVersion),
EXIT);
return;
} else if (formCursor.getCount() > 1) {
// still take the first entry, but warn that
// there are multiple rows.
// user will need to hand-edit the SQLite
// database to fix it.
formCursor.moveToFirst();
mFormPath = formCursor.getString(formCursor.getColumnIndex(FormsColumns.FORM_FILE_PATH));
this.createErrorDialog(getString(R.string.survey_multiple_forms_error), EXIT);
return;
}
} finally {
if (formCursor != null) {
formCursor.close();
}
}
}
} else if (getContentResolver().getType(uri).equals(FormsColumns.CONTENT_ITEM_TYPE)) {
Cursor c = null;
try {
c = getContentResolver().query(uri, null, null, null,
null);
if (c.getCount() != 1) {
Log.w(TAG, "No form found for URI " + uri);
this.createErrorDialog("Bad URI: " + uri, EXIT);
return;
} else {
c.moveToFirst();
mFormPath = c.getString(c.getColumnIndex(FormsColumns.FORM_FILE_PATH));
// This is the fill-blank-form code path.
// See if there is a savepoint for this form that
// has never been
// explicitly saved
// by the user. If there is, open this savepoint
// (resume this filled-in
// form).
// Savepoints for forms that were explicitly saved
// will be recovered
// when that
// explicitly saved instance is edited via
// edit-saved-form.
final String filePrefix = mFormPath.substring(
mFormPath.lastIndexOf('/') + 1,
mFormPath.lastIndexOf('.'))
+ "_";
final String fileSuffix = ".xml.save";
File cacheDir = new File(Collect.getInstance().getCachePath());
File[] files = cacheDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName();
return name.startsWith(filePrefix)
&& name.endsWith(fileSuffix);
}
});
// see if any of these savepoints are for a
// filled-in form that has never been
// explicitly saved by the user...
for (int i = 0; i < files.length; ++i) {
File candidate = files[i];
String instanceDirName = candidate.getName()
.substring(
0,
candidate.getName().length()
- fileSuffix.length());
File instanceDir = new File(
Collect.getInstance().getInstancesPath() + File.separator
+ instanceDirName);
File instanceFile = new File(instanceDir,
instanceDirName + ".xml");
if (instanceDir.exists()
&& instanceDir.isDirectory()
&& !instanceFile.exists()) {
// yes! -- use this savepoint file
instancePath = instanceFile
.getAbsolutePath();
break;
}
}
}
} finally {
if (c != null) {
c.close();
}
}
} else {
Log.e(TAG, "unrecognized URI");
this.createErrorDialog("Unrecognized URI: " + uri, EXIT);
return;
}
mFormLoaderTask = new FormLoaderTask(instancePath, null, null);
Collect.getInstance().getActivityLogger()
.logAction(this, "formLoaded", mFormPath);
showDialog(PROGRESS_DIALOG);
// show dialog before we execute...
mFormLoaderTask.execute(mFormPath);
}
}
}
private void populateViews(Preset preset) {
FormTraverser traverser = new FormTraverser.Builder()
.addVisitor(new QuestionHolderFormVisitor(preset))
.build();
traverser.traverse(Collect.getInstance().getFormController());
mBottomPaddingView = new View(this);
mBottomPaddingView.setLayoutParams(
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
mQuestionHolder.addView(mBottomPaddingView);
// After the form elements have all been sized and laid out, figure out
// where (vertically) the up/down buttons should jump to.
mScrollView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
paginate();
}
}
);
if (mTargetView != null) {
(new Handler(Looper.getMainLooper())).post(new Runnable() {
@Override
public void run() {
mScrollView.scrollTo(0, mTargetView.getTop());
}
});
}
// Store any pre-populated answers to enable performing a diff later on.
mOriginalAnswerData = getAnswers();
}
/**
* Determines the vertical positions that the up/down buttons will jump to.
* These positions are selected so that the height of each page is up to
* MAX_SCROLL_FRACTION of the ScrollView's height, and (if possible) each
* page break is at the top edge of a group or question.
*/
private void paginate() {
// Gather a list of the top edges of the question groups and widgets.
List<Integer> edges = new ArrayList<>();
for (int i = 0; i < mQuestionHolder.getChildCount(); i++) {
View child = mQuestionHolder.getChildAt(i);
edges.add(child.getTop());
if (child instanceof ODKView) {
List<QuestionWidget> widgets = ((ODKView) child).getWidgets();
// Skip the first widget: it's better to land above the group title
// than between the group title and the first question widget.
for (int j = 1; j < widgets.size(); j++) {
edges.add(child.getTop() + widgets.get(j).getTop());
}
}
}
// Select a subset of these edges to be the page breaks. Dividing the
// form into fixed pages ensures that each question appears at a fixed
// vertical position on the screen within its page, which helps keep
// the user oriented.
int maxPageHeight = (int) (mScrollView.getMeasuredHeight() * MAX_SCROLL_FRACTION);
mPageBreaks.clear();
mPageBreaks.add(0);
int prevBreak = 0;
int nextBreak = prevBreak + maxPageHeight;
for (int y : edges) {
while (y > prevBreak + maxPageHeight) { // next edge won't land on this page
mPageBreaks.add(nextBreak);
prevBreak = nextBreak;
// Usually this initial value of nextBreak will be overwritten
// by a value from edges (nextBreak = y below); this value is
// just a fallback in case the nearest edge is too far away.
nextBreak = prevBreak + maxPageHeight;
}
if (y > prevBreak) {
nextBreak = y;
}
}
// Add enough padding so that when the form is scrolled all the way to
// the end, the last page break lands at the top of the ScrollView.
// This can sometimes be a lot of padding (e.g. most of a page), but
// we think the benefit of having a consistent n:1 relationship between
// questions and pages is worth the occasionally large wasted space.
int bottom = prevBreak + mScrollView.getMeasuredHeight();
int paddingHeight = bottom - mBottomPaddingView.getTop();
ViewGroup.LayoutParams params = mBottomPaddingView.getLayoutParams();
if (params.height != paddingHeight) {
// To avoid triggering an infinite loop, only invoke
// requestLayout() when the height actually changes.
params.height = paddingHeight;
mBottomPaddingView.requestLayout();
}
}
/**
* Scrolls the form up or down to the next page break. To keep the user
* oriented, we always go to the nearest page break (even if it is nearby),
* giving a consistent set of pages with a consistent layout on each page.
*/
private void scrollPage(ScrollDirection direction) {
int inc = direction == ScrollDirection.DOWN ? 1 : -1;
int y = mScrollView.getScrollY();
int n = mPageBreaks.size();
for (int i = (inc > 0) ? 0 : n - 1; i >= 0 && i < n; i += inc) {
int deltaY = mPageBreaks.get(i) - y;
if (inc * deltaY > 0) {
mScrollView.smoothScrollTo(0, y + deltaY);
break;
}
}
}
private class QuestionHolderFormVisitor implements FormVisitor {
private final Preset mPreset;
public QuestionHolderFormVisitor(Preset preset) {
mPreset = preset;
}
@Override
public void visit(int event, FormController formController) {
View view = createView(event, false /*advancingPage*/, mPreset);
if (view != null) {
mQuestionHolder.addView(view);
}
}
}
/**
* Create save-points asynchronously in order to not affect swiping performance
* on larger forms.
*/
private void nonblockingCreateSavePointData() {
try {
SavePointTask savePointTask = new SavePointTask(this);
savePointTask.execute();
} catch (Exception e) {
Log.e(TAG, "Could not schedule SavePointTask. Perhaps a lot of swiping is taking place?");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_FORMPATH, mFormPath);
FormController formController = Collect.getInstance()
.getFormController();
if (formController != null) {
outState.putString(KEY_INSTANCEPATH, formController
.getInstancePath().getAbsolutePath());
outState.putString(KEY_XPATH,
formController.getXPath(formController.getFormIndex()));
FormIndex waiting = formController.getIndexWaitingForData();
if (waiting != null) {
outState.putString(KEY_XPATH_WAITING_FOR_DATA,
formController.getXPath(waiting));
}
// save the instance to a temp path...
nonblockingCreateSavePointData();
}
outState.putBoolean(NEWFORM, false);
outState.putString(KEY_ERROR, mErrorMessage);
outState.putBoolean(KEY_AUTO_SAVED, mAutoSaved);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
FormController formController = Collect.getInstance()
.getFormController();
if (formController == null) {
// we must be in the midst of a reload of the FormController.
// try to save this callback data to the FormLoaderTask
if (mFormLoaderTask != null
&& mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED) {
mFormLoaderTask.setActivityResult(requestCode, resultCode,
intent);
} else {
Log.e(TAG,
"Got an activityResult without any pending form loader");
}
return;
}
if (resultCode == RESULT_CANCELED) {
// request was canceled...
// if (requestCode != HIERARCHY_ACTIVITY) {
((ODKView) mCurrentView).cancelWaitingForBinaryData();
// }
return;
}
switch (requestCode) {
case BARCODE_CAPTURE:
String sb = intent.getStringExtra("SCAN_RESULT");
((ODKView) mCurrentView).setBinaryData(sb);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case EX_STRING_CAPTURE:
case EX_INT_CAPTURE:
case EX_DECIMAL_CAPTURE:
String key = "value";
boolean exists = intent.getExtras().containsKey(key);
if (exists) {
Object externalValue = intent.getExtras().get(key);
((ODKView) mCurrentView).setBinaryData(externalValue);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
break;
case EX_GROUP_CAPTURE:
try {
Bundle extras = intent.getExtras();
((ODKView) mCurrentView).setDataForFields(extras);
} catch (JavaRosaException e) {
Log.e(TAG, e.getMessage(), e);
createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT);
}
break;
case DRAW_IMAGE:
case ANNOTATE_IMAGE:
case SIGNATURE_CAPTURE:
case IMAGE_CAPTURE:
/*
* We saved the image to the tempfile_path, but we really want it to
* be in: /sdcard/odk/instances/[current instnace]/something.jpg so
* we move it there before inserting it into the content provider.
* Once the android image capture bug gets fixed, (read, we move on
* from Android 1.6) we want to handle images the audio and video
*/
// The intent is empty, but we know we saved the image to the temp
// file
File fi = new File(Collect.getInstance().getTmpFilePath());
String mInstanceFolder = formController.getInstancePath()
.getParent();
String s = mInstanceFolder + File.separator
+ System.currentTimeMillis() + ".jpg";
File nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(TAG, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(TAG,
"renamed " + fi.getAbsolutePath() + " to "
+ nf.getAbsolutePath());
}
((ODKView) mCurrentView).setBinaryData(nf);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case ALIGNED_IMAGE:
/*
* We saved the image to the tempfile_path; the app returns the full
* path to the saved file in the EXTRA_OUTPUT extra. Take that file
* and move it into the instance folder.
*/
String path = intent
.getStringExtra(android.provider.MediaStore.EXTRA_OUTPUT);
fi = new File(path);
mInstanceFolder = formController.getInstancePath().getParent();
s = mInstanceFolder + File.separator + System.currentTimeMillis()
+ ".jpg";
nf = new File(s);
if (!fi.renameTo(nf)) {
Log.e(TAG, "Failed to rename " + fi.getAbsolutePath());
} else {
Log.i(TAG,
"renamed " + fi.getAbsolutePath() + " to "
+ nf.getAbsolutePath());
}
((ODKView) mCurrentView).setBinaryData(nf);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case IMAGE_CHOOSER:
/*
* We have a saved image somewhere, but we really want it to be in:
* /sdcard/odk/instances/[current instnace]/something.jpg so we move
* it there before inserting it into the content provider. Once the
* android image capture bug gets fixed, (read, we move on from
* Android 1.6) we want to handle images the audio and video
*/
// get gp of chosen file
Uri selectedImage = intent.getData();
String sourceImagePath =
MediaUtils.getPathFromUri(this, selectedImage, Images.Media.DATA);
// Copy file to sdcard
String mInstanceFolder1 = formController.getInstancePath()
.getParent();
String destImagePath = mInstanceFolder1 + File.separator
+ System.currentTimeMillis() + ".jpg";
File source = new File(sourceImagePath);
File newImage = new File(destImagePath);
FileUtils.copyFile(source, newImage);
((ODKView) mCurrentView).setBinaryData(newImage);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case AUDIO_CAPTURE:
case VIDEO_CAPTURE:
case AUDIO_CHOOSER:
case VIDEO_CHOOSER:
// For audio/video capture/chooser, we get the URI from the content
// provider
// then the widget copies the file and makes a new entry in the
// content provider.
Uri media = intent.getData();
((ODKView) mCurrentView).setBinaryData(media);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case LOCATION_CAPTURE:
String sl = intent.getStringExtra(LOCATION_RESULT);
((ODKView) mCurrentView).setBinaryData(sl);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case BEARING_CAPTURE:
String bearing = intent.getStringExtra(BEARING_RESULT);
((ODKView) mCurrentView).setBinaryData(bearing);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
// case HIERARCHY_ACTIVITY:
// // We may have jumped to a new index in hierarchy activity, so
// // refresh
// break;
}
// refreshCurrentView();
}
//
// /**
// * Refreshes the current view. the controller and the displayed view can get
// * out of sync due to dialogs and restarts caused by screen orientation
// * changes, so they're resynchronized here.
// */
// public void refreshCurrentView() {
// FormController formController = Collect.getInstance()
// .getFormController();
// int event = formController.getEvent();
//
// // When we refresh, repeat dialog state isn't maintained, so step back
// // to the previous
// // question.
// // Also, if we're within a group labeled 'field list', step back to the
// // beginning of that
// // group.
// // That is, skip backwards over repeat prompts, groups that are not
// // field-lists,
// // repeat events, and indexes in field-lists that is not the containing
// // group.
// if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
// createRepeatDialog();
// } else {
// View current = createView(event, false);
// showView(current, AnimationType.FADE);
// }
// }
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
showAlertDialog();
return true;
}
else {
return super.onKeyDown(keyCode, event);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "onCreateOptionsMenu", "show");
super.onCreateOptionsMenu(menu);
// CompatibilityUtils.setShowAsAction(
// menu.add(0, MENU_CANCEL, 0, R.string.cancel),
// MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
// CompatibilityUtils.setShowAsAction(
// menu.add(0, MENU_SAVE, 0, R.string.save_all_answers),
// MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
// CompatibilityUtils.setShowAsAction(
// menu.add(0, MENU_HIERARCHY_VIEW, 0, R.string.view_hierarchy)
// .setIcon(R.drawable.ic_menu_goto),
// MenuItem.SHOW_AS_ACTION_IF_ROOM);
// CompatibilityUtils.setShowAsAction(
// menu.add(0, MENU_LANGUAGES, 0, R.string.change_language)
// .setIcon(R.drawable.ic_menu_start_conversation),
// MenuItem.SHOW_AS_ACTION_NEVER);
// CompatibilityUtils.setShowAsAction(
// menu.add(0, MENU_PREFERENCES, 0, R.string.general_preferences)
// .setIcon(R.drawable.ic_menu_preferences),
// MenuItem.SHOW_AS_ACTION_NEVER);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// menu.findItem(MENU_CANCEL).setVisible(true).setEnabled(true);
// menu.findItem(MENU_SAVE).setVisible(true).setEnabled(true);
//
// FormController formController = Collect.getInstance()
// .getFormController();
//
// boolean useability;
// useability = mAdminPreferences.getBoolean(
// AdminPreferencesActivity.KEY_SAVE_MID, true);
//
// menu.findItem(MENU_SAVE).setVisible(useability).setEnabled(useability);
//
// useability = mAdminPreferences.getBoolean(
// AdminPreferencesActivity.KEY_JUMP_TO, true);
//
// menu.findItem(MENU_HIERARCHY_VIEW).setVisible(useability)
// .setEnabled(useability);
//
// useability = mAdminPreferences.getBoolean(
// AdminPreferencesActivity.KEY_CHANGE_LANGUAGE, true)
// && (formController != null)
// && formController.getLanguages() != null
// && formController.getLanguages().length > 1;
//
// menu.findItem(MENU_LANGUAGES).setVisible(useability)
// .setEnabled(useability);
//
// useability = mAdminPreferences.getBoolean(
// AdminPreferencesActivity.KEY_ACCESS_SETTINGS, true);
//
// menu.findItem(MENU_PREFERENCES).setVisible(useability)
// .setEnabled(useability);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// FormController formController = Collect.getInstance()
// .getFormController();
switch (item.getItemId()) {
case android.R.id.home :
// Go back rather than reloading the activity, so that the patient list retains its
// filter state.
onBackPressed();
return true;
//// case MENU_LANGUAGES:
//// Collect.getInstance()
//// .getActivityLogger()
//// .logInstanceAction(this, "onOptionsItemSelected",
//// "MENU_LANGUAGES");
//// createLanguageDialog();
//// return true;
// case MENU_CANCEL:
// showAlertDialog();
// return true;
// case MENU_SAVE:
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this, "onOptionsItemSelected",
// "MENU_SAVE");
// InputMethodManager imm = (InputMethodManager)getSystemService(
// Context.INPUT_METHOD_SERVICE);
// imm.hideSoftInputFromWindow( findViewById(android.R.id.content).getWindowToken(), 0);
// saveDataToDisk(EXIT, true /*complete*/, null);
// return true;
// case MENU_HIERARCHY_VIEW:
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this, "onOptionsItemSelected",
// "MENU_HIERARCHY_VIEW");
// if (formController.currentPromptIsQuestion()) {
// saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
// }
// Intent i = new Intent(this, FormHierarchyActivity.class);
// startActivityForResult(i, HIERARCHY_ACTIVITY);
// return true;
// case MENU_PREFERENCES:
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this, "onOptionsItemSelected",
// "MENU_PREFERENCES");
// Intent pref = new Intent(this, PreferencesActivity.class);
// startActivity(pref);
// return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Attempt to save the answer(s) in the current screen to into the data
* model.
*
* @param evaluateConstraints
* @return false if any error occurs while saving (constraint violated,
* etc...), true otherwise.
*/
private boolean saveAnswersForCurrentScreen(boolean evaluateConstraints) {
FormController formController = Collect.getInstance()
.getFormController();
// only try to save if the current event is a question or a field-list
// group
if (formController.currentPromptIsQuestion()) {
LinkedHashMap<FormIndex, IAnswerData> answers = ((ODKView) mCurrentView)
.getAnswers();
try {
FailedConstraint constraint = formController.saveAnswers(answers, evaluateConstraints);
if (constraint != null) {
createConstraintToast(constraint.index, constraint.status);
return false;
}
} catch (JavaRosaException e) {
Log.e(TAG, e.getMessage(), e);
createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT);
return false;
}
}
return true;
}
/**
* Collects all answers in the form into a single map.
* @return a {@link java.util.LinkedHashMap} of all answers in the form.
*/
private LinkedHashMap<FormIndex, IAnswerData> getAnswers() {
int childCount = mQuestionHolder.getChildCount();
LinkedHashMap<FormIndex, IAnswerData> answers = new LinkedHashMap<FormIndex, IAnswerData>();
for (int i = 0; i < childCount; i++) {
View view = mQuestionHolder.getChildAt(i);
if (!(view instanceof ODKView)) {
continue;
}
answers.putAll(((ODKView) view).getAnswers());
}
return answers;
}
/**
* Saves all answers in the form.
*
* @return false if any error occurs while saving (constraint violated,
* etc...), true otherwise
*/
private boolean saveAnswers(boolean evaluateConstraints) {
FormController formController = Collect.getInstance().getFormController();
int childCount = mQuestionHolder.getChildCount();
LinkedHashMap<FormIndex, IAnswerData> answers = getAnswers();
try {
FailedConstraint constraint = formController.saveAnswers(answers, evaluateConstraints);
if (constraint != null) {
createConstraintToast(constraint.index, constraint.status);
return false;
}
} catch (JavaRosaException e) {
Log.e(TAG, e.getMessage(), e);
createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT);
return false;
}
return true;
}
/**
* Clears the answer on the screen.
*/
private void clearAnswer(QuestionWidget qw) {
if (qw.getAnswer() != null) {
qw.clearAnswer();
}
}
// @Override
// public void onCreateContextMenu(ContextMenu menu, View v,
// ContextMenuInfo menuInfo) {
// super.onCreateContextMenu(menu, v, menuInfo);
// Collect.getInstance().getActivityLogger()
// .logInstanceAction(this, "onCreateContextMenu", "show");
// FormController formController = Collect.getInstance()
// .getFormController();
//
// menu.add(0, v.getId(), 0, getString(R.string.clear_answer));
//// if (formController.indexContainsRepeatableGroup()) {
//// menu.add(0, DELETE_REPEAT, 0, getString(R.string.delete_repeat));
//// }
// menu.setHeaderTitle(getString(R.string.edit_prompt));
// }
// @Override
// public boolean onContextItemSelected(MenuItem item) {
// /*
// * We don't have the right view here, so we store the View's ID as the
// * item ID and loop through the possible views to find the one the user
// * clicked on.
// */
// for (QuestionWidget qw : ((ODKView) mCurrentView).getWidgets()) {
// if (item.getItemId() == qw.getId()) {
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this, "onContextItemSelected",
// "createClearDialog", qw.getPrompt().getIndex());
// createClearDialog(qw);
// }
// }
//// if (item.getItemId() == DELETE_REPEAT) {
//// Collect.getInstance()
//// .getActivityLogger()
//// .logInstanceAction(this, "onContextItemSelected",
//// "createDeleteRepeatConfirmDialog");
//// createDeleteRepeatConfirmDialog();
//// }
//
// return super.onContextItemSelected(item);
// }
/**
* If we're loading, then we pass the loading thread to our next instance.
*/
@Override
public Object onRetainNonConfigurationInstance() {
FormController formController = Collect.getInstance()
.getFormController();
// if a form is loading, pass the loader task
if (mFormLoaderTask != null
&& mFormLoaderTask.getStatus() != AsyncTask.Status.FINISHED)
return mFormLoaderTask;
// if a form is writing to disk, pass the save to disk task
if (mSaveToDiskTask != null
&& mSaveToDiskTask.getStatus() != AsyncTask.Status.FINISHED)
return mSaveToDiskTask;
// mFormEntryController is static so we don't need to pass it.
if (formController != null && formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
return null;
}
/**
* Creates a view given the View type and an event
*
* @param event
* @param advancingPage
* -- true if this results from advancing through the form
* @param preset
* @return newly created View
*/
private View createView(int event, boolean advancingPage, Preset preset) {
FormController formController = Collect.getInstance()
.getFormController();
FormInstance formInstance = formController.getFormDef().getMainInstance();
// setTitle(getString(R.string.app_name) + " > "
// + formController.getFormTitle());
switch (event) {
// case FormEntryController.EVENT_BEGINNING_OF_FORM:
// View startView = View
// .inflate(this, R.layout.form_entry_start, null);
// setTitle(getString(R.string.app_name) + " > "
// + formController.getFormTitle());
//
// Drawable image = null;
// File mediaFolder = formController.getMediaFolder();
// String mediaDir = mediaFolder.getAbsolutePath();
// BitmapDrawable bitImage = null;
// // attempt to load the form-specific logo...
// // this is arbitrarily silly
// bitImage = new BitmapDrawable(getResources(), mediaDir + File.separator
// + "form_logo.png");
//
// if (bitImage != null && bitImage.getBitmap() != null
// && bitImage.getIntrinsicHeight() > 0
// && bitImage.getIntrinsicWidth() > 0) {
// image = bitImage;
// }
//
// if (image == null) {
// // show the opendatakit zig...
// // image =
// // getResources().getDrawable(R.drawable.opendatakit_zig);
// ((ImageView) startView.findViewById(R.id.form_start_bling))
// .setVisibility(View.GONE);
// } else {
// ImageView v = ((ImageView) startView
// .findViewById(R.id.form_start_bling));
// v.setImageDrawable(image);
// v.setContentDescription(formController.getFormTitle());
// }
//
// // change start screen based on navigation prefs
// String navigationChoice = PreferenceManager
// .getDefaultSharedPreferences(this).getString(
// PreferencesActivity.KEY_NAVIGATION,
// PreferencesActivity.KEY_NAVIGATION);
// Boolean useSwipe = false;
// Boolean useButtons = false;
// ImageView ia = ((ImageView) startView
// .findViewById(R.id.image_advance));
// ImageView ib = ((ImageView) startView
// .findViewById(R.id.image_backup));
// TextView ta = ((TextView) startView.findViewById(R.id.text_advance));
// TextView tb = ((TextView) startView.findViewById(R.id.text_backup));
// TextView d = ((TextView) startView.findViewById(R.id.description));
//
// if (navigationChoice != null) {
// if (navigationChoice
// .contains(PreferencesActivity.NAVIGATION_SWIPE)) {
// useSwipe = true;
// }
// if (navigationChoice
// .contains(PreferencesActivity.NAVIGATION_BUTTONS)) {
// useButtons = true;
// }
// }
// if (useSwipe && !useButtons) {
// d.setText(getString(R.string.swipe_instructions,
// formController.getFormTitle()));
// } else if (useButtons && !useSwipe) {
// ia.setVisibility(View.GONE);
// ib.setVisibility(View.GONE);
// ta.setVisibility(View.GONE);
// tb.setVisibility(View.GONE);
// d.setText(getString(R.string.buttons_instructions,
// formController.getFormTitle()));
// } else {
// d.setText(getString(R.string.swipe_buttons_instructions,
// formController.getFormTitle()));
// }
//
// return startView;
// case FormEntryController.EVENT_END_OF_FORM:
// View endView = View.inflate(this, R.layout.form_entry_end, null);
// ((TextView) endView.findViewById(R.id.description))
// .setText(getString(R.string.save_enter_data_description,
// formController.getFormTitle()));
//
// // checkbox for if finished or ready to send
// final CheckBox instanceComplete = ((CheckBox) endView
// .findViewById(R.id.mark_finished));
// instanceComplete.setChecked(isInstanceComplete(true));
//
// if (!mAdminPreferences.getBoolean(
// AdminPreferencesActivity.KEY_MARK_AS_FINALIZED, true)) {
// instanceComplete.setVisibility(View.GONE);
// }
//
// // edittext to change the displayed name of the instance
// final EditText saveAs = (EditText) endView
// .findViewById(R.id.save_name);
//
// // disallow carriage returns in the name
// InputFilter returnFilter = new InputFilter() {
// public CharSequence filter(CharSequence source, int start,
// int end, Spanned dest, int dstart, int dend) {
// for (int i = start; i < end; i++) {
// if (Character.getType((source.charAt(i))) == Character.CONTROL) {
// return "";
// }
// }
// return null;
// }
// };
// saveAs.setFilters(new InputFilter[] { returnFilter });
//
// String saveName = formController.getSubmissionMetadata().instanceName;
// if (saveName == null) {
// // no meta/instanceName field in the form -- see if we have a
// // name for this instance from a previous save attempt...
// if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) {
// Uri instanceUri = getIntent().getData();
// Cursor instance = null;
// try {
// instance = getContentResolver().query(instanceUri,
// null, null, null, null);
// if (instance.getCount() == 1) {
// instance.moveToFirst();
// saveName = instance
// .getString(instance
// .getColumnIndex(InstanceColumns.DISPLAY_NAME));
// }
// } finally {
// if (instance != null) {
// instance.close();
// }
// }
// }
// if (saveName == null) {
// // last resort, default to the form title
// saveName = formController.getFormTitle();
// }
// // present the prompt to allow user to name the form
// TextView sa = (TextView) endView
// .findViewById(R.id.save_form_as);
// sa.setVisibility(View.VISIBLE);
// saveAs.setText(saveName);
// saveAs.setEnabled(true);
// saveAs.setVisibility(View.VISIBLE);
// } else {
// // if instanceName is defined in form, this is the name -- no
// // revisions
// // display only the name, not the prompt, and disable edits
// TextView sa = (TextView) endView
// .findViewById(R.id.save_form_as);
// sa.setVisibility(View.GONE);
// saveAs.setText(saveName);
// saveAs.setEnabled(false);
// saveAs.setBackgroundColor(Color.WHITE);
// saveAs.setVisibility(View.VISIBLE);
// }
//
// // override the visibility settings based upon admin preferences
// if (!mAdminPreferences.getBoolean(
// AdminPreferencesActivity.KEY_SAVE_AS, true)) {
// saveAs.setVisibility(View.GONE);
// TextView sa = (TextView) endView
// .findViewById(R.id.save_form_as);
// sa.setVisibility(View.GONE);
// }
//
// // Create 'save' button
// ((Button) endView.findViewById(R.id.save_exit_button))
// .setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(
// this,
// "createView.saveAndExit",
// instanceComplete.isChecked() ? "saveAsComplete"
// : "saveIncomplete");
// // Form is marked as 'saved' here.
// if (saveAs.getText().length() < 1) {
// Toast.makeText(FormEntryActivity.this,
// R.string.save_as_error,
// Toast.LENGTH_SHORT).show();
// } else {
// saveDataToDisk(EXIT, instanceComplete
// .isChecked(), saveAs.getText()
// .toString());
// }
// }
// });
//
// return endView;
// case FormEntryController.EVENT_GROUP:
// FormEntryCaption[] groups = formController.getGroupsForCurrentIndex();
// if (groups.length == 0) {
// Log.e(
// TAG,
// "Attempted to handle a FormEntryController.EVENT_GROUP when the form was "
// + "not on a group.");
// break;
// }
// WidgetGroupBuilder builder =
// Widget2Factory.INSTANCE.createGroupBuilder(this, groups[groups.length - 1]);
// if (builder != null) {
// // TODO: Use the builder.
// break;
// }
//
// // Fall through to the next case if we didn't manage to create a builder.
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_GROUP:
case FormEntryController.EVENT_REPEAT:
ODKView odkv = null;
// should only be a group here if the event_group is a field-list
try {
FormEntryPrompt[] prompts = formController.getQuestionPrompts();
FormEntryCaption[] groups = formController
.getGroupsForCurrentIndex();
TreeReference ref = formController.getFormIndex().getReference();
TreeElement element = formInstance.resolveReference(ref);
odkv = new ODKView(this, prompts, groups, advancingPage, preset);
if (preset != null
&& preset.targetGroup != null
&& preset.targetGroup.equals(groups[groups.length - 1].getLongText())) {
mTargetView = odkv;
}
Log.i(TAG,
"created view for group "
+ (groups.length > 0 ? groups[groups.length - 1]
.getLongText() : "[top]")
+ " "
+ (prompts.length > 0 ? prompts[0]
.getQuestionText() : "[no question]"));
} catch (RuntimeException e) {
Log.e(TAG, e.getMessage(), e);
// this is badness to avoid a crash.
try {
event = formController.stepToNextScreenEvent();
createErrorDialog(e.getMessage(), DO_NOT_EXIT);
} catch (JavaRosaException e1) {
Log.e(TAG, e1.getMessage(), e1);
createErrorDialog(e.getMessage() + "\n\n" + e1.getCause().getMessage(), DO_NOT_EXIT);
}
return createView(event, advancingPage, preset);
}
// Makes a "clear answer" menu pop up on long-click
for (QuestionWidget qw : odkv.getWidgets()) {
if (!qw.getPrompt().isReadOnly()) {
registerForContextMenu(qw);
}
}
return odkv;
default:
return null;
// Log.e(TAG, "Attempted to create a view that does not exist.");
// // this is badness to avoid a crash.
// try {
// event = formController.stepToNextScreenEvent();
// createErrorDialog(getString(R.string.survey_internal_error), EXIT);
// } catch (JavaRosaException e) {
// Log.e(TAG, e.getMessage(), e);
// createErrorDialog(e.getCause().getMessage(), EXIT);
// }
// return createView(event, advancingPage);
}
}
// @Override
// public boolean dispatchTouchEvent(MotionEvent mv) {
// boolean handled = mGestureDetector.onTouchEvent(mv);
// if (!handled) {
// return super.dispatchTouchEvent(mv);
// }
//
// return handled; // this is always true
// }
//
// /**
// * Determines what should be displayed on the screen. Possible options are:
// * a question, an ask repeat dialog, or the submit screen. Also saves
// * answers to the data model after checking constraints.
// */
// private void showNextView() {
// try {
// FormController formController = Collect.getInstance()
// .getFormController();
//
// // get constraint behavior preference value with appropriate default
// String constraint_behavior = PreferenceManager.getDefaultSharedPreferences(this)
// .getString(PreferencesActivity.KEY_CONSTRAINT_BEHAVIOR,
// PreferencesActivity.CONSTRAINT_BEHAVIOR_DEFAULT);
//
// if (formController.currentPromptIsQuestion()) {
//
// // if constraint behavior says we should validate on swipe, do so
// if (constraint_behavior.equals(PreferencesActivity.CONSTRAINT_BEHAVIOR_ON_SWIPE)) {
// if (!saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS)) {
// // A constraint was violated so a dialog should be showing.
// mBeenSwiped = false;
// return;
// }
//
// // otherwise, just save without validating (constraints will be validated on finalize)
// } else
// saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
// }
//
// View next;
// int event = formController.stepToNextScreenEvent();
//
//
// switch (event) {
// case FormEntryController.EVENT_QUESTION:
// case FormEntryController.EVENT_GROUP:
// // create a savepoint
// if ((++viewCount) % SAVEPOINT_INTERVAL == 0) {
// nonblockingCreateSavePointData();
// }
// next = createView(event, true);
// showView(next, AnimationType.RIGHT);
// break;
// case FormEntryController.EVENT_END_OF_FORM:
// case FormEntryController.EVENT_REPEAT:
// next = createView(event, true);
// showView(next, AnimationType.RIGHT);
// break;
// case FormEntryController.EVENT_PROMPT_NEW_REPEAT:
// createRepeatDialog();
// break;
// case FormEntryController.EVENT_REPEAT_JUNCTURE:
// Log.i(TAG, "repeat juncture: "
// + formController.getFormIndex().getReference());
// // skip repeat junctures until we implement them
// break;
// default:
// Log.w(TAG,
// "JavaRosa added a new EVENT type and didn't tell us... shame on them.");
// break;
// }
// } catch (JavaRosaException e) {
// Log.e(TAG, e.getMessage(), e);
// createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT);
// }
// }
//
// /**
// * Determines what should be displayed between a question, or the start
// * screen and displays the appropriate view. Also saves answers to the data
// * model without checking constraints.
// */
// private void showPreviousView() {
// try {
// FormController formController = Collect.getInstance()
// .getFormController();
// // The answer is saved on a back swipe, but question constraints are
// // ignored.
// if (formController.currentPromptIsQuestion()) {
// saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
// }
//
// if (formController.getEvent() != FormEntryController.EVENT_BEGINNING_OF_FORM) {
// int event = formController.stepToPreviousScreenEvent();
//
// if (event == FormEntryController.EVENT_BEGINNING_OF_FORM
// || event == FormEntryController.EVENT_GROUP
// || event == FormEntryController.EVENT_QUESTION) {
// // create savepoint
// if ((++viewCount) % SAVEPOINT_INTERVAL == 0) {
// nonblockingCreateSavePointData();
// }
// }
// View next = createView(event, false);
// showView(next, AnimationType.LEFT);
// } else {
// mBeenSwiped = false;
// }
// } catch (JavaRosaException e) {
// Log.e(TAG, e.getMessage(), e);
// createErrorDialog(e.getCause().getMessage(), DO_NOT_EXIT);
// }
// }
//
// /**
// * Displays the View specified by the parameter 'next', animating both the
// * current view and next appropriately given the AnimationType. Also updates
// * the progress bar.
// */
// public void showView(View next, AnimationType from) {
//
// // disable notifications...
// if (mInAnimation != null) {
// mInAnimation.setAnimationListener(null);
// }
// if (mOutAnimation != null) {
// mOutAnimation.setAnimationListener(null);
// }
//
// // logging of the view being shown is already done, as this was handled
// // by createView()
// switch (from) {
// case RIGHT:
// mInAnimation = AnimationUtils.loadAnimation(this,
// R.anim.push_left_in);
// mOutAnimation = AnimationUtils.loadAnimation(this,
// R.anim.push_left_out);
// // if animation is left or right then it was a swipe, and we want to re-save on entry
// mAutoSaved = false;
// break;
// case LEFT:
// mInAnimation = AnimationUtils.loadAnimation(this,
// R.anim.push_right_in);
// mOutAnimation = AnimationUtils.loadAnimation(this,
// R.anim.push_right_out);
// mAutoSaved = false;
// break;
// case FADE:
// mInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
// mOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
// break;
// }
//
// // complete setup for animations...
// mInAnimation.setAnimationListener(this);
// mOutAnimation.setAnimationListener(this);
//
// // drop keyboard before transition...
// if (mCurrentView != null) {
// InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// inputManager.hideSoftInputFromWindow(mCurrentView.getWindowToken(),
// 0);
// }
//
// RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
// LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
//
// // adjust which view is in the layout container...
// mStaleView = mCurrentView;
// mCurrentView = next;
// mQuestionHolder.addView(mCurrentView, lp);
// mAnimationCompletionSet = 0;
//
// if (mStaleView != null) {
// // start OutAnimation for transition...
// mStaleView.startAnimation(mOutAnimation);
// // and remove the old view (MUST occur after start of animation!!!)
// mQuestionHolder.removeView(mStaleView);
// } else {
// mAnimationCompletionSet = 2;
// }
// // start InAnimation for transition...
// mCurrentView.startAnimation(mInAnimation);
//
// String logString = "";
// switch (from) {
// case RIGHT:
// logString = "next";
// break;
// case LEFT:
// logString = "previous";
// break;
// case FADE:
// logString = "refresh";
// break;
// }
//
// Collect.getInstance().getActivityLogger().logInstanceAction(this, "showView", logString);
//
// FormController formController = Collect.getInstance().getFormController();
// if (formController.getEvent() == FormEntryController.EVENT_QUESTION
// || formController.getEvent() == FormEntryController.EVENT_GROUP
// || formController.getEvent() == FormEntryController.EVENT_REPEAT) {
// FormEntryPrompt[] prompts = Collect.getInstance().getFormController()
// .getQuestionPrompts();
// for (FormEntryPrompt p : prompts) {
// Vector<TreeElement> attrs = p.getBindAttributes();
// for (int i = 0; i < attrs.size(); i++) {
// if (!mAutoSaved && "saveIncomplete".equals(attrs.get(i).getName())) {
// saveDataToDisk(false, false, null, false);
// mAutoSaved = true;
// }
// }
// }
// }
// }
// Hopefully someday we can use managed dialogs when the bugs are fixed
/*
* Ideally, we'd like to use Android to manage dialogs with onCreateDialog()
* and onPrepareDialog(), but dialogs with dynamic content are broken in 1.5
* (cupcake). We do use managed dialogs for our static loading
* ProgressDialog. The main issue we noticed and are waiting to see fixed
* is: onPrepareDialog() is not called after a screen orientation change.
* http://code.google.com/p/android/issues/detail?id=1639
*/
private String getAttribute(Vector<TreeElement> attrs, String name) {
for (TreeElement attr : attrs) {
if (eq(attr.getName(), name)) {
return attr.getAttributeValue();
}
}
return null;
}
/** Displays a toast message showing a violated constraint. */
private void createConstraintToast(FormIndex index, int saveStatus) {
FormController formController = Collect.getInstance().getFormController();
FormEntryPrompt prompt = formController.getQuestionPrompt(index);
String questionText = Utils.localize(prompt.getQuestionText(), this).trim();
String message;
switch (saveStatus) {
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createConstraintToast.ANSWER_CONSTRAINT_VIOLATED",
"show", index);
Vector<TreeElement> attrs = prompt.getBindAttributes();
String min = getAttribute(attrs, "constraint-min");
String max = getAttribute(attrs, "constraint-max");
if (min != null && max != null) {
message = getString(R.string.invalid_min_max, questionText, min, max);
} else if (min != null) {
message = getString(R.string.invalid_min, questionText, min);
} else if (max != null) {
message = getString(R.string.invalid_max, questionText, max);
} else {
message = Utils.localize(prompt.getConstraintText(), this);
if (message == null) {
message = Utils.localize(prompt.getSpecialFormQuestionText("constraintMsg"), this);
}
if (message == null) {
message = questionText + ": " + Utils.localize(getAttribute(prompt.getBindAttributes(), "message"), this);
}
if (message == null) {
message = getString(R.string.question_is_invalid, questionText);
}
}
break;
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"createConstraintToast.ANSWER_REQUIRED_BUT_EMPTY",
"show", index);
message = Utils.localize(formController.getQuestionPromptRequiredText(index), this);
if (message == null) {
message = Utils.localize(prompt.getSpecialFormQuestionText("requiredMsg"), this);
}
if (message == null) {
message = getString(R.string.question_is_required, questionText);
}
break;
default:
return;
}
showCustomToast(message, Toast.LENGTH_SHORT);
}
/**
* Creates a toast with the specified message.
*
* @param message
*/
private void showCustomToast(String message, int duration) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.toast_view, null);
// set the text in the view
TextView tv = (TextView) view.findViewById(R.id.message);
tv.setText(message);
Toast t = new Toast(this);
t.setView(view);
t.setDuration(duration);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
// /**
// * Creates and displays a dialog asking the user if they'd like to create a
// * repeat of the current group.
// */
// private void createRepeatDialog() {
// FormController formController = Collect.getInstance()
// .getFormController();
// Collect.getInstance().getActivityLogger()
// .logInstanceAction(this, "createRepeatDialog", "show");
// mAlertDialog = new AlertDialog.Builder(this).create();
// mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
// DialogInterface.OnClickListener repeatListener = new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int i) {
// FormController formController = Collect.getInstance()
// .getFormController();
// switch (i) {
// case DialogInterface.BUTTON_POSITIVE: // yes, repeat
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this, "createRepeatDialog",
// "addRepeat");
// try {
// formController.newRepeat();
// } catch (Exception e) {
// FormEntryActivity.this.createErrorDialog(
// e.getMessage(), DO_NOT_EXIT);
// return;
// }
// if (!formController.indexIsInFieldList()) {
// // we are at a REPEAT event that does not have a
// // field-list appearance
// // step to the next visible field...
// // which could be the start of a new repeat group...
// showNextView();
// } else {
// // we are at a REPEAT event that has a field-list
// // appearance
// // just display this REPEAT event's group.
// refreshCurrentView();
// }
// break;
// case DialogInterface. BUTTON_NEGATIVE: // no, no repeat
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this, "createRepeatDialog",
// "showNext");
//
// //
// // Make sure the error dialog will not disappear.
// //
// // When showNextView() popups an error dialog (because of a JavaRosaException)
// // the issue is that the "add new repeat dialog" is referenced by mAlertDialog
// // like the error dialog. When the "no repeat" is clicked, the error dialog
// // is shown. Android by default dismisses the dialogs when a button is clicked,
// // so instead of closing the first dialog, it closes the second.
// new Thread() {
//
// @Override
// public void run() {
// FormEntryActivity.this.runOnUiThread(new Runnable() {
// @Override
// public void run() {
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// showNextView();
// }
// });
// }
// }.start();
//
// break;
// }
// }
// };
// if (formController.getLastRepeatCount() > 0) {
// mAlertDialog.setTitle(getString(R.string.leaving_repeat_ask));
// mAlertDialog.setMessage(getString(R.string.add_another_repeat,
// formController.getLastGroupText()));
// mAlertDialog.setButton(getString(R.string.add_another),
// repeatListener);
// mAlertDialog.setButton2(getString(R.string.leave_repeat_yes),
// repeatListener);
//
// } else {
// mAlertDialog.setTitle(getString(R.string.entering_repeat_ask));
// mAlertDialog.setMessage(getString(R.string.add_repeat,
// formController.getLastGroupText()));
// mAlertDialog.setButton(getString(R.string.entering_repeat),
// repeatListener);
// mAlertDialog.setButton2(getString(R.string.add_repeat_no),
// repeatListener);
// }
// mAlertDialog.setCancelable(false);
// mBeenSwiped = false;
// showAlertDialog();
// }
/**
* Creates and displays dialog with the given errorMsg.
*/
private void createErrorDialog(String errorMsg, final boolean shouldExit) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createErrorDialog",
"show." + Boolean.toString(shouldExit));
if (mAlertDialog != null && mAlertDialog.isShowing()) {
errorMsg = mErrorMessage + "\n\n" + errorMsg;
mErrorMessage = errorMsg;
} else {
mAlertDialog = new AlertDialog.Builder(this).create();
mErrorMessage = errorMsg;
}
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setTitle(getString(R.string.error_occured));
mAlertDialog.setMessage(errorMsg);
DialogInterface.OnClickListener errorListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createErrorDialog", "OK");
if (shouldExit) {
mErrorMessage = null;
finish();
}
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog.setButton(getString(R.string.ok), errorListener);
showAlertDialog();
}
// /**
// * Creates a confirm/cancel dialog for deleting repeats.
// */
// private void createDeleteRepeatConfirmDialog() {
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this, "createDeleteRepeatConfirmDialog",
// "show");
// FormController formController = Collect.getInstance()
// .getFormController();
// mAlertDialog = new AlertDialog.Builder(this).create();
// mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
// String name = formController.getLastRepeatedGroupName();
// int repeatcount = formController.getLastRepeatedGroupRepeatCount();
// if (repeatcount != -1) {
// name += " (" + (repeatcount + 1) + ")";
// }
// mAlertDialog.setTitle(getString(R.string.delete_repeat_ask));
// mAlertDialog
// .setMessage(getString(R.string.delete_repeat_confirm, name));
// DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int i) {
// FormController formController = Collect.getInstance()
// .getFormController();
// switch (i) {
// case DialogInterface.BUTTON_POSITIVE: // yes
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this,
// "createDeleteRepeatConfirmDialog", "OK");
// formController.deleteRepeat();
// showPreviousView();
// break;
// case DialogInterface. BUTTON_NEGATIVE: // no
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this,
// "createDeleteRepeatConfirmDialog", "cancel");
// break;
// }
// }
// };
// mAlertDialog.setCancelable(false);
// mAlertDialog.setButton(getString(R.string.discard_group), quitListener);
// mAlertDialog.setButton2(getString(R.string.delete_repeat_no),
// quitListener);
// showAlertDialog();
// }
/**
* Saves data and writes it to disk. If exit is set, program will exit after
* save completes. Complete indicates whether the user has marked the
* isntancs as complete. If updatedSaveName is non-null, the instances
* content provider is updated with the new name
*/
// by default, save the current screen
private boolean saveDataToDisk(boolean exit, boolean complete, String updatedSaveName) {
return saveDataToDisk(exit, complete, updatedSaveName, true);
}
// but if you want save in the background, can't be current screen
private boolean saveDataToDisk(boolean exit, boolean complete, String updatedSaveName,
boolean current) {
// save current answer
if (!saveAnswers(EVALUATE_CONSTRAINTS)) {
return false;
}
synchronized (saveDialogLock) {
mSaveToDiskTask = new SaveToDiskTask(getIntent().getData(), exit, complete,
updatedSaveName);
mSaveToDiskTask.setFormSavedListener(this);
mAutoSaved = true;
showDialog(SAVING_DIALOG);
// show dialog before we execute...
mSaveToDiskTask.execute();
}
return true;
}
/**
* Create a dialog with options to save and exit, save, or quit without
* saving
*/
private void createQuitDialog() {
FormController formController = Collect.getInstance()
.getFormController();
String[] items;
String[] two = { getString(R.string.keep_changes),
getString(R.string.do_not_save) };
items = two;
Collect.getInstance().getActivityLogger()
.logInstanceAction(this, "createQuitDialog", "show");
showAlertDialog();
}
/**
* this method cleans up unneeded files when the user selects 'discard and
* exit'
*/
private void removeTempInstance() {
FormController formController = Collect.getInstance()
.getFormController();
// attempt to remove any scratch file
File temp = SaveToDiskTask.savepointFile(formController
.getInstancePath());
if (temp.exists()) {
temp.delete();
}
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = { formController.getInstancePath()
.getAbsolutePath() };
boolean erase = false;
{
Cursor c = null;
try {
c = getContentResolver().query(InstanceColumns.CONTENT_URI,
null, selection, selectionArgs, null);
erase = (c.getCount() < 1);
} finally {
if (c != null) {
c.close();
}
}
}
// if it's not already saved, erase everything
if (erase) {
// delete media first
String instanceFolder = formController.getInstancePath()
.getParent();
Log.i(TAG, "attempting to delete: " + instanceFolder);
int images = MediaUtils
.deleteImagesInFolderFromMediaProvider(formController
.getInstancePath().getParentFile());
int audio = MediaUtils
.deleteAudioInFolderFromMediaProvider(formController
.getInstancePath().getParentFile());
int video = MediaUtils
.deleteVideoInFolderFromMediaProvider(formController
.getInstancePath().getParentFile());
Log.i(TAG, "removed from content providers: " + images
+ " image files, " + audio + " audio files," + " and "
+ video + " video files.");
File f = new File(instanceFolder);
if (f.exists() && f.isDirectory()) {
for (File del : f.listFiles()) {
Log.i(TAG, "deleting file: " + del.getAbsolutePath());
del.delete();
}
f.delete();
}
}
}
/**
* Confirm clear answer dialog
*/
private void createClearDialog(final QuestionWidget qw) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createClearDialog", "show",
qw.getPrompt().getIndex());
mAlertDialog = new AlertDialog.Builder(this).create();
mAlertDialog.setIcon(android.R.drawable.ic_dialog_info);
mAlertDialog.setTitle(getString(R.string.clear_answer_ask));
String question = qw.getPrompt().getLongText();
if (question == null) {
question = "";
}
if (question.length() > 50) {
question = question.substring(0, 50) + "...";
}
mAlertDialog.setMessage(getString(R.string.clearanswer_confirm,
question));
DialogInterface.OnClickListener quitListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE: // yes
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createClearDialog",
"clearAnswer", qw.getPrompt().getIndex());
clearAnswer(qw);
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
break;
case DialogInterface. BUTTON_NEGATIVE: // no
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "createClearDialog",
"cancel", qw.getPrompt().getIndex());
break;
}
}
};
mAlertDialog.setCancelable(false);
mAlertDialog
.setButton(getString(R.string.discard_answer), quitListener);
mAlertDialog.setButton2(getString(R.string.clear_answer_no),
quitListener);
showAlertDialog();
}
//
// /**
// * Creates and displays a dialog allowing the user to set the language for
// * the form.
// */
// private void createLanguageDialog() {
// Collect.getInstance().getActivityLogger()
// .logInstanceAction(this, "createLanguageDialog", "show");
// FormController formController = Collect.getInstance()
// .getFormController();
// final String[] languages = formController.getLanguages();
// int selected = -1;
// if (languages != null) {
// String language = formController.getLanguage();
// for (int i = 0; i < languages.length; i++) {
// if (language.equals(languages[i])) {
// selected = i;
// }
// }
// }
// mAlertDialog = new AlertDialog.Builder(this)
// .setSingleChoiceItems(languages, selected,
// new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog,
// int whichButton) {
// FormController formController = Collect
// .getInstance().getFormController();
// // Update the language in the content provider
// // when selecting a new
// // language
// ContentValues values = new ContentValues();
// values.put(FormsColumns.LANGUAGE,
// languages[whichButton]);
// String selection = FormsColumns.FORM_FILE_PATH
// + "=?";
// String selectArgs[] = { mFormPath };
// int updated = getContentResolver().update(
// FormsColumns.CONTENT_URI, values,
// selection, selectArgs);
// Log.i(TAG, "Updated language to: "
// + languages[whichButton] + " in "
// + updated + " rows");
//
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(
// this,
// "createLanguageDialog",
// "changeLanguage."
// + languages[whichButton]);
// formController
// .setLanguage(languages[whichButton]);
// dialog.dismiss();
// if (formController.currentPromptIsQuestion()) {
// saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
// }
// refreshCurrentView();
// }
// })
// .setTitle(getString(R.string.change_language))
// .setNegativeButton(getString(R.string.do_not_change),
// new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog,
// int whichButton) {
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this,
// "createLanguageDialog",
// "cancel");
// }
// }).create();
// showAlertDialog();
// }
/**
* We use Android's dialog management for loading/saving progress dialogs
*/
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
Log.e(TAG, "Creating PROGRESS_DIALOG");
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onCreateDialog.PROGRESS_DIALOG",
"show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener loadingButtonListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onCreateDialog.PROGRESS_DIALOG", "cancel");
dialog.dismiss();
mFormLoaderTask.setFormLoaderListener(null);
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
finish();
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(getString(R.string.loading_form));
mProgressDialog.setMessage(getString(R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setButton(getString(R.string.cancel_loading_form),
loadingButtonListener);
return mProgressDialog;
case SAVING_DIALOG:
Log.e(TAG, "Creating SAVING_DIALOG");
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this, "onCreateDialog.SAVING_DIALOG",
"show");
mProgressDialog = new ProgressDialog(this);
DialogInterface.OnClickListener cancelSavingButtonListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onCreateDialog.SAVING_DIALOG", "cancel");
dialog.dismiss();
cancelSaveToDiskTask();
}
};
mProgressDialog.setIcon(android.R.drawable.ic_dialog_info);
mProgressDialog.setTitle(getString(R.string.saving_form));
mProgressDialog.setMessage(getString(R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
Collect.getInstance()
.getActivityLogger()
.logInstanceAction(this,
"onCreateDialog.SAVING_DIALOG", "OnDismissListener");
cancelSaveToDiskTask();
}
});
return mProgressDialog;
}
return null;
}
private void cancelSaveToDiskTask() {
synchronized (saveDialogLock) {
mSaveToDiskTask.setFormSavedListener(null);
boolean cancelled = mSaveToDiskTask.cancel(true);
Log.w(TAG, "Cancelled SaveToDiskTask! (" + cancelled + ")");
mSaveToDiskTask = null;
}
}
/**
* Dismiss any showing dialogs that we manually manage.
*/
private void dismissDialogs() {
Log.e(TAG, "Dismiss dialogs");
if (mAlertDialog != null && mAlertDialog.isShowing()) {
mAlertDialog.dismiss();
}
}
@Override
protected void onPause() {
FormController formController = Collect.getInstance()
.getFormController();
dismissDialogs();
// make sure we're not already saving to disk. if we are, currentPrompt
// is getting constantly updated
if (mSaveToDiskTask == null
|| mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
if (mCurrentView != null && formController != null
&& formController.currentPromptIsQuestion()) {
saveAnswersForCurrentScreen(DO_NOT_EVALUATE_CONSTRAINTS);
}
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (mErrorMessage != null) {
if (mAlertDialog != null && !mAlertDialog.isShowing()) {
createErrorDialog(mErrorMessage, EXIT);
} else {
return;
}
}
FormController formController = Collect.getInstance().getFormController();
Collect.getInstance().getActivityLogger().open();
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(this);
if (formController == null
&& mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
FormController fec = mFormLoaderTask.getFormController();
if (fec != null) {
loadingComplete(mFormLoaderTask);
} else {
dismissDialog(PROGRESS_DIALOG);
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
// there is no formController -- fire MainMenu activity?
startActivity(new Intent(this, MainMenuActivity.class));
}
}
} else {
if (formController == null) {
// there is no formController -- fire MainMenu activity?
startActivity(new Intent(this, MainMenuActivity.class));
return;
}
// else {
// refreshCurrentView();
// }
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(this);
}
// only check the buttons if it's enabled in preferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String navigation = sharedPreferences.getString(
PreferencesActivity.KEY_NAVIGATION,
PreferencesActivity.KEY_NAVIGATION);
Boolean showButtons = false;
if (navigation.contains(PreferencesActivity.NAVIGATION_BUTTONS)) {
showButtons = true;
}
}
//
// @Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// switch (keyCode) {
// case KeyEvent.KEYCODE_BACK:
// Collect.getInstance().getActivityLogger()
// .logInstanceAction(this, "onKeyDown.KEYCODE_BACK", "quit");
// createQuitDialog();
// return true;
// case KeyEvent.KEYCODE_DPAD_RIGHT:
// if (event.isAltPressed() && !mBeenSwiped) {
// mBeenSwiped = true;
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this,
// "onKeyDown.KEYCODE_DPAD_RIGHT", "showNext");
// showNextView();
// return true;
// }
// break;
// case KeyEvent.KEYCODE_DPAD_LEFT:
// if (event.isAltPressed() && !mBeenSwiped) {
// mBeenSwiped = true;
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this, "onKeyDown.KEYCODE_DPAD_LEFT",
// "showPrevious");
// showPreviousView();
// return true;
// }
// break;
// }
// return super.onKeyDown(keyCode, event);
// }
@Override
protected void onDestroy() {
if (mFormLoaderTask != null) {
mFormLoaderTask.setFormLoaderListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
// but only if it's done, otherwise the thread never returns
if (mFormLoaderTask.getStatus() == AsyncTask.Status.FINISHED) {
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
}
}
if (mSaveToDiskTask != null) {
mSaveToDiskTask.setFormSavedListener(null);
// We have to call cancel to terminate the thread, otherwise it
// lives on and retains the FEC in memory.
if (mSaveToDiskTask.getStatus() == AsyncTask.Status.FINISHED) {
mSaveToDiskTask.cancel(true);
mSaveToDiskTask = null;
}
}
super.onDestroy();
}
//
// private int mAnimationCompletionSet = 0;
//
// private void afterAllAnimations() {
// Log.i(TAG, "afterAllAnimations");
// if (mStaleView != null) {
// if (mStaleView instanceof ODKView) {
// // http://code.google.com/p/android/issues/detail?id=8488
// ((ODKView) mStaleView).recycleDrawables();
// }
// mStaleView = null;
// }
//
// if (mCurrentView instanceof ODKView) {
// ((ODKView) mCurrentView).setFocus(this);
// }
// mBeenSwiped = false;
// }
//
// @Override
// public void onAnimationEnd(Animation animation) {
// Log.i(TAG, "onAnimationEnd "
// + ((animation == mInAnimation) ? "in"
// : ((animation == mOutAnimation) ? "out" : "other")));
// if (mInAnimation == animation) {
// mAnimationCompletionSet |= 1;
// } else if (mOutAnimation == animation) {
// mAnimationCompletionSet |= 2;
// } else {
// Log.e(TAG, "Unexpected animation");
// }
//
// if (mAnimationCompletionSet == 3) {
// this.afterAllAnimations();
// }
// }
//
// @Override
// public void onAnimationRepeat(Animation animation) {
// // Added by AnimationListener interface.
// Log.i(TAG, "onAnimationRepeat "
// + ((animation == mInAnimation) ? "in"
// : ((animation == mOutAnimation) ? "out" : "other")));
// }
//
// @Override
// public void onAnimationStart(Animation animation) {
// // Added by AnimationListener interface.
// Log.i(TAG, "onAnimationStart "
// + ((animation == mInAnimation) ? "in"
// : ((animation == mOutAnimation) ? "out" : "other")));
// }
/**
* loadingComplete() is called by FormLoaderTask once it has finished
* loading a form.
*/
@Override
public void loadingComplete(FormLoaderTask task) {
dismissDialog(PROGRESS_DIALOG);
FormController formController = task.getFormController();
boolean pendingActivityResult = task.hasPendingActivityResult();
boolean hasUsedSavepoint = task.hasUsedSavepoint();
int requestCode = task.getRequestCode(); // these are bogus if
// pendingActivityResult is
// false
int resultCode = task.getResultCode();
Intent intent = task.getIntent();
mFormLoaderTask.setFormLoaderListener(null);
FormLoaderTask t = mFormLoaderTask;
mFormLoaderTask = null;
t.cancel(true);
t.destroy();
Collect.getInstance().setFormController(formController);
CompatibilityUtils.invalidateOptionsMenu(this);
Collect.getInstance().setExternalDataManager(task.getExternalDataManager());
// Set the language if one has already been set in the past
String[] languageTest = formController.getLanguages();
if (languageTest != null) {
String defaultLanguage = formController.getLanguage();
String newLanguage = "";
String selection = FormsColumns.FORM_FILE_PATH + "=?";
String selectArgs[] = { mFormPath };
Cursor c = null;
try {
c = getContentResolver().query(FormsColumns.CONTENT_URI, null,
selection, selectArgs, null);
if (c.getCount() == 1) {
c.moveToFirst();
newLanguage = c.getString(c
.getColumnIndex(FormsColumns.LANGUAGE));
}
} finally {
if (c != null) {
c.close();
}
}
// if somehow we end up with a bad language, set it to the default
try {
formController.setLanguage(newLanguage);
} catch (Exception e) {
formController.setLanguage(defaultLanguage);
}
}
if (pendingActivityResult) {
// set the current view to whatever group we were at...
populateViews((Preset) getIntent().getParcelableExtra("fields"));
// process the pending activity request...
onActivityResult(requestCode, resultCode, intent);
return;
}
//
// // it can be a normal flow for a pending activity result to restore from
// // a savepoint
// // (the call flow handled by the above if statement). For all other use
// // cases, the
// // user should be notified, as it means they wandered off doing other
// // things then
// // returned to ODK Collect and chose Edit Saved Form, but that the
// // savepoint for that
// // form is newer than the last saved version of their form data.
// if (hasUsedSavepoint) {
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(FormEntryActivity.this,
// getString(R.string.savepoint_used),
// Toast.LENGTH_LONG).show();
// }
// });
// }
// Set saved answer path
if (formController.getInstancePath() == null) {
// Create new answer folder.
String time = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss",
Locale.ENGLISH).format(Calendar.getInstance().getTime());
String file = mFormPath.substring(mFormPath.lastIndexOf('/') + 1,
mFormPath.lastIndexOf('.'));
String path = Collect.getInstance().getInstancesPath() + File.separator + file + "_"
+ time;
if (FileUtils.createFolder(path)) {
formController.setInstancePath(new File(path + File.separator
+ file + "_" + time + ".xml"));
}
}
// else {
// Intent reqIntent = getIntent();
// boolean showFirst = reqIntent.getBooleanExtra("start", false);
//
// if (!showFirst) {
// // we've just loaded a saved form, so start in the hierarchy
// // view
// Intent i = new Intent(this, FormHierarchyActivity.class);
// startActivity(i);
// return; // so we don't show the intro screen before jumping to
// // the hierarchy
// }
// }
Patient patient = getIntent().getParcelableExtra("patient");
if (patient != null) {
setTitle(patient.id + ": " + patient.givenName + " " + patient.familyName);
} else {
setTitle(formController.getFormTitle());
}
populateViews((Preset) getIntent().getParcelableExtra("fields"));
}
/**
* called by the FormLoaderTask if something goes wrong.
*/
@Override
public void loadingError(String errorMsg) {
dismissDialog(PROGRESS_DIALOG);
if (errorMsg != null) {
createErrorDialog(errorMsg, EXIT);
} else {
createErrorDialog(getString(R.string.parse_error), EXIT);
}
}
/**
* Called by SavetoDiskTask if everything saves correctly.
*/
@Override
public void savingComplete(SaveResult saveResult) {
dismissDialog(SAVING_DIALOG);
int saveStatus = saveResult.getSaveResult();
switch (saveStatus) {
case SaveToDiskTask.SAVED:
// Toast.makeText(this, getString(R.string.data_saved_ok),
// Toast.LENGTH_SHORT).show();
sendSavedBroadcast();
break;
case SaveToDiskTask.SAVED_AND_EXIT:
// Toast.makeText(this, getString(R.string.data_saved_ok),
// Toast.LENGTH_SHORT).show();
sendSavedBroadcast();
finishReturnInstance();
break;
case SaveToDiskTask.SAVE_ERROR:
String message;
if (saveResult.getSaveErrorMessage() != null) {
message = getString(R.string.data_saved_error) + ": " + saveResult.getSaveErrorMessage();
} else {
message = getString(R.string.data_saved_error);
}
Toast.makeText(this, message,
Toast.LENGTH_LONG).show();
break;
case FormEntryController.ANSWER_CONSTRAINT_VIOLATED:
case FormEntryController.ANSWER_REQUIRED_BUT_EMPTY:
// refreshCurrentView();
// get constraint behavior preference value with appropriate default
String constraint_behavior = PreferenceManager.getDefaultSharedPreferences(this)
.getString(PreferencesActivity.KEY_CONSTRAINT_BEHAVIOR,
PreferencesActivity.CONSTRAINT_BEHAVIOR_DEFAULT);
//
// // an answer constraint was violated, so we need to display the proper toast(s)
// // if constraint behavior is on_swipe, this will happen if we do a 'swipe' to the next question
// if (constraint_behavior.equals(PreferencesActivity.CONSTRAINT_BEHAVIOR_ON_SWIPE))
// next();
// // otherwise, we can get the proper toast(s) by saving with constraint check
// else
// saveAnswersForCurrentScreen(EVALUATE_CONSTRAINTS);
break;
}
}
@Override
public void onProgressStep(String stepMessage) {
this.stepMessage = stepMessage;
if (mProgressDialog != null) {
mProgressDialog.setMessage(getString(R.string.please_wait) + "\n\n" + stepMessage);
}
}
/**
* Attempts to save an answer to the specified index.
*
* @param answer
* @param index
* @param evaluateConstraints
* @return status as determined in FormEntryController
*/
public int saveAnswer(IAnswerData answer, FormIndex index,
boolean evaluateConstraints) throws JavaRosaException {
FormController formController = Collect.getInstance()
.getFormController();
if (evaluateConstraints) {
return formController.answerQuestion(index, answer);
} else {
formController.saveAnswer(index, answer);
return FormEntryController.ANSWER_OK;
}
}
// /**
// * Checks the database to determine if the current instance being edited has
// * already been 'marked completed'. A form can be 'unmarked' complete and
// * then resaved.
// *
// * @return true if form has been marked completed, false otherwise.
// */
// private boolean isInstanceComplete(boolean end) {
// FormController formController = Collect.getInstance()
// .getFormController();
// // default to false if we're mid form
// boolean complete = false;
//
// // if we're at the end of the form, then check the preferences
// if (end) {
// // First get the value from the preferences
// SharedPreferences sharedPreferences = PreferenceManager
// .getDefaultSharedPreferences(this);
// complete = sharedPreferences.getBoolean(
// PreferencesActivity.KEY_COMPLETED_DEFAULT, true);
// }
//
// // Then see if we've already marked this form as complete before
// String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
// String[] selectionArgs = { formController.getInstancePath()
// .getAbsolutePath() };
// Cursor c = null;
// try {
// c = getContentResolver().query(InstanceColumns.CONTENT_URI, null,
// selection, selectionArgs, null);
// if (c != null && c.getCount() > 0) {
// c.moveToFirst();
// String status = c.getString(c
// .getColumnIndex(InstanceColumns.STATUS));
// if (InstanceProviderAPI.STATUS_COMPLETE.compareTo(status) == 0) {
// complete = true;
// }
// }
// } finally {
// if (c != null) {
// c.close();
// }
// }
// return complete;
// }
//
// public void next() {
// if (!mBeenSwiped) {
// mBeenSwiped = true;
// showNextView();
// }
// }
/**
* Returns the instance that was just filled out to the calling activity, if
* requested.
*/
private void finishReturnInstance() {
FormController formController = Collect.getInstance()
.getFormController();
String action = getIntent().getAction();
if (Intent.ACTION_PICK.equals(action)
|| Intent.ACTION_EDIT.equals(action)) {
// caller is waiting on a picked form
String selection = InstanceColumns.INSTANCE_FILE_PATH + "=?";
String[] selectionArgs = { formController.getInstancePath()
.getAbsolutePath() };
Cursor c = null;
try {
c = getContentResolver().query(InstanceColumns.CONTENT_URI,
null, selection, selectionArgs, null);
if (c.getCount() > 0) {
// should only be one...
c.moveToFirst();
String id = c.getString(c
.getColumnIndex(InstanceColumns._ID));
Uri instance = Uri.withAppendedPath(
InstanceColumns.CONTENT_URI, id);
setResult(RESULT_OK, new Intent().setData(instance));
}
} finally {
if (c != null) {
c.close();
}
}
}
finish();
}
//
// @Override
// public boolean onDown(MotionEvent e) {
// return false;
// }
//
// @Override
// public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
// float velocityY) {
// // only check the swipe if it's enabled in preferences
// SharedPreferences sharedPreferences = PreferenceManager
// .getDefaultSharedPreferences(this);
// String navigation = sharedPreferences.getString(
// PreferencesActivity.KEY_NAVIGATION,
// PreferencesActivity.NAVIGATION_SWIPE);
// Boolean doSwipe = false;
// if (navigation.contains(PreferencesActivity.NAVIGATION_SWIPE)) {
// doSwipe = true;
// }
// if (doSwipe) {
// // Looks for user swipes. If the user has swiped, move to the
// // appropriate screen.
//
// // for all screens a swipe is left/right of at least
// // .25" and up/down of less than .25"
// // OR left/right of > .5"
// DisplayMetrics dm = new DisplayMetrics();
// getWindowManager().getDefaultDisplay().getMetrics(dm);
// int xPixelLimit = (int) (dm.xdpi * .25);
// int yPixelLimit = (int) (dm.ydpi * .25);
//
// if (mCurrentView instanceof ODKView) {
// if (((ODKView) mCurrentView).suppressFlingGesture(e1, e2,
// velocityX, velocityY)) {
// return false;
// }
// }
//
// if (mBeenSwiped) {
// return false;
// }
//
// if ((Math.abs(e1.getX() - e2.getX()) > xPixelLimit && Math.abs(e1
// .getY() - e2.getY()) < yPixelLimit)
// || Math.abs(e1.getX() - e2.getX()) > xPixelLimit * 2) {
// mBeenSwiped = true;
// if (velocityX > 0) {
// if (e1.getX() > e2.getX()) {
// Log.e(TAG,
// "showNextView VelocityX is bogus! " + e1.getX()
// + " > " + e2.getX());
// Collect.getInstance().getActivityLogger()
// .logInstanceAction(this, "onFling", "showNext");
// showNextView();
// } else {
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this, "onFling",
// "showPrevious");
// showPreviousView();
// }
// } else {
// if (e1.getX() < e2.getX()) {
// Log.e(TAG,
// "showPreviousView VelocityX is bogus! "
// + e1.getX() + " < " + e2.getX());
// Collect.getInstance()
// .getActivityLogger()
// .logInstanceAction(this, "onFling",
// "showPrevious");
// showPreviousView();
// } else {
// Collect.getInstance().getActivityLogger()
// .logInstanceAction(this, "onFling", "showNext");
// showNextView();
// }
// }
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void onLongPress(MotionEvent e) {
// }
//
// @Override
// public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
// float distanceY) {
// // The onFling() captures the 'up' event so our view thinks it gets long
// // pressed.
// // We don't wnat that, so cancel it.
// if (mCurrentView != null) {
// mCurrentView.cancelLongPress();
// }
// return false;
// }
//
// @Override
// public void onShowPress(MotionEvent e) {
// }
//
// @Override
// public boolean onSingleTapUp(MotionEvent e) {
// return false;
// }
//
// @Override
// public void advance() {
// next();
// }
public static void hideKeyboard(Context context, View view) {
InputMethodManager inputMethodManager =
(InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
@Override
protected void onStart() {
super.onStart();
Collect.getInstance().getActivityLogger().logOnStart(this);
}
@Override
protected void onStop() {
Collect.getInstance().getActivityLogger().logOnStop(this);
super.onStop();
}
private void sendSavedBroadcast() {
Intent i = new Intent();
i.setAction("org.odk.collect.android.FormSaved");
this.sendBroadcast(i);
}
@Override
public void onSavePointError(String errorMessage) {
if (errorMessage != null && errorMessage.trim().length() > 0) {
Toast.makeText(this, getString(R.string.save_point_error, errorMessage), Toast.LENGTH_LONG).show();
}
}
private void showAlertDialog() {
if (mAlertDialog == null) {
return;
}
mAlertDialog.show();
// Increase text sizes in dialog, which must be done after the alert is shown when not
// specifying a custom alert dialog theme or layout.
TextView[] views = {
(TextView) mAlertDialog.findViewById(android.R.id.message),
mAlertDialog.getButton(DialogInterface.BUTTON_NEGATIVE),
mAlertDialog.getButton(DialogInterface.BUTTON_NEUTRAL),
mAlertDialog.getButton(DialogInterface.BUTTON_POSITIVE)
};
for (TextView view : views) {
if (view != null) {
view.setTextSize(ALERT_DIALOG_TEXT_SIZE);
view.setPadding(
ALERT_DIALOG_PADDING, ALERT_DIALOG_PADDING,
ALERT_DIALOG_PADDING, ALERT_DIALOG_PADDING);
}
}
// Title should be bigger than message and button text.
int alertTitleResource = getResources().getIdentifier("alertTitle", "id", "android");
TextView title = (TextView)mAlertDialog.findViewById(alertTitleResource);
if (title != null) {
title.setTextSize(ALERT_DIALOG_TITLE_TEXT_SIZE);
title.setPadding(
ALERT_DIALOG_PADDING, ALERT_DIALOG_PADDING,
ALERT_DIALOG_PADDING, ALERT_DIALOG_PADDING);
}
}
/**
* Returns true iff no values in the form have changed from the
* pre-populated defaults. This will return true even if a value
* has been given and subsequently cleared.
*
* @return true iff no form values have changed, false otherwise
*/
private boolean allContentsUnchanged() {
Map<FormIndex, IAnswerData> answers = getAnswers();
// Compare each individual answer to the original answers (after
// pre-population), returning false for any unmatched answer.
for (Map.Entry<FormIndex, IAnswerData> entry : answers.entrySet()) {
// Double-check the key even exists before continuing to avoid
// a NullPointerException, but this should never happen in
// practice.
if (!mOriginalAnswerData.containsKey(entry.getKey())) {
return false;
}
// Check for differences based on the display text of answers. This
// has the (rare) downside that different values may be considered
// equal if they have the same display text, but equals() is not
// reliable for IAnswerData objects.
String newText = getDisplayText(entry.getValue());
String oldText = getDisplayText(mOriginalAnswerData.get(entry.getKey()));
if (!equalOrBothNull(newText, oldText)) {
return false;
}
}
return true;
}
/**
* Retrieves the displayed text for an {@link IAnswerData} object.
*
* @param data the field
* @return the displayed text, or null if the data is null
*/
@Nullable
private String getDisplayText(@Nullable IAnswerData data) {
if (data == null) {
return null;
}
return data.getDisplayText();
}
/**
* Checks if the given objects are both equal or both null (equivalent to Objects.equals,
* but without the requirement for API level 19).
* @param obj1 the first object to compare
* @param obj2 the second object to compare
* @return true if obj1 == obj2 or obj1 and obj2 are both null, false otherwise
*/
private boolean equalOrBothNull(Object obj1, Object obj2) {
// Check if the Objects refer to the same Object or are both null.
if (obj1 == obj2) {
return true;
}
// If either Object is null, then the two cannot be equal.
if (obj1 == null || obj2 == null) {
return false;
}
return obj1.equals(obj2);
}
}
| apache-2.0 |
openengsb-domcon/openengsb-connector-promreport | src/test/java/org/openengsb/connector/promreport/internal/events/TestDomainEndEvent.java | 980 | /**
* Licensed to the Austrian Association for Software Tool Integration (AASTI)
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. The AASTI 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.openengsb.connector.promreport.internal.events;
import org.openengsb.core.api.Event;
public class TestDomainEndEvent extends Event {
}
| apache-2.0 |
RyanTech/ubivearound_2 | src/com/ubive/ui/MMoreActivity.java | 9098 | package com.ubive.ui;
import java.io.IOException;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.ubive.BaseActivity;
import com.ubive.Global;
import com.ubive.R;
import com.ubive.biz.FarmBiz;
import com.ubive.entity.UpdateInfo;
import com.ubive.service.DownLoadApkService;
import com.ubive.ui.option.DisplayOption;
import com.ubive.util.ExitAppUtil;
import com.ubive.util.Logger;
public class MMoreActivity extends BaseActivity implements OnClickListener {
private static final String TAG = "SettingCenter";
ImageView ivNeedUpdate;
RelativeLayout rlUser;
RelativeLayout rlShare;
RelativeLayout rlScore;
RelativeLayout llChecknew;
RelativeLayout llAboutme;
TextView tvVersion,tvUsername;
FarmBiz farmBiz;
int flagProbRight = Global.SETTING_EXIT;
private UpdateInfo updateInfo = null;
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
hiderLoading();
switch (msg.what) {
case Global.NEED_NOT_UPDATE:
showToast(R.string.version_no_need);
initUpdateFlag(false);
break;
case Global.NEED_UPDATE:
initUpdateFlag(true);
flagProbRight = Global.SETTING_UPDATE;
String info = updateInfo.description;
for (String string:updateInfo.newfeature) {
info+=string;
}
showBaseDialog(R.string.update_title, info, R.string.update, R.string.cancle);
btDialogLeft.setOnClickListener(MMoreActivity.this);
btDialogRigth.setOnClickListener(MMoreActivity.this);
break;
case Global.NET_UN_CONN:
showToast(R.string.problem_net_un_conn);
break;
case Global.NET_PROBLEM:
showToast(R.string.problem_check_new_fail);
break;
default:
break;
}
}
};
@Override
public void setUpView() {
tvTitle = (TextView) findViewById(R.id.tv_model_title);
tvTitle.setText(R.string.main_tag_more);
ivNeedUpdate = (ImageView) findViewById(R.id.iv_need_update);
rlUser = (RelativeLayout) findViewById(R.id.ll_setfarm_head);
rlShare = (RelativeLayout) findViewById(R.id.ll_setfarm_tel);
rlScore = (RelativeLayout) findViewById(R.id.ll_set_score);
llChecknew = (RelativeLayout) findViewById(R.id.ll_setfarm_name);
llAboutme = (RelativeLayout) findViewById(R.id.ll_setfarm_shop);
tvVersion = (TextView) findViewById(R.id.tv_varsion);
tvUsername = (TextView) findViewById(R.id.tv_name);
boolean needUpdata = sp.getBoolean("needUpdate", false);
initUpdateFlag(needUpdata);
farmBiz = new FarmBiz(this);
}
private void initUpdateFlag(boolean needUpdata) {
if(needUpdata){
ivNeedUpdate.setVisibility(View.VISIBLE);
tvVersion.setText("");
}else{
ivNeedUpdate.setVisibility(View.INVISIBLE);
tvVersion.setText(getVersion());
}
}
@Override
public void addListener() {
rlUser.setOnClickListener(this);
rlShare.setOnClickListener(this);
rlScore.setOnClickListener(this);
llChecknew.setOnClickListener(this);
llAboutme.setOnClickListener(this);
}
@Override
public void fillData() {
int userid = sp.getInt("userid", Global.DEFAULT_USERID);
if(userid!=Global.DEFAULT_USERID){
String name = sp.getString("username", "");
if (!TextUtils.isEmpty(name)) {
if (name.length() > 15) {
tvUsername.setText(name.substring(0, 14) + "...");
} else {
tvUsername.setText(name);
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main_tab_setting);
super.onCreate(savedInstanceState);
}
private void showExitDialog(int resInfoId) {
showBaseDialog(R.string.point, resInfoId,R.string.confirm,R.string.cancle);
btDialogLeft.setOnClickListener(this);
btDialogRigth.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_dialog_left:
baseDialog.dismiss();
switch (flagProbRight) {
case Global.SETTING_EXIT:
ExitAppUtil.exitApp(this);
break;
case Global.SETTING_UPDATE:
showToast(R.string.point_loading_apk);
loadApkFile();
break;
default:
break;
}
break;
case R.id.bt_dialog_right:
baseDialog.dismiss();
break;
case R.id.ll_setfarm_head://¸öÈËÉèÖÃÐÅÏ¢½çÃæ
goActivityAfterValid();
break;
case R.id.ll_setfarm_tel://·ÖÏí
share();
break;
case R.id.ll_set_score://·ÖÏí
goScore();
break;
case R.id.ll_setfarm_name://¼ì²é¸üÐÂ
if(!isDoing()){
checkVersion();
}
break;
case R.id.ll_setfarm_shop:
Bundle extra = new Bundle();
extra.putString("version", getVersion());
goTo(this, AboutUbiveActivity.class, extra);
this.getParent().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
break;
default:
break;
}
}
private void goScore() {
Uri uri = Uri.parse("market://details?id=" + this.getPackageName());
Intent intent = new Intent(Intent.ACTION_VIEW,uri);
try{
startActivity(intent);
this.getParent().overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_top);
}catch(ActivityNotFoundException e){
showToast(R.string.problem_lunch_appstore_fail);
}
}
private void goActivityAfterValid() {
int userid = sp.getInt("userid", Global.DEFAULT_USERID);
if(userid!=Global.DEFAULT_USERID){
Intent intent = new Intent(this,SetUserInfoActivity.class);
startActivityForResult(intent, 100);
this.getParent().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
}else{
Intent intent = new Intent(this, LoginActivity.class);
intent.putExtra("fromWhat", Global.RLNAV_FROM_SETTING);
startActivityForResult(intent, 100);
this.getParent().overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_top);
}
}
private void loadApkFile(){
Intent intent = new Intent(this,DownLoadApkService.class);
intent.putExtra("url",updateInfo.apkurl);
startService(intent);
}
private void share() {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "·ÖÏí");
String info = getResources().getString(R.string.setting_share);
shareIntent.putExtra(Intent.EXTRA_TEXT,info);
startActivity(shareIntent);
this.getParent().overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_top);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
flagProbRight = Global.SETTING_EXIT;
showExitDialog(R.string.dialog_affirm_exit_ubive);
return true;
}
return false;
}
public String getVersion(){
PackageManager manager = getPackageManager();
try {
PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
return info.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
return "1.0.0";
}
}
private void checkVersion(){
if(!isNetConn()){//ÍøÂçÎÞÁ¬½Ó
handler.sendEmptyMessage(Global.NET_UN_CONN);
return;
}
final String version = getVersion();
new AsyncTask<Integer, Void, UpdateInfo>() {
@Override
protected void onPostExecute(UpdateInfo result) {
hiderLoading();
if(result == null){
showToast(R.string.problem_check_new_fail);
return;
}
float serverVersion = Float.valueOf(result.version.replace(".", ""));
float appVersion = Float.valueOf(version.replace(".",""));
if(serverVersion>appVersion){
handler.sendEmptyMessage(Global.NEED_UPDATE);
}else{
handler.sendEmptyMessage(Global.NEED_NOT_UPDATE);
}
super.onPostExecute(result);
}
@Override
protected void onPreExecute() {
showLoading(R.string.loading_check_new);
super.onPreExecute();
}
@Override
protected UpdateInfo doInBackground(Integer... params) {
FarmBiz farmBiz = new FarmBiz(MMoreActivity.this);
try {
updateInfo = farmBiz.getUpdateInfo();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return updateInfo;
}
}.execute(0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (resultCode) {
case Global.RET:
break;
case Global.RLNAV_FROM_SETTING:
goActivityAfterValid();
break;
default:
fillData();
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| apache-2.0 |
ov3rflow/eFaps-Kernel | src/main/java/org/efaps/admin/datamodel/IEnum.java | 902 | /*
* Copyright 2003 - 2013 The eFaps Team
*
* 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.
*
* Revision: $Rev$
* Last Changed: $Date$
* Last Changed By: $Author$
*/
package org.efaps.admin.datamodel;
/**
* TODO comment!
*
* @author The eFaps Team
* @version $Id$
*/
public interface IEnum
{
/**
* @return integer value of the Enum
*/
int getInt();
}
| apache-2.0 |
claudiu-stanciu/kylo | services/feed-manager-service/feed-manager-core/src/main/java/com/thinkbiganalytics/feedmgr/service/feed/FeedPreconditionService.java | 5455 | /**
*
*/
package com.thinkbiganalytics.feedmgr.service.feed;
/*-
* #%L
* thinkbig-feed-manager-core
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.thinkbiganalytics.metadata.api.MetadataAccess;
import com.thinkbiganalytics.metadata.api.event.MetadataEventListener;
import com.thinkbiganalytics.metadata.api.event.MetadataEventService;
import com.thinkbiganalytics.metadata.api.event.feed.FeedOperationStatusEvent;
import com.thinkbiganalytics.metadata.api.event.feed.OperationStatus;
import com.thinkbiganalytics.metadata.api.event.feed.PreconditionTriggerEvent;
import com.thinkbiganalytics.metadata.api.feed.Feed;
import com.thinkbiganalytics.metadata.api.feed.FeedPrecondition;
import com.thinkbiganalytics.metadata.api.feed.FeedProvider;
import com.thinkbiganalytics.metadata.api.op.FeedOperation;
import com.thinkbiganalytics.metadata.api.sla.FeedExecutedSinceFeed;
import com.thinkbiganalytics.metadata.sla.api.AssessmentResult;
import com.thinkbiganalytics.metadata.sla.api.Metric;
import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement;
import com.thinkbiganalytics.metadata.sla.api.ServiceLevelAssessment;
import com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAssessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
/**
* Service for assessing {@link FeedPrecondition}
*/
public class FeedPreconditionService {
private static final Logger log = LoggerFactory.getLogger(FeedPreconditionService.class);
@Inject
private ServiceLevelAssessor assessor;
@Inject
private FeedProvider feedProvider;
@Inject
private MetadataAccess metadata;
@Inject
private MetadataEventService eventService;
private FeedOperationListener listener = new FeedOperationListener();
@PostConstruct
public void addEventListener() {
this.eventService.addListener(this.listener);
}
@PreDestroy
public void removeEventListener() {
this.eventService.removeListener(this.listener);
}
public ServiceLevelAssessment assess(FeedPrecondition precond) {
ServiceLevelAgreement sla = precond.getAgreement();
return this.assessor.assess(sla);
}
private void checkPrecondition(Feed feed, OperationStatus operationStatus) {
FeedPrecondition precond = feed.getPrecondition();
if (precond != null) {
log.debug("Checking precondition of feed: {} ({})", feed.getName(), feed.getId());
ServiceLevelAgreement sla = precond.getAgreement();
boolean isAssess = sla.getAllMetrics().stream()
.anyMatch(metric -> isMetricDependentOnStatus(metric, operationStatus));
if (isAssess) {
ServiceLevelAssessment assessment = this.assessor.assess(sla);
if (assessment.getResult() == AssessmentResult.SUCCESS) {
log.info("Firing precondition trigger event for feed:{} ({})", feed.getName(), feed.getId());
this.eventService.notify(new PreconditionTriggerEvent(feed.getId()));
}
} else {
log.debug("Feed {}.{} does not depend on feed {}", feed.getCategory(), feed.getName(), operationStatus.getFeedName());
}
}
}
/**
* To avoid feeds being triggered by feeds they do not depend on
*/
private boolean isMetricDependentOnStatus(Metric metric, OperationStatus operationStatus) {
return !(metric instanceof FeedExecutedSinceFeed) || operationStatus.getFeedName().equalsIgnoreCase(((FeedExecutedSinceFeed) metric).getCategoryAndFeed());
}
private class FeedOperationListener implements MetadataEventListener<FeedOperationStatusEvent> {
@Override
public void notify(FeedOperationStatusEvent event) {
FeedOperation.State state = event.getData().getState();
// TODO as precondition check criteria are not implemented yet,
// check all preconditions of feeds that have them.
if (state == FeedOperation.State.SUCCESS) {
metadata.read(() -> {
for (Feed feed : feedProvider.findPreconditionedFeeds()) {
// Don't check the precondition of the feed that that generated this change event.
// TODO: this might not be the correct behavior but none of our current metrics
// need to be assessed when the feed itself containing the precondition has changed state.
if (!feed.getQualifiedName().equals(event.getData().getFeedName())) {
checkPrecondition(feed, event.getData());
}
}
}, MetadataAccess.SERVICE);
}
}
}
}
| apache-2.0 |
charles-cooper/idylfin | src/com/idylwood/yahoo/YahooFinance.java | 16581 | /*
* ====================================================
* Copyright (C) 2013 by Idylwood Technologies, LLC. All rights reserved.
*
* Developed at Idylwood Technologies, LLC.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* The License should have been distributed to you with the source tree.
* If not, it can be found at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Charles Cooper
* Date: 2013
* ====================================================
*/
package com.idylwood.yahoo;
import java.io.*;
import java.util.*;
import org.apache.commons.math3.stat.regression.*;
import de.erichseifert.gral.data.*;
import de.erichseifert.gral.data.filters.*;
import de.erichseifert.gral.data.filters.Filter.Mode;
import au.com.bytecode.opencsv.CSVReader;
import com.idylwood.*;
import com.idylwood.utils.FinUtils;
import com.idylwood.utils.MathUtils;
// Class intended to provide wrapper to Yahoo Finance API
public final class YahooFinance
{
final static long TwentyFourHours = 1000L * 60 * 60 * 24; // millis in day
final static public Date DEFAULT_START_DATE = new Date(20070101);
final Map<String,HistTable> mTables = new HashMap<String,HistTable>();
final Map<String,DivTable> mDividends = new HashMap<String,DivTable>();
final Map<String,SplitTable> mSplits = new HashMap<String,SplitTable>();
final Map<String,DivSplitTable> mDivSplits = new HashMap<String,DivSplitTable>();
final Map<String,Quote> mQuotes = new HashMap<String,Quote>();
// Surprisingly useful class which contains two doubles and a date.
// TODO refactor to extend Date
public static class Pair {
public Date date;
public double first;
public double second;
public Pair() {}
public Pair(Date date, double first, double second) {
this.date = date; this.first = first; this.second = second;
}
// copy constructor
public Pair(Pair other) {
this(other.date,other.first,other.second);
}
@Override public String toString() { return date.toString() + ","+first +","+ second; }
}
public static class Single extends Date {
public double data;
public Single(Date date) { super(date); }
public Single(Date date, double data) { this(date); this.data = data; }
// copy constructor
public Single(Single other) { this((Date)other,other.data); }
}
// TODO refactor to extend ArrayList
public static class DivTable
{
public final String symbol;
public final long dateAccessed; // in millis
public final List<Single> data;
public final boolean splitAdjusted;
public DivTable(final String symbol,
final long dateAccessed,
final boolean splitAdjusted,
final List<Single> data)
{
this.symbol = symbol; this.dateAccessed = dateAccessed;
this.data = data; this.splitAdjusted = splitAdjusted;
}
}
// TODO refactor to extend ArrayList
public static class SplitTable
{
// TODO refactor so member variables are final
public String symbol;
public long dateAccessed; // in millis
public List<Single> data; // 1:10 == 0.1, 3:2 == 1.5, etc.
// TODO this is not thread safe! make the data structure immutable so that it is
public List<Single> RunningRatios(Date startDate)
{
// Allocate new stuff all over the place! So glad this isn't C++.
List<Single> ret = new ArrayList<Single>(this.data.size()+1);
ret.add(new Single(startDate,1)); // start the ratio at zero.
for (int i = 0; i < this.data.size(); ++i)
{
Single s = new Single(this.data.get(i));
// recall that ret has an extra element at the beginning
// so the indices are off by one.
s.data *= ret.get(i).data;
ret.add(s);
}
return ret;
}
}
// TODO refactor so this is private
public static class DivSplitTable extends ArrayList<Pair>
{
public DivSplitTable(int size) { super(size); }
public DivSplitTable() { super(); }
String symbol;
long dateAccessed;
Date startDate;
Date endDate;
int totalSize;
int status;
// TODO refactor so this is a method in an abstract Table class
public DivSplitTable SubTable(final Date startDate, final Date endDate)
{
DivSplitTable ret = new DivSplitTable(this.size());
for (Pair row : this)
if (row.date.compareTo(startDate)>=0 && row.date.compareTo(endDate)<= 0)
ret.add(new Pair(row)); // hammering malloc, baby
ret.symbol = this.symbol; ret.dateAccessed = this.dateAccessed;
ret.totalSize = -1; // undefined since i don't know what this represents
ret.status = this.status;
ret.startDate = this.startDate; ret.endDate = this.endDate;
return ret;
}
// returns newly allocated thing.
public DivTable DivTable()
{
final List<Single> data = new ArrayList<Single>();
for (final Pair p : this)
if (0!=p.first)
data.add(new Single(p.date,p.first));
DivTable ret = new DivTable(this.symbol,
this.dateAccessed,
false, // not split adjusted.
data);
return ret;
}
// returns newly allocated thing.
public SplitTable SplitTable()
{
SplitTable ret = new SplitTable();
ret.symbol = this.symbol;
ret.dateAccessed = this.dateAccessed;
ret.data = new ArrayList<Single>();
for (final Pair p : this)
if (0!=p.second)
ret.data.add(new Single(p.date,p.second));
return ret;
}
}
public DivTable HistoricalDividends(String symbol, Date startDate, Date endDate)
throws IOException
{
final DivSplitTable dst = this.HistoricalDivSplits(symbol,startDate,endDate);
return dst.DivTable();
}
public SplitTable HistoricalSplits(String symbol, Date startDate, Date endDate)
throws IOException
{
final DivSplitTable dst = this.HistoricalDivSplits(symbol, startDate, endDate);
return dst.SplitTable();
}
DivSplitTable HistoricalDivSplits(String symbol)
throws IOException
{
DivSplitTable ret;
// TODO maybe this lock needs to be more sophisticated.
synchronized(mDivSplits)
{
ret = mDivSplits.get(symbol);
// TODO make this more sophisticated. As it is it's going to download the whole table another time every day.
if (null==ret || System.currentTimeMillis() - ret.dateAccessed > TwentyFourHours)
{
ret = DownloadHistoricalDivSplits(symbol);
// intern it in case calling code is smart
mDivSplits.put(symbol.intern(),ret);
}
}
return ret;
}
// TODO refactor to make this private
DivSplitTable HistoricalDivSplits(String symbol, Date startDate, Date endDate)
throws IOException
{
return HistoricalDivSplits(symbol).SubTable(startDate, endDate);
}
// Downloads historical split and dividend data and caches them. Called for side effects.
private DivSplitTable DownloadHistoricalDivSplits(String symbol)
throws IOException
{
String csv = new HistoricalUrlBuilder(symbol)
.setType(HistoricalUrlBuilder.Type.DIVIDEND)
.download();
String [] lines = csv.split("\n");
final DivSplitTable ret = new DivSplitTable(lines.length);
ret.symbol = symbol;
ret.dateAccessed = System.currentTimeMillis();
for (String s : lines)
{
s = s.replaceAll(" ","");
String [] elements = s.split(",");
if (elements[0].equals("DIVIDEND"))
{
Pair p = new Pair();
int date = Integer.parseInt(elements[1]);
p.date = new Date(date);
p.second = 0;
p.first = Double.parseDouble(elements[2]);
ret.add(p);
}
if (elements[0].equals("SPLIT"))
{
Pair p = new Pair();
int date = Integer.parseInt(elements[1]);
p.date = new Date(date);
p.first = 0;
String [] fractionParts = elements[2].split(":"); // gonna be like 1:10 or something
p.second = Double.parseDouble(fractionParts[1]) / Double.parseDouble(fractionParts[0]);
ret.add(p);
}
if (elements[0].equals("STARTDATE"))
ret.startDate = new Date(Integer.parseInt(elements[1]));
if (elements[0].equals("ENDDATE"))
ret.endDate = new Date(Integer.parseInt(elements[1]));
if (elements[0].equals("STATUS"))
ret.status = Integer.parseInt(elements[1]);
if (elements[0].equals("TOTALSIZE"))
ret.totalSize = Integer.parseInt(elements[1]);
}
//if (ret.totalSize != ret.data.size()) throw new RuntimeException("Uh oh");
// TODO figure out what ret.totalSize represents
Collections.reverse(ret); // ascending order
return ret;
}
final boolean DBG_QUOTES = false;
// Low level API
public List<Quote> DownloadQuotes(final String... symbols)
throws IOException
{
final List<Quote> ret = new ArrayList<Quote>(symbols.length);
if (0==symbols.length) return ret;
final QuoteUrlBuilder qub = new QuoteUrlBuilder();
qub.addTags(Quote.quoteTags);
qub.addSymbols(Arrays.asList(symbols));
if (DBG_QUOTES)
{
System.out.println(qub.prepare());
System.out.println(Quote.quoteTags);
}
final CSVReader csv = new CSVReader(new InputStreamReader(qub.prepare().toURL().openStream()));
final List<String[]> allLines = csv.readAll();
csv.close();
int i = 0;
for (final String line[] : allLines)
{
if (DBG_QUOTES)
{
for (final String s : line)
System.out.print(s+", ");
System.out.println();
}
ret.add(new Quote(symbols[i], line));
++i;
}
return ret;
}
public Quote getQuote(final String ticker)
throws IOException
{
// yeah this is awesome
return Quotes(ticker).get(0);
}
public List<Quote> Quotes(final String... tickers)
throws IOException
{
final List<Quote> ret = new ArrayList<Quote>(tickers.length);
final List<String> needed_quotes = new ArrayList<String>(tickers.length);
synchronized(mQuotes)
{
// download needed quotes
for (final String ticker : tickers)
{
final Quote q = mQuotes.get(ticker);
if (null==q || System.currentTimeMillis() - q.time_accessed > TwentyFourHours)
needed_quotes.add(ticker);
}
List<Quote> downloaded = DownloadQuotes(needed_quotes.toArray(new String[needed_quotes.size()]));
int i = 0;
for (final Quote q : downloaded)
mQuotes.put(tickers[i++], q);
// return them in order requested
for (final String ticker : tickers)
ret.add(mQuotes.get(ticker));
}
return ret;
}
// Downloads stuff from Yahoo Finance
public HistTable DownloadHistoricalPrices(String symbol)
throws IOException
{
String csv = new HistoricalUrlBuilder(symbol)
.setType(HistoricalUrlBuilder.Type.DAILY)
.download();
List<HistRow> list = new ArrayList<HistRow>();
String [] lines = csv.split("\n");
// skip first line and put it into a list backwards
// since it is already in sorted descending order
for (int i = lines.length; i--!=1; )
list.add(new HistRow(lines[i]));
HistTable ret = new HistTable(symbol,System.currentTimeMillis(),list);
return ret;
}
/**
* Get the historical csv table for symbol. Will memoize (cache) the result.
* @param symbol
* @return
* @throws IOException
*/
public HistTable HistoricalPrices(String symbol)
throws IOException
{
HistTable ret = null;
synchronized (mTables)
{
ret = mTables.get(symbol);
// TODO make this more sophisticated. As it is it's going to download the whole table another time every day. Lol.
// Try something where you just download today's price. problematic
// because then it's like mutable.
//
// If we don't have the table or it is old get a new one
if (null==ret || System.currentTimeMillis() - ret.dateAccessed > TwentyFourHours)
{
ret = DownloadHistoricalPrices(symbol);
// intern it in case calling code is smart
mTables.put(symbol.intern(),ret);
}
}
return ret;
}
public HistTable HistoricalPrices(String symbol, Date startDate, Date endDate)
throws IOException
{
final HistTable ret = HistoricalPrices(symbol);
return ret.SubTable(startDate,endDate);
}
/**
* Overloaded version of HistoricalPrices(String, Date, Date)
* @param symbol
* @param startDate
* @param endDate
* @return
* @throws IOException
*/
public HistTable HistoricalPrices(String symbol, int startDate, int endDate)
throws IOException
{
return HistoricalPrices(symbol, new Date(startDate), new Date(endDate));
}
private YahooFinance() {}
static final private YahooFinance sYahooFinance = new YahooFinance();
static public YahooFinance getInstance()
{
return sYahooFinance;
}
static long time = 0;
// helper function
static public void logTime(String msg)
{
final long newTime = System.currentTimeMillis();
//final long newTime = System.nanoTime();
final long elapsed = newTime - time;
System.out.println(msg+" "+elapsed);
time = newTime;
}
// TODO put this in FinUtils
/**
* Calculates the rolling alpha and beta for two stocks
* @param stock1
* @param stock2
* @param windowSize Size of window to calculate the regression over
* @param convolutionFilter A smoothing parameter
* @return A list of <code>Pair</code>s where the first member is the alpha
* and the second member is the beta.
*/
public List<Pair> Alphabet(HistTable stock1, HistTable stock2, int windowSize, double convolutionFilter)
{
logTime("Start");
List<Pair> merged = FinUtils.merge(stock1,stock2);
logTime("Merged");
// This size is slightly different from R window size
// it is like R window size + 1
// Since Statistics.regress does the diff/log
DataTable alpha = new DataTable(Integer.class, Double.class);
DataTable beta = new DataTable(Integer.class, Double.class);
// perform regression over rolling windows
// TODO make this faster.
SimpleRegression regress;
for (int i = 0; i < merged.size() - windowSize; i++)
{
List<Pair> window = merged.subList(i,i+windowSize);
regress = Statistics.regress(window);
int date = window.get(window.size()-1).date.toInt();
double intercept = regress.getIntercept();
intercept = 100 * (Math.exp(intercept * 250) - 1); // in APR, not daily log
alpha.add(date, intercept);
beta.add(date, regress.getSlope());
}
logTime("Regressed");
Kernel kernel = KernelUtils.getBinomial(convolutionFilter).normalize();
DataSource filteredAlpha = new Convolution(alpha, kernel, Mode.REPEAT, 1);
DataSource filteredBeta = new Convolution(beta ,kernel, Mode.REPEAT, 1);
logTime("Smoothed");
int size = filteredAlpha.getRowCount();
List<Pair> ret = new ArrayList<Pair>(size);
for (int i = 0; i < size; i++)
{
Pair p = new Pair(); // yay for hammering malloc ;)
p.date = new Date((Integer)filteredAlpha.get(0, i)); // oy vey what awful code
p.first = (Double) filteredAlpha.get(1,i);
p.second = (Double) filteredBeta.get(1,i);
ret.add(p);
}
return ret;
}
public static void main(String args[])
throws IOException, java.text.ParseException
{
/*
final YahooFinance yf = YahooFinance.getInstance();
final String []symbols = new String[]{"BAC","JPM","AAPL","INTC","MSFT"};
final List<Quote> quotes = yf.DownloadQuotes(symbols);
final double[] weights_earnings = FinUtils.weightByEarnings(quotes);
final double[] weights_market_cap = FinUtils.weightByMarketCap(quotes);
*/
YahooFinance yf = YahooFinance.getInstance();
logTime("start");
yf.Quotes("BAC");
logTime("done");
List<Quote> quotes = yf.Quotes("AMZN");
logTime("done");
for (final Quote q : quotes)
System.out.println(q.dividend_yield);
/*
final Date today = new Date(new java.util.Date());
final Date start = new Date(20120501);
final HistTable[] tables = new HistTable[symbols.length];
int i = 0;
for (final String symbol : symbols)
tables[i++] = yf.HistoricalPrices(symbol,start,today).AdjustOHLCWithReinvestment();
final double[] weights_markowitz = FinUtils.MarkowitzPortfolio(tables);
System.out.println(Arrays.toString(symbols));
//System.out.println("Markowitz");
//System.out.println(Arrays.toString(weights_markowitz));
System.out.println("Earnings");
//MathUtils.printArray(weights_earnings);
System.out.println(Arrays.toString(weights_earnings));
System.out.println("Market Cap");
MathUtils.printArray(weights_market_cap);
System.out.println("Div Yields");
MathUtils.printArray(FinUtils.weightByDividendYield(quotes));
System.out.println("Div per share");
MathUtils.printArray(FinUtils.weightByDividends(quotes));
*/
}
}
| apache-2.0 |
jenetics/jenetics | jenetics.prog/src/main/java/io/jenetics/prog/op/MathOp.java | 11985 | /*
* Java Genetic Algorithm Library (@__identifier__@).
* Copyright (c) @__year__@ Franz Wilhelmstötter
*
* 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.
*
* Author:
* Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
*/
package io.jenetics.prog.op;
import static java.lang.Math.abs;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan;
import static java.lang.Math.cbrt;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.cosh;
import static java.lang.Math.exp;
import static java.lang.Math.floor;
import static java.lang.Math.hypot;
import static java.lang.Math.log;
import static java.lang.Math.log10;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.pow;
import static java.lang.Math.rint;
import static java.lang.Math.signum;
import static java.lang.Math.sin;
import static java.lang.Math.sinh;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static java.lang.Math.tanh;
import static java.util.Objects.requireNonNull;
import static io.jenetics.prog.op.Numbers.box;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import io.jenetics.ext.util.Tree;
import io.jenetics.ext.util.TreeNode;
/**
* This class contains operations for performing basic numeric operations.
*
* @see Math
*
* @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
* @version 5.0
* @since 3.9
*/
public enum MathOp implements Op<Double> {
/* *************************************************************************
* Arithmetic operations
* ************************************************************************/
/**
* Return the absolute value of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#abs(double)
*/
ABS("abs", 1, v -> abs(v[0])),
/**
* Return the negation value of a double value.
* <em>This operation has arity 1.</em>
*/
NEG("neg", 1, v -> -v[0]),
/**
* The identity function.
*/
ID("id", 1, v -> v[0]),
/**
* Return the minimum of two values.
* <em>This operation has arity 2.</em>
*
* @see Math#min(double, double)
*/
MIN("min", 2, v -> min(v[0], v[1])),
/**
* Return the maximum of two values
* <em>This operation has arity 2.</em>
*
* @see Math#max(double, double)
*/
MAX("max", 2, v -> max(v[0], v[1])),
/**
* Returns the smallest (closest to negative infinity) double value that is
* greater than or equal to the argument and is equal to a mathematical
* integer.
* <em>This operation has arity 1.</em>
*
* @see Math#ceil(double)
*/
CEIL("ceil", 1, v -> ceil(v[0])),
/**
* Returns the largest (closest to positive infinity) double value that is
* less than or equal to the argument and is equal to a mathematical integer.
* <em>This operation has arity 1.</em>
*
* @see Math#floor(double)
*/
FLOOR("floor", 1, v -> floor(v[0])),
/**
* Returns the signum function of the argument; zero if the argument is
* zero, 1.0 if the argument is greater than zero, -1.0 if the argument is
* less than zero.
* <em>This operation has arity 1.</em>
*
* @see Math#signum(double)
*/
SIGNUM("signum", 1, v -> signum(v[0])),
/**
* Returns the double value that is closest in value to the argument and is
* equal to a mathematical integer.
* <em>This operation has arity 1.</em>
*
* @see Math#rint(double)
*/
RINT("rint", 1, v -> rint(v[0])),
/**
* Returns the sum of its arguments.
* <em>This operation has arity 2.</em>
*/
ADD("add", 2, v -> v[0] + v[1]),
/**
* Return the diff of its arguments.
* <em>This operation has arity 2.</em>
*/
SUB("sub", 2, v -> v[0] - v[1]),
/**
* Returns the product of its arguments.
* <em>This operation has arity 2.</em>
*/
MUL("mul", 2, v -> v[0]*v[1]),
/**
* Returns the quotient of its arguments.
* <em>This operation has arity 2.</em>
*/
DIV("div", 2, v -> v[0]/v[1]),
/**
* Returns the modulo of its arguments.
* <em>This operation has arity 2.</em>
*/
MOD("mod", 2, v -> v[0]%v[1]),
/**
* Returns the value of the first argument raised to the power of the second
* argument.
* <em>This operation has arity 2.</em>
*
* @see Math#pow(double, double)
*/
POW("pow", 2, v -> pow(v[0], v[1])),
/**
* Returns the square value of a given double value.
* <em>This operation has arity 1.</em>
*/
SQR("sqr", 1, v -> v[0]*v[0]),
/**
* Returns the correctly rounded positive square root of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#sqrt(double)
*/
SQRT("sqrt", 1, v -> sqrt(v[0])),
/**
* Returns the cube root of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#cbrt(double)
*/
CBRT("cbrt", 1, v -> cbrt(v[0])),
/**
* Returns sqrt(<i>x</i><sup>2</sup> +<i>y</i><sup>2</sup>) without
* intermediate overflow or underflow.
* <em>This operation has arity 2.</em>
*
* @see Math#hypot(double, double)
*/
HYPOT("hypot", 2, v -> hypot(v[0], v[1])),
/* *************************************************************************
* Exponential/logarithmic operations
* ************************************************************************/
/**
* Returns Euler's number e raised to the power of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#exp(double)
*/
EXP("exp", 1, v -> exp(v[0])),
/**
* Returns the natural logarithm (base e) of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#log(double)
*/
LOG("log", 1, v -> log(v[0])),
/**
* Returns the base 10 logarithm of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#log10(double)
*/
LOG10("log10", 1, v -> log10(v[0])),
/* *************************************************************************
* Trigonometric operations
* ************************************************************************/
/**
* Returns the trigonometric sine of an angle.
* <em>This operation has arity 1.</em>
*
* @see Math#sin(double)
*/
SIN("sin", 1, v -> sin(v[0])),
/**
* Returns the trigonometric cosine of an angle.
* <em>This operation has arity 1.</em>
*
* @see Math#cos(double)
*/
COS("cos", 1, v -> cos(v[0])),
/**
* Returns the trigonometric tangent of an angle.
* <em>This operation has arity 1.</em>
*
* @see Math#tan(double)
*/
TAN("tan", 1, v -> tan(v[0])),
/**
* Returns the arc cosine of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#acos(double)
*/
ACOS("acos", 1, v -> acos(v[0])),
/**
* Returns the arc sine of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#asin(double)
*/
ASIN("asin", 1, v -> asin(v[0])),
/**
* Returns the arc tangent of a value.
* <em>This operation has arity 1.</em>
*
* @see Math#atan(double)
*/
ATAN("atan", 1, v -> atan(v[0])),
/**
* Returns the hyperbolic cosine of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#cosh(double)
*/
COSH("cosh", 1, v -> cosh(v[0])),
/**
* Returns the hyperbolic sine of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#sinh(double)
*/
SINH("sinh", 1, v -> sinh(v[0])),
/**
* Returns the hyperbolic tangent of a double value.
* <em>This operation has arity 1.</em>
*
* @see Math#tanh(double)
*/
TANH("tanh", 1, v -> tanh(v[0])),
/* *************************************************************************
* Conditional functions
* ************************************************************************/
/**
* Returns +1.0 if its first argument is greater than its second argument
* and returns -1.0 otherwise.
*
* @since 5.0
*/
GT("gt", 2, v -> v[0] > v[1] ? 1.0 : -1.0);
/* *************************************************************************
* Additional mathematical constants.
* ************************************************************************/
/**
* The double value that is closer than any other to pi, the ratio of the
* circumference of a circle to its diameter. <em>This is a terminal
* operation.</em>
*
* @see Math#PI
*/
public static final Const<Double> PI = Const.of("π", Math.PI);
/**
* The double value that is closer than any other to e, the base of the
* natural logarithms. <em>This is a terminal operation.</em>
*
* @see Math#E
*/
public static final Const<Double> E = Const.of("e", Math.E);
/**
* The names of all defined operation names.
*
* @since 7.0
*/
public static final Set<String> NAMES = Stream.of(MathOp.values())
.map(MathOp::toString)
.collect(Collectors.toUnmodifiableSet());
private final String _name;
private final int _arity;
private final Function<Double[], Double> _function;
MathOp(
final String name,
final int arity,
final Function<Double[], Double> function
) {
assert name != null;
assert arity >= 0;
assert function != null;
_name = name;
_function = function;
_arity = arity;
}
@Override
public int arity() {
return _arity;
}
@Override
public Double apply(final Double[] args) {
return _function.apply(args);
}
/**
* Evaluates the operation with the given arguments.
*
* @since 5.0
*
* @see #apply(Double[])
*
* @param args the operation arguments
* @return the evaluated operation
*/
public double eval(final double... args) {
return apply(box(args));
}
@Override
public String toString() {
return _name;
}
/**
* Converts the string representation of an operation to the operation
* object. It is used for converting the string representation of a tree to
* an operation tree. <b>If you use it that way, you should not forget to
* re-index the tree variables.</b>
*
* <pre>{@code
* final TreeNode<Op<Double>> tree = TreeNode.parse(
* "add(mul(x,y),sub(y,x))",
* MathOp::toMathOp
* );
*
* assert Program.eval(tree, 10.0, 5.0) == 100.0;
* Var.reindex(tree);
* assert Program.eval(tree, 10.0, 5.0) == 45.0;
* }</pre>
*
* @since 5.0
*
* @see Var#reindex(TreeNode)
* @see Program#eval(Tree, Object[])
*
* @param string the string representation of an operation which should be
* converted
* @return the operation, converted from the given string
* @throws IllegalArgumentException if the given {@code value} doesn't
* represent a mathematical expression
* @throws NullPointerException if the given string {@code value} is
* {@code null}
*/
public static Op<Double> toMathOp(final String string) {
requireNonNull(string);
final Op<Double> result;
final Optional<Const<Double>> cop = toConst(string);
if (cop.isPresent()) {
result = cop.orElseThrow(AssertionError::new);
} else {
final Optional<Op<Double>> mop = toOp(string);
result = mop.isPresent()
? mop.orElseThrow(AssertionError::new)
: Var.parse(string);
}
return result;
}
static Optional<Const<Double>> toConst(final String string) {
return Numbers.toDoubleOptional(string)
.map(Const::of);
}
private static Optional<Op<Double>> toOp(final String string) {
return Stream.of(values())
.filter(op -> Objects.equals(op._name, string))
.map(op -> (Op<Double>)op)
.findFirst();
}
}
| apache-2.0 |
litesuits/for-test | DataBaseTest/app/src/main/java/lite/dbtest/model/Note.java | 1864 | package lite.dbtest.model;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT. Enable "keep" sections if you want to edit.
import com.litesuits.orm.db.annotation.Column;
import com.litesuits.orm.db.annotation.NotNull;
import com.litesuits.orm.db.annotation.PrimaryKey;
import com.litesuits.orm.db.annotation.Table;
import com.litesuits.orm.db.enums.AssignType;
/**
* Entity mapped to table "NOTE".
*/
@Table("lite_note")
public class Note {
@Column("_id")
@PrimaryKey(AssignType.AUTO_INCREMENT)
private Long id;
/** Not-null value. */
@NotNull
@Column("_text")
private String text;
private String comment;
private java.util.Date date;
public Note() {
}
public Note(Long id) {
this.id = id;
}
public Note(Long id, String text, String comment, java.util.Date date) {
this.id = id;
this.text = text;
this.comment = comment;
this.date = date;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/** Not-null value. */
public String getText() {
return text;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setText(String text) {
this.text = text;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
@Override
public String toString() {
return "Note{" +
"id=" + id +
", text='" + text + '\'' +
", comment='" + comment + '\'' +
", date=" + date +
'}';
}
}
| apache-2.0 |
Ranx0r0x/Enjekt-Microservice | microserver/src/main/java/org/enjekt/osgi/microserver/impl/MicroWebserviceRegistration.java | 2255 | /**
Copyright 2016 Brad Johnson, Enjekt Software
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.enjekt.osgi.microserver.impl;
import java.util.UUID;
import org.enjekt.osgi.microserver.api.MicroWebservice;
/**
* The Class MicroWebserviceRegistration extends the basic MicroWebserviceConfiguration but also provides
* specific fields and methods that are necessary for setting up a SOAP or REST web service such as the
* interface and implementing component.
*
* It creates a final UUID associated with this microservice so that it can be uniquely identified for registration
* and unregistration events with the MicrowebserverManager.
*/
public class MicroWebserviceRegistration extends MicroWebserviceConfiguration implements MicroWebservice {
/** The id. */
private final String id = UUID.randomUUID().toString();
/** The interface clazz. */
private final Class interfaceClazz;
/** The component. */
private final Object component;
/**
* Instantiates a new micro webservice registration.
*
* @param interfaceClazz the interface clazz
* @param component the component
*/
public MicroWebserviceRegistration(Class interfaceClazz, Object component) {
this.interfaceClazz = interfaceClazz;
this.component = component;
}
/* (non-Javadoc)
* @see org.enjekt.osgi.microserver.api.MicroWebservice#getInterfaceClazz()
*/
@Override
public Class getInterfaceClazz() {
return interfaceClazz;
}
/* (non-Javadoc)
* @see org.enjekt.osgi.microserver.api.MicroWebservice#getComponent()
*/
@Override
public Object getComponent() {
return component;
}
/* (non-Javadoc)
* @see org.enjekt.osgi.microserver.api.MicroWebservice#getIdentifier()
*/
@Override
public String getIdentifier() {
return id;
}
}
| apache-2.0 |
nasa/OpenSPIFe | gov.nasa.ensemble.core.model.plan.provider/src/gov/nasa/ensemble/core/model/plan/provider/ItemColorProvider.java | 1123 | /*******************************************************************************
* Copyright 2014 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* 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 gov.nasa.ensemble.core.model.plan.provider;
import gov.nasa.ensemble.common.mission.MissionExtendable;
public class ItemColorProvider implements MissionExtendable {
public Object getBackground(Object object) {
return null;
}
}
| apache-2.0 |
iatsyk/cafemenu | src/main/java/tk/iatsyk/handler/CafeHandler.java | 329 | package tk.iatsyk.handler;
import tk.iatsyk.entities.businessentities.Cafe;
import tk.iatsyk.entities.representationobjects.CafeRO;
import java.util.List;
/**
* User: Vova Iatsyk
* Date: 17.10.2015
*/
public interface CafeHandler {
String getProperties();
long save(Cafe cafe);
List<CafeRO> getAllCafes();
}
| apache-2.0 |