hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
74f14205f291b5541c94c1b1efce21fca66ce775 | 1,235 | package org.catrobat.confluence.rest.json;
import javax.xml.bind.annotation.XmlElement;
public class JsonCategory {
@XmlElement
private int categoryID;
@XmlElement
private String categoryName;
public JsonCategory(int categoryID, String categoryName) {
this.categoryID = categoryID;
this.categoryName = categoryName;
}
public int getCategoryID() {
return categoryID;
}
public void setCategoryID(int categoryID) {
this.categoryID = categoryID;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
@Override
public int hashCode() {
int hash = 7;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final JsonCategory other = (JsonCategory) obj;
if (this.categoryID != other.categoryID) {
return false;
}
if ((this.categoryName == null) ? (other.categoryName != null) : !this.categoryName.equals(other.categoryName)) {
return false;
}
return true;
}
}
| 22.053571 | 118 | 0.639676 |
8a8827917048e70e650af2e27eefc844f18cbb92 | 199 | package org.beigesoft.ui;
public interface IEventMotion {
public int getX();
public int getY();
public boolean isIntentEdit();
public void consume();
public boolean isConsumed();
}
| 13.266667 | 32 | 0.698492 |
0c8c4ae43fb7cf058aedff0f002809fb70116303 | 13,672 | // Copyright 2020 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.beam.initsql;
import static com.google.common.truth.Truth.assertThat;
import static google.registry.model.ImmutableObjectSubject.assertAboutImmutableObjects;
import static google.registry.model.ImmutableObjectSubject.immutableObjectCorrespondence;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import static google.registry.testing.DatastoreHelper.newRegistry;
import static google.registry.testing.DatastoreHelper.persistResource;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.googlecode.objectify.Key;
import google.registry.backup.AppEngineEnvironment;
import google.registry.beam.TestPipelineExtension;
import google.registry.model.billing.BillingEvent;
import google.registry.model.contact.ContactResource;
import google.registry.model.domain.DesignatedContact;
import google.registry.model.domain.DomainAuthInfo;
import google.registry.model.domain.DomainBase;
import google.registry.model.domain.GracePeriod;
import google.registry.model.domain.launch.LaunchNotice;
import google.registry.model.domain.rgp.GracePeriodStatus;
import google.registry.model.domain.secdns.DelegationSignerData;
import google.registry.model.eppcommon.AuthInfo.PasswordAuth;
import google.registry.model.eppcommon.StatusValue;
import google.registry.model.eppcommon.Trid;
import google.registry.model.host.HostResource;
import google.registry.model.ofy.Ofy;
import google.registry.model.poll.PollMessage;
import google.registry.model.registrar.Registrar;
import google.registry.model.registry.Registry;
import google.registry.model.reporting.HistoryEntry;
import google.registry.model.transfer.DomainTransferData;
import google.registry.model.transfer.TransferStatus;
import google.registry.persistence.VKey;
import google.registry.persistence.transaction.JpaTestRules;
import google.registry.persistence.transaction.JpaTestRules.JpaIntegrationTestExtension;
import google.registry.testing.AppEngineExtension;
import google.registry.testing.DatastoreEntityExtension;
import google.registry.testing.FakeClock;
import google.registry.testing.InjectExtension;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.joda.time.DateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
/** Unit tests for {@link InitSqlPipeline}. */
class InitSqlPipelineTest {
private static final DateTime START_TIME = DateTime.parse("2000-01-01T00:00:00.0Z");
private static final ImmutableList<Class<?>> ALL_KINDS =
ImmutableList.of(
Registry.class,
Registrar.class,
ContactResource.class,
HostResource.class,
DomainBase.class,
HistoryEntry.class);
private transient FakeClock fakeClock = new FakeClock(START_TIME);
@RegisterExtension
@Order(Order.DEFAULT - 1)
final transient DatastoreEntityExtension datastore = new DatastoreEntityExtension();
@RegisterExtension final transient InjectExtension injectRule = new InjectExtension();
@SuppressWarnings("WeakerAccess")
@TempDir
transient Path tmpDir;
@RegisterExtension
final transient TestPipelineExtension testPipeline =
TestPipelineExtension.create().enableAbandonedNodeEnforcement(true);
@RegisterExtension
final transient JpaIntegrationTestExtension database =
new JpaTestRules.Builder().withClock(fakeClock).buildIntegrationTestRule();
// Must not be transient!
@RegisterExtension
@Order(Order.DEFAULT + 1)
final BeamJpaExtension beamJpaExtension =
new BeamJpaExtension(() -> tmpDir.resolve("credential.dat"), database.getDatabase());
private File exportRootDir;
private File exportDir;
private File commitLogDir;
private transient Registrar registrar1;
private transient Registrar registrar2;
private transient DomainBase domain;
private transient ContactResource contact1;
private transient ContactResource contact2;
private transient HostResource hostResource;
private transient HistoryEntry historyEntry;
@BeforeEach
void beforeEach() throws Exception {
try (BackupTestStore store = new BackupTestStore(fakeClock)) {
injectRule.setStaticField(Ofy.class, "clock", fakeClock);
exportRootDir = Files.createDirectory(tmpDir.resolve("exports")).toFile();
persistResource(newRegistry("com", "COM"));
registrar1 = persistResource(AppEngineExtension.makeRegistrar1());
registrar2 = persistResource(AppEngineExtension.makeRegistrar2());
Key<DomainBase> domainKey = Key.create(null, DomainBase.class, "4-COM");
hostResource =
persistResource(
new HostResource.Builder()
.setHostName("ns1.example.com")
.setSuperordinateDomain(VKey.from(domainKey))
.setRepoId("1-COM")
.setCreationClientId(registrar1.getClientId())
.setPersistedCurrentSponsorClientId(registrar2.getClientId())
.build());
contact1 =
persistResource(
new ContactResource.Builder()
.setContactId("contact_id1")
.setRepoId("2-COM")
.setCreationClientId(registrar1.getClientId())
.setPersistedCurrentSponsorClientId(registrar2.getClientId())
.build());
contact2 =
persistResource(
new ContactResource.Builder()
.setContactId("contact_id2")
.setRepoId("3-COM")
.setCreationClientId(registrar1.getClientId())
.setPersistedCurrentSponsorClientId(registrar1.getClientId())
.build());
historyEntry = persistResource(new HistoryEntry.Builder().setParent(domainKey).build());
Key<HistoryEntry> historyEntryKey = Key.create(historyEntry);
Key<BillingEvent.OneTime> oneTimeBillKey =
Key.create(historyEntryKey, BillingEvent.OneTime.class, 1);
VKey<BillingEvent.Recurring> recurringBillKey =
VKey.from(Key.create(historyEntryKey, BillingEvent.Recurring.class, 2));
VKey<PollMessage.Autorenew> autorenewPollKey =
VKey.from(Key.create(historyEntryKey, PollMessage.Autorenew.class, 3));
VKey<PollMessage.OneTime> onetimePollKey =
VKey.from(Key.create(historyEntryKey, PollMessage.OneTime.class, 1));
domain =
persistResource(
new DomainBase.Builder()
.setDomainName("example.com")
.setRepoId("4-COM")
.setCreationClientId(registrar1.getClientId())
.setLastEppUpdateTime(fakeClock.nowUtc())
.setLastEppUpdateClientId(registrar2.getClientId())
.setLastTransferTime(fakeClock.nowUtc())
.setStatusValues(
ImmutableSet.of(
StatusValue.CLIENT_DELETE_PROHIBITED,
StatusValue.SERVER_DELETE_PROHIBITED,
StatusValue.SERVER_TRANSFER_PROHIBITED,
StatusValue.SERVER_UPDATE_PROHIBITED,
StatusValue.SERVER_RENEW_PROHIBITED,
StatusValue.SERVER_HOLD))
.setRegistrant(contact1.createVKey())
.setContacts(
ImmutableSet.of(
DesignatedContact.create(
DesignatedContact.Type.ADMIN, contact2.createVKey())))
.setNameservers(ImmutableSet.of(hostResource.createVKey()))
.setSubordinateHosts(ImmutableSet.of("ns1.example.com"))
.setPersistedCurrentSponsorClientId(registrar2.getClientId())
.setRegistrationExpirationTime(fakeClock.nowUtc().plusYears(1))
.setAuthInfo(DomainAuthInfo.create(PasswordAuth.create("password")))
.setDsData(
ImmutableSet.of(DelegationSignerData.create(1, 2, 3, new byte[] {0, 1, 2})))
.setLaunchNotice(
LaunchNotice.create("tcnid", "validatorId", START_OF_TIME, START_OF_TIME))
.setTransferData(
new DomainTransferData.Builder()
.setGainingClientId(registrar1.getClientId())
.setLosingClientId(registrar2.getClientId())
.setPendingTransferExpirationTime(fakeClock.nowUtc())
.setServerApproveEntities(
ImmutableSet.of(
VKey.from(oneTimeBillKey), recurringBillKey, autorenewPollKey))
.setServerApproveBillingEvent(VKey.from(oneTimeBillKey))
.setServerApproveAutorenewEvent(recurringBillKey)
.setServerApproveAutorenewPollMessage(autorenewPollKey)
.setTransferRequestTime(fakeClock.nowUtc().plusDays(1))
.setTransferStatus(TransferStatus.SERVER_APPROVED)
.setTransferRequestTrid(Trid.create("client-trid", "server-trid"))
.build())
.setDeletePollMessage(onetimePollKey)
.setAutorenewBillingEvent(recurringBillKey)
.setAutorenewPollMessage(autorenewPollKey)
.setSmdId("smdid")
.addGracePeriod(
GracePeriod.create(
GracePeriodStatus.ADD,
"4-COM",
fakeClock.nowUtc().plusDays(1),
"registrar",
null))
.build());
exportDir = store.export(exportRootDir.getAbsolutePath(), ALL_KINDS, ImmutableSet.of());
commitLogDir = Files.createDirectory(tmpDir.resolve("commits")).toFile();
}
}
@Test
void runPipeline() {
InitSqlPipelineOptions options =
PipelineOptionsFactory.fromArgs(
"--sqlCredentialUrlOverride="
+ beamJpaExtension.getCredentialFile().getAbsolutePath(),
"--commitLogStartTimestamp=" + START_TIME,
"--commitLogEndTimestamp=" + fakeClock.nowUtc().plusMillis(1),
"--datastoreExportDir=" + exportDir.getAbsolutePath(),
"--commitLogDir=" + commitLogDir.getAbsolutePath())
.withValidation()
.as(InitSqlPipelineOptions.class);
InitSqlPipeline initSqlPipeline = new InitSqlPipeline(options, testPipeline);
initSqlPipeline.run().waitUntilFinish();
try (AppEngineEnvironment env = new AppEngineEnvironment("test")) {
assertHostResourceEquals(
jpaTm().transact(() -> jpaTm().load(hostResource.createVKey())), hostResource);
assertThat(jpaTm().transact(() -> jpaTm().loadAll(Registrar.class)))
.comparingElementsUsing(immutableObjectCorrespondence("lastUpdateTime"))
.containsExactly(registrar1, registrar2);
assertThat(jpaTm().transact(() -> jpaTm().loadAll(ContactResource.class)))
.comparingElementsUsing(immutableObjectCorrespondence("revisions", "updateTimestamp"))
.containsExactly(contact1, contact2);
assertCleansedDomainEquals(jpaTm().transact(() -> jpaTm().load(domain.createVKey())), domain);
}
}
private static void assertHostResourceEquals(HostResource actual, HostResource expected) {
assertAboutImmutableObjects()
.that(actual)
.isEqualExceptFields(expected, "superordinateDomain", "revisions", "updateTimestamp");
assertThat(actual.getSuperordinateDomain().getSqlKey())
.isEqualTo(expected.getSuperordinateDomain().getSqlKey());
}
private static void assertCleansedDomainEquals(DomainBase actual, DomainBase expected) {
assertAboutImmutableObjects()
.that(actual)
.isEqualExceptFields(
expected,
"adminContact",
"registrantContact",
"gracePeriods",
"dsData",
"allContacts",
"revisions",
"updateTimestamp",
"autorenewBillingEvent",
"autorenewBillingEventHistoryId",
"autorenewPollMessage",
"autorenewPollMessageHistoryId",
"deletePollMessage",
"deletePollMessageHistoryId",
"nsHosts",
"transferData");
assertThat(actual.getAdminContact().getSqlKey())
.isEqualTo(expected.getAdminContact().getSqlKey());
assertThat(actual.getRegistrant().getSqlKey()).isEqualTo(expected.getRegistrant().getSqlKey());
// TODO(weiminyu): compare gracePeriods, allContacts and dsData, when SQL model supports them.
}
}
| 47.307958 | 100 | 0.677443 |
0d01b22f7090496bfd70656d419964d01cc1c48e | 1,775 | package com.opsgenie.tools.backup.exporters;
import com.opsgenie.tools.backup.retrieval.EntityRetriever;
import com.opsgenie.tools.backup.util.BackupUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
abstract class BaseExporter<T> implements Exporter {
final Logger logger = LoggerFactory.getLogger(getClass());
private File exportDirectory;
BaseExporter(String backupRootDirectory, String exportDirectoryName) {
this.exportDirectory = new File(backupRootDirectory + "/" + exportDirectoryName + "/");
this.exportDirectory.mkdirs();
}
protected void exportFile(String fileName, T entity) {
try {
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.print(BackupUtils.toJson(entity));
writer.close();
logger.info(getEntityFileName(entity) + " file written.");
} catch (Exception e) {
logger.error("Error at writing entity, fileName=" + fileName, e);
}
}
@Override
public void export() {
List<T> currentEntityList;
try {
currentEntityList = initializeEntityRetriever().retrieveEntities();
} catch (Exception e) {
logger.error("Could not list " + exportDirectory.getName(), e);
return;
}
for (T bean : currentEntityList) {
exportFile(getExportDirectory().getAbsolutePath() + "/" + getEntityFileName(bean) + ".json", bean);
}
}
protected abstract EntityRetriever<T> initializeEntityRetriever();
protected abstract String getEntityFileName(T entity);
protected File getExportDirectory() {
return exportDirectory;
}
}
| 31.140351 | 111 | 0.661972 |
339c9c89eacf5e91e79e277c9f6e21644e471c11 | 2,579 | package com.jzd.jzshop.ui.home.local_life.location;
import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.jzd.jzshop.R;
import com.jzd.jzshop.entity.ChoiceCityEntity;
import com.jzd.jzshop.ui.order.orderdetail.OrderDetailViewModel;
import org.byteam.superadapter.OnItemClickListener;
import org.byteam.superadapter.SuperAdapter;
import org.byteam.superadapter.SuperViewHolder;
import java.util.List;
import me.goldze.mvvmhabit.bus.Messenger;
/**
* Created by lxb on 2020/2/15.
* 邮箱:2072301410@qq.com
* TIP:
*/
public class SearchChoiceCityAdapter extends SuperAdapter<ChoiceCityEntity> {
private Context mContext;
private List<ChoiceCityEntity> dataList;
private ChoiceCityViewModel viewModel;
private String hotCity;
public SearchChoiceCityAdapter(Context context, ChoiceCityViewModel viewModel, List<ChoiceCityEntity> items, int layoutResId) {
super(context, items, layoutResId);
this.dataList = items;
this.mContext = context;
this.viewModel = viewModel;
}
@Override
public void onBind(SuperViewHolder holder, int viewType, int layoutPosition, ChoiceCityEntity item) {
holder.setText(R.id.tv_tip, item.getTip());
//--------------key word recycleview-------------start--------------------
RecyclerView recycleChild = holder.findViewById(R.id.recycle);
final List<String> keys = item.getKeys();
if (keys != null && keys.size() > 0) {
recycleChild.setVisibility(View.VISIBLE);
final ChoiceCityItemChildAdapter adapter = new ChoiceCityItemChildAdapter(
mContext, keys, R.layout.item_rv_choice_city_child_list_item);
recycleChild.setAdapter(adapter);
GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 3);
recycleChild.setLayoutManager(gridLayoutManager);
adapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(View itemView, int viewType, int position) {//热门城市
hotCity = keys.get(position);
Messenger.getDefault().send(hotCity, ChoiceCityViewModel.TOKEN_VIEWMODEL_CHOICE_CITY_REFRESH);
viewModel.finish();
}
});
} else {
recycleChild.setVisibility(View.GONE);
}
//--------------key word recycleview-------------end--------------------
}
}
| 39.075758 | 131 | 0.670415 |
ee3c023bc93383df4fd41260ad573f9f8a9e9df3 | 18,897 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU General
* Public License Version 2 only ("GPL") or the Common Development and Distribution
* License("CDDL") (collectively, the "License"). You may not use this file except in
* compliance with the License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html or nbbuild/licenses/CDDL-GPL-2-CP. See the
* License for the specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header Notice in
* each file and include the License file at nbbuild/licenses/CDDL-GPL-2-CP. Sun
* designates this particular file as subject to the "Classpath" exception as
* provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License Header,
* with the fields enclosed by brackets [] replaced by your own identifying
* information: "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original Software
* is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun Microsystems, Inc. All
* Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL or only the
* GPL Version 2, indicate your decision by adding "[Contributor] elects to include
* this software in this distribution under the [CDDL or GPL Version 2] license." If
* you do not indicate a single choice of license, a recipient has the option to
* distribute your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above. However, if
* you add GPL Version 2 code and therefore, elected the GPL Version 2 license, then
* the option applies only if the new code is made subject to such option by the
* copyright holder.
*/
package org.netbeans.installer.wizard.components.panels.sunstudio;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JSeparator;
import javax.swing.border.EtchedBorder;
import org.netbeans.installer.utils.ResourceUtils;
import org.netbeans.installer.utils.StringUtils;
import org.netbeans.installer.utils.SystemUtils;
import org.netbeans.installer.utils.env.ExistingSunStudioChecker;
import org.netbeans.installer.utils.helper.swing.NbiButton;
import org.netbeans.installer.utils.helper.swing.NbiDialog;
import org.netbeans.installer.utils.helper.swing.NbiLabel;
import org.netbeans.installer.utils.helper.swing.NbiPanel;
import org.netbeans.installer.utils.helper.swing.NbiTextPane;
import org.netbeans.installer.wizard.components.panels.ErrorMessagePanel;
import org.netbeans.installer.wizard.components.panels.ErrorMessagePanel.ErrorMessagePanelSwingUi;
import org.netbeans.installer.wizard.containers.SwingContainer;
import org.netbeans.installer.wizard.ui.SwingUi;
import org.netbeans.installer.wizard.ui.WizardUi;
public class ExistingSunStudioPanel extends ErrorMessagePanel {
public static final String DEFAULT_TITLE = ResourceUtils.getString(ExistingSunStudioPanel.class, "ESSP.title"); // NOI18N
public static final String DEFAULT_DESCRIPTION = ResourceUtils.getString(ExistingSunStudioPanel.class, "ESSP.description"); // NOI18N
public static final String CLOSE_BUTTON_TEXT = ResourceUtils.getString(ExistingSunStudioPanel.class, "ESSP.close.button.text"); // NOI18N
public static final String GET_LIST_BUTTON_TEXT = ResourceUtils.getString(ExistingSunStudioPanel.class, "ESSP.get.list.button.text"); // NOI18N
public static final String ALREADY_INSTALLED_TEXT = ResourceUtils.getString(ExistingSunStudioPanel.class, "ESSP.already.installed.text"); // NOI18N
public static final String COULD_NOT_BE_USED_TEXT = ResourceUtils.getString(ExistingSunStudioPanel.class, "ESSP.directories.not.used.installed.text"); // NOI18N
public static final String NOT_POSSIBLE_TEXT = ResourceUtils.getString(ExistingSunStudioPanel.class, "ESSP.installation.not.possible.text"); // NOI18N
public static final String ONLY_THIS_DIRECTORY_USED_TEXT = ResourceUtils.getString(ExistingSunStudioPanel.class, "ESSP.only.directory.used.installed.text"); // NOI18N
public static final String LIST_INSTALLED_PACKAGES_TEXT = ResourceUtils.getString(ExistingSunStudioPanel.class, "ESSP.list.packages.text"); // NOI18N
public static final String WARNING_TEXT = ResourceUtils.getString(SystemCheckPanel.class, "ESSP.warning.text"); // NOI18N
public static final String ERROR_TEXT = ResourceUtils.getString(SystemCheckPanel.class, "ESSP.error.text"); // NOI18N
public static final String UNINSTALL_DESCRIPTION_TEXT = ResourceUtils.getString(ExistingSunStudioPanel.class,
SystemUtils.isSolaris() ? "ESPP.uninstall.instructions.solaris.text" : "ESPP.uninstall.instructions.linux.text" ); // NOI18N
/////////////////////////////////////////////////////////////////////////////////
// Instance
public ExistingSunStudioPanel() {}
@Override
public WizardUi getWizardUi() {
if (wizardUi == null) {
wizardUi = new ExistingSunStudioPanelUi(this);
}
return wizardUi;
}
@Override
public void initialize() {
setProperty(TITLE_PROPERTY, DEFAULT_TITLE);
setProperty(DESCRIPTION_PROPERTY, DEFAULT_DESCRIPTION);
}
@Override
public boolean canExecuteForward() {
return true;
}
/////////////////////////////////////////////////////////////////////////////////
// Inner Classes
public static class ExistingSunStudioPanelUi extends ErrorMessagePanelUi {
protected ExistingSunStudioPanel component;
public ExistingSunStudioPanelUi(ExistingSunStudioPanel component) {
super(component);
this.component = component;
}
@Override
public SwingUi getSwingUi(SwingContainer container) {
if (swingUi == null) {
swingUi = new ExistingSunStudioPanelSwingUi(component, container);
}
return super.getSwingUi(container);
}
}
public static class ExistingSunStudioPanelSwingUi extends ErrorMessagePanelSwingUi {
protected ExistingSunStudioPanel component;
ExistingSunStudioChecker checker = ExistingSunStudioChecker.getInstance();
public ExistingSunStudioPanelSwingUi(
final ExistingSunStudioPanel component,
final SwingContainer container) {
super(component, container);
this.component = component;
initComponents();
}
// protected ////////////////////////////////////////////////////////////////
@Override
protected void initializeContainer() {
super.initializeContainer();
container.getNextButton().setText(
panel.getProperty(NEXT_BUTTON_TEXT_PROPERTY));
if (!checker.isInstallationPossible()) {
container.getNextButton().setVisible(false);
container.getBackButton().setVisible(false);
container.getCancelButton().setText(component.getProperty(FINISH_BUTTON_TEXT_PROPERTY));
}
}
// private //////////////////////////////////////////////////////////////////
ConflictedPackagesDialog conflictedPackagesDialog;
private void initComponents() {
//List<SSInstallationInfo> infoList = new ArrayList<SSInstallationInfo>();
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.PAGE_START;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets = new Insets(5, 5, 5, 5);
constraints.gridy = 0;
constraints.gridx = 0;
constraints.gridheight = 1;
constraints.gridheight = 1;
constraints.weightx = 1.0;
// constraints.weighty = 0.5;
for(String version : checker.getInstalledVersions()) {
SSInstallationInfo info = new SSInstallationInfo(version);
//infoList.add(info);
this.add(info, constraints);
constraints.gridy ++;
}
constraints.weighty = 1.0;
this.add(new JSeparator(), constraints);
conflictedPackagesDialog = new ConflictedPackagesDialog();
}
@Override
public void evaluateCancelButtonClick() {
if (!checker.isInstallationPossible()) {
component.getWizard().getFinishHandler().cancel();
} else {
super.evaluateCancelButtonClick();
}
}
@Override
protected String getWarningMessage() {
if (checker.isSunStudioInstallationFound()) {
return WARNING_TEXT;
}
return null;
}
@Override
protected String validateInput() {
if (!checker.isInstallationPossible()) {
return ERROR_TEXT;
}
return null;
}
private class SSInstallationInfo extends NbiPanel {
NbiLabel descriptionLabel;
NbiLabel locationsLabel;
NbiLabel resolutionLabel;
NbiButton getListButton;
String version;
public SSInstallationInfo(String version) {
this.version = version;
initComponents();
}
void initComponents() {
descriptionLabel = new NbiLabel();
locationsLabel = new NbiLabel();
resolutionLabel = new NbiLabel();
getListButton = new NbiButton();
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.anchor = GridBagConstraints.PAGE_START;
constraints.weightx = 0.5;
constraints.weighty = 1;
constraints.insets = new Insets(6, 11, 6, 11);
descriptionLabel.setText(StringUtils.format(ALREADY_INSTALLED_TEXT,
version, StringUtils.asString(checker.getBaseDirsForVersion(version), ", ")));
Font bf = descriptionLabel.getFont();
//descriptionLabel.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
//descriptionLabel.setFont(bf.deriveFont(Font.BOLD, bf.getSize2D()));
this.add(descriptionLabel, constraints);
//locationsLabel.setText(StringUtils.asString(checker.getBaseDirsForVersion(version), ", "));
constraints.gridx = 1;
// constraints.anchor = GridBagConstraints.FIRST_LINE_START;
// constraints.weightx = 1.0;
//locationsLabel.setBorder(new EtchedBorder(EtchedBorder.LOWERED));
//this.add(locationsLabel, constraints);
//constraints.weightx = 0.5;
// constraints.anchor = GridBagConstraints.PAGE_START;
String text = COULD_NOT_BE_USED_TEXT;
if (checker.getResolutionForVersion(version) == ExistingSunStudioChecker.INSTALLATION_BLOCKED) {
text = NOT_POSSIBLE_TEXT;
}
if (checker.getResolutionForVersion(version) == ExistingSunStudioChecker.ONLY_THIS_LOCATION_USED) {
text = ONLY_THIS_DIRECTORY_USED_TEXT;
}
resolutionLabel.setText(text);
constraints.gridy = 1;
constraints.gridx = 0;
constraints.weightx = 2;
constraints.gridwidth = GridBagConstraints.REMAINDER;
bf = resolutionLabel.getFont();
resolutionLabel.setFont(bf.deriveFont(Font.BOLD, bf.getSize2D()));
this.add(resolutionLabel, constraints);
getListButton.setText(GET_LIST_BUTTON_TEXT);
constraints.gridy = 2;
constraints.gridx = 0;
constraints.anchor = GridBagConstraints.WEST;
constraints.weightx = 1;
constraints.gridwidth = 1;
constraints.fill = GridBagConstraints.NONE;
getListButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
conflictedPackagesDialog.show(version, checker.getPackagesForVersion(version));
}
});
this.add(getListButton, constraints);
}
}
}
public static class ConflictedPackagesDialog extends NbiDialog {
private NbiButton okButton;
private NbiButton removeButton;
private NbiPanel buttonsPanel;
private NbiPanel componentPanel;
private NbiLabel header;
private NbiTextPane descriptionPane;
private NbiTextPane packageListPane;
public ConflictedPackagesDialog() {
super();
initComponents();
setModal(true);
}
private void initComponents() {
packageListPane = new NbiTextPane();
packageListPane.setBorder(BorderFactory.createEtchedBorder());
ScrollPane packageListScrollPane = new ScrollPane();
packageListScrollPane.add(packageListPane);
descriptionPane = new NbiTextPane();
descriptionPane.setBorder(BorderFactory.createEtchedBorder());
ScrollPane descriptionScrollPane = new ScrollPane();
descriptionScrollPane.add(descriptionPane);
okButton = new NbiButton();
okButton.setText(CLOSE_BUTTON_TEXT);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
removeButton = new NbiButton();
removeButton.setText("Remove it now");
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
componentPanel = new NbiPanel();
header = new NbiLabel();
componentPanel.setLayout(new GridBagLayout());
componentPanel.add(header, new GridBagConstraints(
0, 0, // x, y
2, 1, // width, height
0.0, 0.0, // weight-x, weight-y
GridBagConstraints.PAGE_START, // anchor
GridBagConstraints.HORIZONTAL, // fill
new Insets(10, 10, 10, 10), // padding
0, 0));
componentPanel.add(packageListScrollPane, new GridBagConstraints(
0, 1, // x, y
1, 1, // width, height
1.0, 1.0, // weight-x, weight-y
GridBagConstraints.LINE_START, // anchor
GridBagConstraints.BOTH, // fill
new Insets(10, 10, 10, 10), // padding
0, 0));
componentPanel.add(descriptionScrollPane, new GridBagConstraints(
1, 1, // x, y
1, 1, // width, height
1.0, 1.0, // weight-x, weight-y
GridBagConstraints.LINE_END, // anchor
GridBagConstraints.BOTH, // fill
new Insets(10, 10, 10, 10), // padding
0, 0));
buttonsPanel = new NbiPanel();
buttonsPanel.add(okButton, new GridBagConstraints(
0, 0, // x, y
1, 1, // width, height
0.0, 0.0, // weight-x, weight-y
GridBagConstraints.CENTER, // anchor
GridBagConstraints.NONE, // fill
new Insets(0, 0, 10, 0), // padding
0, 0)); // padx, pady - ???)
/* buttonsPanel.add(removeButton, new GridBagConstraints(
1, 0, // x, y
1, 1, // width, height
1.0, 0.0, // weight-x, weight-y
GridBagConstraints.CENTER, // anchor
GridBagConstraints.NONE, // fill
new Insets(0, 0, 0, 0), // padding
0, 0)); // padx, pady - ???)
*/
getContentPane().add(componentPanel, new GridBagConstraints(
0, 0, // x, y
1, 1, // width, height
1.0, 1.0, // weight-x, weight-y
GridBagConstraints.PAGE_START, // anchor
GridBagConstraints.BOTH, // fill
new Insets(6, 11, 0, 11), // padding
0, 0)); // padx, pady - ???
getContentPane().add(buttonsPanel, new GridBagConstraints(
0, 1, // x, y
1, 1, // width, height
1.0, 0.0, // weight-x, weight-y
GridBagConstraints.PAGE_END, // anchor
GridBagConstraints.BOTH, // fill
new Insets(6, 11, 0, 11), // padding
0, 0)); // padx, pady - ???
}
public void show(String version, List<String> names) {
packageListPane.setText(StringUtils.asString(names, "\n"));
descriptionPane.setText(UNINSTALL_DESCRIPTION_TEXT);
String headerString = LIST_INSTALLED_PACKAGES_TEXT;
header.setText(StringUtils.format(headerString, version));
this.setTitle("Sun Studio " + version);
setVisible(true);
requestFocus();
}
}
}
| 45.644928 | 170 | 0.594645 |
ad0c24087802c88857bd7b7cb153ab880114efa8 | 2,861 | /*
* Copyright (c) 2012 - 2020 Arvato Systems GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arvatosystems.t9t.bpmn2;
import com.arvatosystems.t9t.base.CrudViewModel;
import com.arvatosystems.t9t.base.IViewModelContainer;
import com.arvatosystems.t9t.base.entities.FullTrackingWithVersion;
import com.arvatosystems.t9t.bpmn2.request.EventSubscriptionSearchRequest;
import com.arvatosystems.t9t.bpmn2.request.IncidentSearchRequest;
import com.arvatosystems.t9t.bpmn2.request.ProcessDefinitionSearchRequest;
import com.arvatosystems.t9t.bpmn2.request.ProcessInstanceSearchRequest;
public final class T9tBPMN2Models implements IViewModelContainer {
private static final CrudViewModel<ProcessDefinitionDTO, FullTrackingWithVersion> PROCESS_DEFINITION_BPMN2_VIEW_MODEL
= new CrudViewModel<>(
ProcessDefinitionDTO.BClass.INSTANCE, FullTrackingWithVersion.BClass.INSTANCE,
ProcessDefinitionSearchRequest.BClass.INSTANCE, null);
private static final CrudViewModel<ProcessInstanceDTO, FullTrackingWithVersion> PROCESS_INSTANCE_BPMN2_VIEW_MODEL
= new CrudViewModel<>(
ProcessInstanceDTO.BClass.INSTANCE, FullTrackingWithVersion.BClass.INSTANCE,
ProcessInstanceSearchRequest.BClass.INSTANCE, null);
private static final CrudViewModel<EventSubscriptionDTO, FullTrackingWithVersion> EVENT_SUBSCRIPTIONS_VIEW_MODEL
= new CrudViewModel<>(
EventSubscriptionDTO.BClass.INSTANCE, FullTrackingWithVersion.BClass.INSTANCE,
EventSubscriptionSearchRequest.BClass.INSTANCE, null);
private static final CrudViewModel<IncidentDTO, FullTrackingWithVersion> INCIDENTS_VIEW_MODEL
= new CrudViewModel<>(
IncidentDTO.BClass.INSTANCE, FullTrackingWithVersion.BClass.INSTANCE,
IncidentSearchRequest.BClass.INSTANCE, null);
@Override
public void register() {
IViewModelContainer.CRUD_VIEW_MODEL_REGISTRY.putIfAbsent("processDefinitionBpmn2", PROCESS_DEFINITION_BPMN2_VIEW_MODEL);
IViewModelContainer.CRUD_VIEW_MODEL_REGISTRY.putIfAbsent("processInstanceBpmn2", PROCESS_INSTANCE_BPMN2_VIEW_MODEL);
IViewModelContainer.CRUD_VIEW_MODEL_REGISTRY.putIfAbsent("eventSubscriptions", EVENT_SUBSCRIPTIONS_VIEW_MODEL);
IViewModelContainer.CRUD_VIEW_MODEL_REGISTRY.putIfAbsent("incidents", INCIDENTS_VIEW_MODEL);
}
}
| 51.089286 | 128 | 0.803216 |
dbfb6f8ecd40f72991e567e9edf40b5662ff18ca | 1,297 | /**
* @author Virtusa
*/
package org.bian.service;
import java.util.List;
import org.bian.dto.*;
public interface FraudAmlResolutionApiService {
FraudCaseBaseWithIdAndRoot executePost(FraudCaseBase request);
FraudCaseBaseWithIdAndRoot executePut(String crReferenceId, FraudCaseBase request);
RecordResponse record(String crReferenceId, FraudCaseBase request);
FraudCaseBaseWithIdAndRoot requestPost(FraudCaseBase request);
FraudCaseBaseWithIdAndRoot requestPut(String crReferenceId, FraudCaseBase request);
AnalysisBaseWithIdAndRoot retrieveAnalysis(String crReferenceId, String bqReferenceId);
List<String> retrieveBQIds(String crReferenceId, String behaviorQualifier);
List<String> retrieveBQs();
DeterminationBaseWithIdAndRoot retrieveDeterminations(String crReferenceId, String bqReferenceId);
FraudCaseBaseWithIdAndRoot retrieve(String crReferenceId);
List<String> retrieveRefIds();
ProceduresBaseWithIdAndRoot retrieveProcedures(String crReferenceId, String bqReferenceId);
ReportingBaseWithIdAndRoot retrieveReportings(String crReferenceId, String bqReferenceId);
ResolutionBaseWithIdAndRoot retrieveResolutions(String crReferenceId, String bqReferenceId);
FraudCaseBaseWithIdAndRoot update(String crReferenceId, FraudCaseBase request);
}
| 30.162791 | 99 | 0.837317 |
f17f1c059a5c21c4027d42da0824a4fc41378722 | 16,338 | /*
* JBoss, Home of Professional Open Source
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2005-2006,
* @author JBoss Inc.
*/
/*
* Copyright (C) 2002,
*
* Arjuna Technologies Limited,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: ACCoordinator.java,v 1.5 2005/05/19 12:13:37 nmcl Exp $
*/
package com.arjuna.mwlabs.wscf.model.sagas.arjunacore;
import com.arjuna.mw.wscf.logging.wscfLogger;
import com.arjuna.ats.arjuna.common.Uid;
import com.arjuna.ats.arjuna.coordinator.*;
import com.arjuna.mw.wscf.model.sagas.participants.*;
import com.arjuna.mw.wscf.model.sagas.exceptions.DuplicateSynchronizationException;
import com.arjuna.mw.wscf.model.sagas.exceptions.InvalidSynchronizationException;
import com.arjuna.mw.wscf.common.Qualifier;
import com.arjuna.mw.wscf.common.CoordinatorId;
import com.arjuna.mw.wsas.activity.Outcome;
import com.arjuna.mw.wsas.completionstatus.CompletionStatus;
import com.arjuna.mw.wsas.exceptions.SystemException;
import com.arjuna.mw.wsas.exceptions.WrongStateException;
import com.arjuna.mw.wsas.exceptions.ProtocolViolationException;
import com.arjuna.mw.wscf.exceptions.*;
/**
* This class represents a specific coordination instance. It inherits from
* ArjunaCore TwoPhaseCoordinator so we can do the prepare and commit when a
* BA client close is requested and have it roll back if anything goes wrong.
* The BA client cancel request maps through to TwoPhaseCoordinator cancel which
* also does what we need. Although we inherit synchronization support from
* TwoPhaseCoordinator it is not used by the BA code.
*
* This class also exposes a separate complete method which implements
* the deprectaed BA client complete operation allowing coordinator completion
* participants to be notified that they complete. This is pretty much redundant
* as complete gets called at close anyway.
*
* @author Mark Little (mark.little@arjuna.com)
* @version $Id: ACCoordinator.java,v 1.5 2005/05/19 12:13:37 nmcl Exp $
* @since 1.0.
*
*/
public class BACoordinator extends TwoPhaseCoordinator
{
private final static int DELISTED = 0;
private final static int COMPLETED = 1;
private final static int FAILED = 2;
public BACoordinator()
{
super();
_theId = new CoordinatorIdImple(get_uid());
}
public BACoordinator(Uid recovery)
{
super(recovery);
_theId = new CoordinatorIdImple(get_uid());
}
/**
* If the application requires and if the coordination protocol supports it,
* then this method can be used to execute a coordination protocol on the
* currently enlisted participants at any time prior to the termination of
* the coordination scope.
*
* This implementation only supports coordination at the end of the
* activity.
*
* @exception WrongStateException
* Thrown if the coordinator is in a state the does not allow
* coordination to occur.
* @exception ProtocolViolationException
* Thrown if the protocol is violated in some manner during
* execution.
* @exception SystemException
* Thrown if any other error occurs.
*
* @return The result of executing the protocol, or null.
*/
public Outcome coordinate (CompletionStatus cs) throws WrongStateException,
ProtocolViolationException, SystemException
{
return null;
}
/**
* ensure all ParticipantCompletion participants have completed and then send a complete message to
* any remaining CoordinatorCompletion participants.
* @throws WrongStateException if the transaction is neither RUNNING nor PREPARED
* @throws SystemException if there are incomplete ParticipantCompletion participants or if one of the
* CoordinatorCompletion participants fails to complete.
*/
public synchronized void complete () throws WrongStateException,
SystemException
{
int status = status();
if (status == ActionStatus.RUNNING)
{
// check that all ParticipantCompletion participants have completed
// throwing a wobbly if not
if (pendingList != null)
{
RecordListIterator iter = new RecordListIterator(pendingList);
AbstractRecord absRec = iter.iterate();
while (absRec != null)
{
if (absRec instanceof ParticipantRecord)
{
ParticipantRecord pr = (ParticipantRecord) absRec;
if (!pr.complete()) {
// ok, we must force a rollback
preventCommit();
wscfLogger.i18NLogger.warn_model_sagas_arjunacore_BACoordinator_1(get_uid());
throw new SystemException("Participant failed to complete");
}
}
absRec = iter.iterate();
}
}
}
else
{
throw new WrongStateException();
}
}
/**
* close the activity
* @return the outcome of the close
* @throws SystemException
*/
public int close () throws SystemException
{
// we need to make sure all coordinator completion aprticipants ahve completed
try {
complete();
} catch (Exception e) {
// carry on as end will catch any further problems
}
// now call end(). if any of the participant completion participants are not
// completed they will throw a WrongStateException during prepare leading to rollback
return end(true);
}
/**
* cancel the activity
* @return the outcome of the cancel
*/
public int cancel ()
{
return super.cancel();
}
/**
* Enrol the specified participant with the coordinator associated with the
* current thread.
*
* @exception WrongStateException
* Thrown if the coordinator is not in a state that allows
* participants to be enrolled.
* @exception DuplicateParticipantException
* Thrown if the participant has already been enrolled and
* the coordination protocol does not support multiple
* entries.
* @exception InvalidParticipantException
* Thrown if the participant is invalid.
* @exception SystemException
* Thrown if any other error occurs.
*/
public void enlistParticipant (Participant act) throws WrongStateException,
DuplicateParticipantException, InvalidParticipantException,
SystemException
{
if (act == null) throw new InvalidParticipantException();
AbstractRecord rec = new ParticipantRecord((Participant)act, new Uid());
if (add(rec) != AddOutcome.AR_ADDED) throw new WrongStateException();
else
{
/*
* Presume nothing protocol, so we need to write the intentions list
* every time a participant is added.
*/
}
}
/**
* Remove the specified participant from the coordinator's list. this is the target of the
*
* @exception InvalidParticipantException
* Thrown if the participant is not known of by the
* coordinator.
* @exception WrongStateException
* Thrown if the state of the coordinator does not allow the
* participant to be removed
* @exception SystemException
* Thrown if any other error occurs.
*/
public synchronized void delistParticipant (String participantId)
throws InvalidParticipantException, WrongStateException,
SystemException
{
if (participantId == null)
throw new SystemException(
wscfLogger.i18NLogger.get_model_sagas_arjunacore_BACoordinator_2());
int status = status();
// exit is only legitimate when the TX is in these states
switch (status) {
case ActionStatus.RUNNING:
case ActionStatus.ABORT_ONLY:
changeParticipantStatus(participantId, DELISTED);
break;
default:
throw new WrongStateException(
wscfLogger.i18NLogger.get_model_sagas_arjunacore_BACoordinator_3());
}
}
public synchronized void participantCompleted (String participantId)
throws InvalidParticipantException, WrongStateException,
SystemException
{
if (participantId == null)
throw new SystemException(
wscfLogger.i18NLogger.get_model_sagas_arjunacore_BACoordinator_2());
int status = status();
// completed is only legitimate when the TX is in these states
switch (status) {
case ActionStatus.ABORTED:
break;
case ActionStatus.RUNNING:
case ActionStatus.ABORT_ONLY:
changeParticipantStatus(participantId, COMPLETED);
break;
default:
throw new WrongStateException(
wscfLogger.i18NLogger.get_model_sagas_arjunacore_BACoordinator_3());
}
}
public synchronized void participantFaulted (String participantId)
throws InvalidParticipantException, SystemException
{
if (participantId == null)
throw new SystemException(
wscfLogger.i18NLogger.get_model_sagas_arjunacore_BACoordinator_2());
int status = status();
// faulted is only legitimate when the TX is in these states
switch (status) {
case ActionStatus.RUNNING:
// if a participant notifies this then we need to mark the transaction as abort only
preventCommit();
// !!! deliberate drop through !!!
case ActionStatus.ABORT_ONLY:
case ActionStatus.COMMITTING:
case ActionStatus.COMMITTED: // this can happen during recovery processing
case ActionStatus.ABORTING:
changeParticipantStatus(participantId, FAILED);
break;
default:
throw new SystemException(
wscfLogger.i18NLogger.get_model_sagas_arjunacore_BACoordinator_3());
}
}
// n.b. this is only appropriate for the 1.1 protocol
public synchronized void participantCannotComplete (String participantId)
throws InvalidParticipantException, WrongStateException, SystemException
{
if (participantId == null)
throw new SystemException(
wscfLogger.i18NLogger.get_model_sagas_arjunacore_BACoordinator_2());
int status = status();
// cannot complete is only legitimate when the TX is in these states
switch (status) {
case ActionStatus.RUNNING:
// if a participant notifies this then we need to mark the transaction as abort only
preventCommit();
// !!! deliberate drop through !!!
case ActionStatus.ABORT_ONLY:
changeParticipantStatus(participantId, DELISTED);
break;
default:
throw new WrongStateException(
wscfLogger.i18NLogger.get_model_sagas_arjunacore_BACoordinator_3());
}
}
/**
* Enrol the specified synchronization with the coordinator associated with
* the current thread.
*
* @param act The synchronization to add.
*
* @exception WrongStateException
* Thrown if the coordinator is not in a state that allows
* participants to be enrolled.
* @exception DuplicateSynchronizationException
* Thrown if the participant has already been enrolled and
* the coordination protocol does not support multiple
* entries.
* @exception InvalidSynchronizationException
* Thrown if the participant is invalid.
* @exception SystemException
* Thrown if any other error occurs.
*/
public void enlistSynchronization (Synchronization act)
throws WrongStateException, DuplicateSynchronizationException,
InvalidSynchronizationException, SystemException
{
if (act == null)
throw new InvalidSynchronizationException();
SynchronizationRecord rec = new SynchronizationRecord(act, new Uid());
if (addSynchronization(rec) != AddOutcome.AR_ADDED)
throw new WrongStateException();
}
/**
* Remove the specified synchronization from the coordinator's list.
*
* @exception InvalidSynchronizationException
* Thrown if the participant is not known of by the
* coordinator.
* @exception WrongStateException
* Thrown if the state of the coordinator does not allow the
* participant to be removed (e.g., in a two-phase protocol
* the coordinator is committing.)
* @exception SystemException
* Thrown if any other error occurs.
*/
public void delistSynchronization (Synchronization act)
throws InvalidSynchronizationException, WrongStateException,
SystemException
{
if (act == null)
throw new InvalidSynchronizationException();
else
throw new WrongStateException(
wscfLogger.i18NLogger.get_model_sagas_arjunacore_BACoordinator_4());
}
/**
* @exception SystemException
* Thrown if any error occurs.
*
* @return the complete list of qualifiers that have been registered with
* the current coordinator.
*/
public Qualifier[] qualifiers () throws SystemException
{
return null;
}
/**
* @exception SystemException
* Thrown if any error occurs.
*
* @return The unique identity of the current coordinator.
*/
public CoordinatorId identifier () throws SystemException
{
return _theId;
}
public String type ()
{
return "/StateManager/BasicAction/AtomicAction/Sagas/BACoordinator";
}
private final void changeParticipantStatus (String participantId, int status)
throws InvalidParticipantException, SystemException
{
/*
* Transaction is active, so we can look at the pendingList only.
*/
// TODO allow transaction status to be changed during commit - exit
// could come in late
boolean found = false;
if (pendingList != null)
{
RecordListIterator iter = new RecordListIterator(pendingList);
AbstractRecord absRec = iter.iterate();
try
{
while ((absRec != null) && !found)
{
if (absRec instanceof ParticipantRecord)
{
ParticipantRecord pr = (ParticipantRecord) absRec;
Participant participant = (Participant) pr.value();
if (participantId.equals(participant.id()))
{
found = true;
if (status == DELISTED) {
pr.delist(false);
} else if (status == FAILED) {
pr.delist(true);
} else {
pr.completed();
}
}
}
absRec = iter.iterate();
}
}
catch (Exception ex)
{
throw new SystemException(ex.toString());
}
}
if (!found) throw new InvalidParticipantException();
}
private CoordinatorIdImple _theId;
}
| 33.479508 | 106 | 0.64555 |
1e9f666c95a95e197c4c5148889162971d59b2d1 | 2,289 | package se.claremont.taf.core.gui.teststructure;
import java.util.ArrayList;
import java.util.List;
public class TestStepList {
private List<TestStep> testSteps = new ArrayList<>();
private List<TestStepListChangeListener> changeListeners = new ArrayList<>();
public TestStepList(){
}
public void addChangeListener(TestStepListChangeListener listener){
changeListeners.add(listener);
}
public void removeChangeListener(TestStepListChangeListener listener){
if(!changeListeners.contains(listener)) return;
changeListeners.remove(listener);
}
public void add(TestStep testStep){
testSteps.add(testStep);
for(TestStepListChangeListener listener : changeListeners){
listener.isAdded(testStep);
}
}
public void remove(TestStep testStep){
if(testSteps.contains(testStep)){
for(TestStepListChangeListener listener : changeListeners){
listener.isRemoved(testStep);
}
testSteps.remove(testStep);
}
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("Test step list:[").append(System.lineSeparator());
for(TestStep testStep : testSteps){
sb.append("[name:'").append(testStep.getName())
.append("', type:'")
.append(testStep.getTestStepTypeShortName())
.append("', action:'")
.append(testStep.actionName)
.append("', element:'")
.append(testStep.elementName)
.append("', data:'")
.append(testStep.data)
.append("', description:'")
.append(testStep.getDescription())
.append("']")
.append(System.lineSeparator());
}
sb.append("]");
return sb.toString();
}
public List<TestStep> getTestSteps() {
return testSteps;
}
public abstract static class TestStepListChangeListener{
public TestStepListChangeListener(){}
public abstract void isAdded(TestStep testStep);
public abstract void isRemoved(TestStep testStep);
}
}
| 30.52 | 81 | 0.592398 |
b92962f7713fbc39e720f41ec65f6deb0c855e19 | 2,630 | package mage.deck;
import mage.cards.ExpansionSet;
import mage.cards.Sets;
import mage.cards.decks.Constructed;
/**
* LevelX2
*/
public class Legacy extends Constructed {
public Legacy() {
super("Constructed - Legacy");
for (ExpansionSet set : Sets.getInstance().values()) {
if (set.getSetType().isEternalLegal()) {
setCodes.add(set.getCode());
}
}
banned.add("Ancestral Recall");
banned.add("Arcum's Astrolabe");
banned.add("Balance");
banned.add("Bazaar of Baghdad");
banned.add("Black Lotus");
banned.add("Channel");
banned.add("Deathrite Shaman");
banned.add("Demonic Consultation");
banned.add("Demonic Tutor");
banned.add("Dig Through Time");
banned.add("Dreadhorde Arcanist");
banned.add("Earthcraft");
banned.add("Fastbond");
banned.add("Flash");
banned.add("Frantic Search");
banned.add("Gitaxian Probe");
banned.add("Goblin Recruiter");
banned.add("Gush");
banned.add("Hermit Druid");
banned.add("Imperial Seal");
banned.add("Library of Alexandria");
banned.add("Lurrus of the Dream-Den");
banned.add("Mana Crypt");
banned.add("Mana Drain");
banned.add("Mana Vault");
banned.add("Memory Jar");
banned.add("Mental Misstep");
banned.add("Mind's Desire");
banned.add("Mind Twist");
banned.add("Mishra's Workshop");
banned.add("Mox Emerald");
banned.add("Mox Jet");
banned.add("Mox Pearl");
banned.add("Mox Ruby");
banned.add("Mox Sapphire");
banned.add("Mystical Tutor");
banned.add("Necropotence");
banned.add("Oath of Druids");
banned.add("Oko, Thief of Crowns");
banned.add("Ragavan, Nimble Pilferer");
banned.add("Sensei's Divining Top");
banned.add("Skullclamp");
banned.add("Sol Ring");
banned.add("Strip Mine");
banned.add("Survival of the Fittest");
banned.add("Timetwister");
banned.add("Time Vault");
banned.add("Time Walk");
banned.add("Tinker");
banned.add("Tolarian Academy");
banned.add("Treasure Cruise");
banned.add("Underworld Breach");
banned.add("Vampiric Tutor");
banned.add("Wheel of Fortune");
banned.add("Windfall");
banned.add("Wrenn and Six");
banned.add("Yawgmoth's Bargain");
banned.add("Yawgmoth's Will");
banned.add("Zirda, the Dawnwaker");
}
}
| 32.875 | 62 | 0.569962 |
6adb4a95dc950af4624ede5abfab6e7741f3f7bf | 2,422 | package org.solent.devops.chargereconciler.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.Serializable;
public class Bill implements Serializable {
@JsonProperty("entry_camera")
private String entryCamera;
@JsonProperty("entry_time")
private String entryTime;
@JsonProperty("exit_camera")
private String exitCamera;
@JsonProperty("exit_time")
private String exitTime;
@JsonProperty("number_plate")
private String numberplate;
@JsonProperty("charge")
private Double charge;
@JsonProperty("charge_rate")
private Double rate;
public Bill(Vehicle entryVehicle, Vehicle exitVehicle) {
this.entryCamera = entryVehicle.getCameraId();
this.entryTime = entryVehicle.getTimestamp();
this.exitCamera = exitVehicle.getCameraId();
this.exitTime = exitVehicle.getTimestamp();
this.numberplate = entryVehicle.getNumberplate();
}
public String getEntryCamera() {
return entryCamera;
}
public void setEntryCamera(String entryCamera) {
this.entryCamera = entryCamera;
}
public String getEntryTime() {
return entryTime;
}
public void setEntryTime(String entryTime) {
this.entryTime = entryTime;
}
public String getExitCamera() {
return exitCamera;
}
public void setExitCamera(String exitCamera) {
this.exitCamera = exitCamera;
}
public String getExitTime() {
return exitTime;
}
public void setExitTime(String exitTime) {
this.exitTime = exitTime;
}
public String getNumberplate() {
return numberplate;
}
public void setNumberplate(String numberplate) {
this.numberplate = numberplate;
}
public Double getCharge() {
return charge;
}
public void setCharge(Double charge) {
this.charge = charge;
}
public Double getRate() {
return rate;
}
public void setRate(Double rate) {
this.rate = rate;
}
public String toJsonString() {
String json = null;
try {
json = new ObjectMapper().writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
}
| 23.980198 | 63 | 0.655244 |
34aa7eff73bd99f5aeffb64a26eec69f55a69e04 | 12,751 | /*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* bdoughan - Jan 27/2009 - 1.1 - Initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.sdo.helper.jaxbhelper.helpercontext;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import org.eclipse.persistence.exceptions.SDOException;
import org.eclipse.persistence.oxm.XMLContext;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.sdo.SDODataObject;
import org.eclipse.persistence.sdo.helper.SDODataFactory;
import org.eclipse.persistence.sdo.helper.SDOXMLHelper;
import org.eclipse.persistence.sdo.helper.delegates.SDODataFactoryDelegator;
import org.eclipse.persistence.sdo.helper.delegates.SDOTypeHelperDelegator;
import org.eclipse.persistence.sdo.helper.delegates.SDOXMLHelperDelegator;
import org.eclipse.persistence.sdo.helper.delegates.SDOXSDHelperDelegator;
import org.eclipse.persistence.sdo.helper.jaxb.JAXBHelperContext;
import org.eclipse.persistence.sdo.helper.jaxb.JAXBValueStore;
import org.eclipse.persistence.testing.sdo.SDOTestCase;
import commonj.sdo.DataObject;
import commonj.sdo.Type;
import commonj.sdo.helper.DataFactory;
import commonj.sdo.helper.HelperContext;
import commonj.sdo.helper.TypeHelper;
import commonj.sdo.helper.XMLHelper;
import commonj.sdo.helper.XSDHelper;
import commonj.sdo.impl.HelperProvider;
public class HelperContextTestCases extends SDOTestCase {
private JAXBHelperContext jaxbHelperContext;
public HelperContextTestCases(String name) {
super(name);
}
public void setUp() {
try {
Class[] classes = new Class[1];
classes[0] = Root.class;
JAXBContext jaxbContext = JAXBContext.newInstance(classes);
jaxbHelperContext = new JAXBHelperContext(jaxbContext);
jaxbHelperContext.makeDefaultContext();
JAXBSchemaOutputResolver sor = new JAXBSchemaOutputResolver();
jaxbContext.generateSchema(sor);
String xmlSchema = sor.getSchema();
jaxbHelperContext.getXSDHelper().define(xmlSchema);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public void testGetType() {
Type pojoType = jaxbHelperContext.getType(Root.class);
assertNotNull(pojoType);
Type rootType = jaxbHelperContext.getTypeHelper().getType("urn:helpercontext", "root");
assertSame(rootType, pojoType);
}
public void testGetClass() {
Type rootType = jaxbHelperContext.getTypeHelper().getType("urn:helpercontext", "root");
Class pojoClass = jaxbHelperContext.getClass(rootType);
assertSame(Root.class, pojoClass);
}
public void testGetClassNull() {
Class pojoClass = jaxbHelperContext.getClass(null);
assertNull(pojoClass);
}
public void testGetClassNegative() {
try {
Type propertyType = jaxbHelperContext.getTypeHelper().getType("commonj.sdo", "Property");
Class pojoClass = jaxbHelperContext.getClass(propertyType);
} catch(SDOException e) {
assertEquals(SDOException.SDO_JAXB_NO_DESCRIPTOR_FOR_TYPE, e.getErrorCode());
return;
}
fail("An exception should have been thrown, but was not.");
}
public void testDataFactoryGetHelperContext() {
SDODataFactoryDelegator sdoDataFactoryDelegator = (SDODataFactoryDelegator) DataFactory.INSTANCE;
HelperContext testDefaultHelperContext = sdoDataFactoryDelegator.getHelperContext();
assertSame(HelperProvider.getDefaultContext(), testDefaultHelperContext);
HelperContext testHelperContext = sdoDataFactoryDelegator.getDataFactoryDelegate().getHelperContext();
assertSame(jaxbHelperContext, testHelperContext);
}
public void testTypeHelperGetHelperContext() {
SDOTypeHelperDelegator sdoTypeHelperDelegator = (SDOTypeHelperDelegator) TypeHelper.INSTANCE;
HelperContext testDefaultHelperContext = sdoTypeHelperDelegator.getHelperContext();
assertSame(HelperProvider.getDefaultContext(), testDefaultHelperContext);
HelperContext testHelperContext = sdoTypeHelperDelegator.getTypeHelperDelegate().getHelperContext();
assertSame(jaxbHelperContext, testHelperContext);
}
public void testXMLHelperGetHelperContext() {
SDOXMLHelperDelegator sdoXMLHelperDelegator = (SDOXMLHelperDelegator) XMLHelper.INSTANCE;
HelperContext testDefaultHelperContext = sdoXMLHelperDelegator.getHelperContext();
assertSame(HelperProvider.getDefaultContext(), testDefaultHelperContext);
HelperContext testHelperContext = sdoXMLHelperDelegator.getXMLHelperDelegate().getHelperContext();
assertSame(jaxbHelperContext, testHelperContext);
}
public void testXSDHelperGetHelperContext() {
SDOXSDHelperDelegator sdoXSDHelperDelegator = (SDOXSDHelperDelegator) XSDHelper.INSTANCE;
HelperContext testDefaultHelperContext = sdoXSDHelperDelegator.getHelperContext();
assertSame(HelperProvider.getDefaultContext(), testDefaultHelperContext);
HelperContext testHelperContext = sdoXSDHelperDelegator.getXSDHelperDelegate().getHelperContext();
assertSame(jaxbHelperContext, testHelperContext);
}
public void testWrap() {
Root root = new Root();
SDODataObject rootDO = (SDODataObject) jaxbHelperContext.wrap(root);
assertNotNull(rootDO);
assertSame(JAXBValueStore.class, rootDO._getCurrentValueStore().getClass());
}
public void testWrapTwice() {
Root root = new Root();
SDODataObject rootDO1 = (SDODataObject) jaxbHelperContext.wrap(root);
assertNotNull(rootDO1);
SDODataObject rootDO2 = (SDODataObject) jaxbHelperContext.wrap(root);
assertNotNull(rootDO2);
assertSame(rootDO1, rootDO2);
}
public void testWrapCollection() {
Root root1 = new Root();
Root root2 = new Root();
Set collection = new HashSet(2);
collection.add(root1);
collection.add(root2);
List<DataObject> wrappedList = jaxbHelperContext.wrap(collection);
for(DataObject dataObject: wrappedList) {
assertNotNull(dataObject);
assertSame(JAXBValueStore.class, ((SDODataObject) dataObject)._getCurrentValueStore().getClass());
}
}
public void testWrapNullCollection() {
List<DataObject> wrappedList = jaxbHelperContext.wrap(null);
assertNotNull(wrappedList);
assertEquals(0, wrappedList.size());
}
public void testWrapEmptyCollection() {
Set collection = new HashSet(0);
List<DataObject> wrappedList = jaxbHelperContext.wrap(collection);
assertNotNull(wrappedList);
assertEquals(0, wrappedList.size());
}
public void testWrapNull() {
DataObject nullDO = jaxbHelperContext.wrap((Object) null);
assertNull(nullDO);
}
public void testWrapUnknownObject() {
boolean fail = true;
try {
Object unknownObject = "FOO";
jaxbHelperContext.wrap(unknownObject);
} catch(SDOException e) {
if(e.getErrorCode() == SDOException.SDO_JAXB_NO_TYPE_FOR_CLASS) {
fail = false;
}
}
if(fail) {
fail();
}
}
public void testWrapObjectWithoutSchemaReference() {
boolean fail = true;
try {
org.eclipse.persistence.jaxb.JAXBContext jaxbContext = (org.eclipse.persistence.jaxb.JAXBContext) jaxbHelperContext.getJAXBContext();
XMLDescriptor xmlDescriptor = (XMLDescriptor) jaxbContext.getXMLContext().getSession(Root.class).getDescriptor(Root.class);
xmlDescriptor.setSchemaReference(null);
jaxbHelperContext.wrap(new Root());
} catch(SDOException e) {
if(e.getErrorCode() == SDOException.SDO_JAXB_NO_SCHEMA_REFERENCE) {
fail = false;
}
}
if(fail) {
fail();
}
}
public void testWrapObjectWithoutSchemaContext() {
boolean fail = true;
try {
org.eclipse.persistence.jaxb.JAXBContext jaxbContext = (org.eclipse.persistence.jaxb.JAXBContext) jaxbHelperContext.getJAXBContext();
XMLDescriptor xmlDescriptor = (XMLDescriptor) jaxbContext.getXMLContext().getSession(Root.class).getDescriptor(Root.class);
xmlDescriptor.getSchemaReference().setSchemaContext(null);
xmlDescriptor.getSchemaReference().setSchemaContextAsQName(null);
jaxbHelperContext.wrap(new Root());
} catch(SDOException e) {
if(e.getErrorCode() == SDOException.SDO_JAXB_NO_SCHEMA_CONTEXT) {
fail = false;
}
}
if(fail) {
fail();
}
}
public void testWrapObjectWithIncorrectSchemaContext() {
boolean fail = true;
try {
org.eclipse.persistence.jaxb.JAXBContext jaxbContext = (org.eclipse.persistence.jaxb.JAXBContext) jaxbHelperContext.getJAXBContext();
XMLDescriptor xmlDescriptor = (XMLDescriptor) jaxbContext.getXMLContext().getSession(Root.class).getDescriptor(Root.class);
xmlDescriptor.getSchemaReference().setSchemaContext("/INVALID");
xmlDescriptor.getSchemaReference().setSchemaContextAsQName(null);
jaxbHelperContext.wrap(new Root());
} catch(SDOException e) {
if(e.getErrorCode() == SDOException.SDO_JAXB_NO_TYPE_FOR_CLASS_BY_SCHEMA_CONTEXT) {
fail = false;
}
}
if(fail) {
fail();
}
}
public void testUnwrap() {
Root root = new Root();
SDODataObject rootDO = (SDODataObject) jaxbHelperContext.wrap(root);
assertSame(root, jaxbHelperContext.unwrap(rootDO));
}
public void testUnwrapNull() {
Object object = jaxbHelperContext.unwrap((DataObject) null);
assertNull(object);
}
public void testUnwrapCollection() {
Root root1 = new Root();
Root root2 = new Root();
Set collection = new HashSet(2);
collection.add(root1);
collection.add(root2);
Collection<DataObject> wrappedEntities = jaxbHelperContext.wrap(collection);
List<Object> entities = jaxbHelperContext.unwrap(wrappedEntities);
assertNotNull(entities);
assertEquals(2, entities.size());
assertTrue(entities.contains(root1));
assertTrue(entities.contains(root2));
}
public void testUnwrapNullCollection() {
List<Object> entities = jaxbHelperContext.unwrap((Collection) null);
assertNotNull(entities);
assertEquals(0, entities.size());
}
public void testUnwrapEmptyCollection() {
Collection wrappedCollection = new HashSet(0);
List entities = jaxbHelperContext.unwrap(wrappedCollection);
assertNotNull(entities);
assertEquals(0, entities.size());
}
public void tearDown() {
}
private class JAXBSchemaOutputResolver extends SchemaOutputResolver {
private StringWriter schemaWriter;
public String getSchema() {
return schemaWriter.toString();
}
public Result createOutput(String arg0, String arg1) throws IOException {
schemaWriter = new StringWriter();
return new StreamResult(schemaWriter);
}
}
}
| 39.354938 | 146 | 0.666614 |
4f9c7fe184fa01d252181b3aa52f5d49c4fb1c71 | 5,217 | /*
* Tencent is pleased to support the open source community by making Angel available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.angel.ml.utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class MathUtilsTest {
private static final Log LOG = LogFactory.getLog(MathsTest.class);
static {
PropertyConfigurator.configure("../conf/log4j.properties");
}
@Test public void testSigmoid() throws Exception {
float data[] = {0.000001f, 1f, 100f, 1000f};
for (int i = 0; i < data.length; i++) {
// LOG.info(sigmoid(data[i]));
// LOG.info(Math.exp(-data[i]));
assertTrue((Maths.sigmoid(data[i]) > 0.00f) && (Maths.sigmoid(data[i]) <= 1.00f));
}
}
@Test public void testSigmoid1() throws Exception {
double data[] = {0.000001, 1, 100, 1000};
for (int i = 0; i < data.length; i++) {
assertTrue((Maths.sigmoid(data[i]) > 0.00) && (Maths.sigmoid(data[i]) <= 1.00));
}
}
@Test public void testSoftmax() throws Exception {
double data[] = {0.2, 3, 4, 900, 1};
Maths.softmax(data);
for (int i = 0; i < data.length; i++) {
assertTrue((Maths.sigmoid(data[i]) > 0.00) && (Maths.sigmoid(data[i]) <= 1.00));
}
}
@Test public void testSoftmax1() throws Exception {
float data[] = {0.2f, 3f, 4f, 900f, 1f};
Maths.softmax(data);
for (int i = 0; i < data.length; i++) {
assertTrue((Maths.sigmoid(data[i]) > 0.00f) && (Maths.sigmoid(data[i]) <= 1.00f));
}
}
@Test public void testThresholdL1() throws Exception {
double data[] = {0.2, 3, -4, 900, -200};
assertTrue(Maths.thresholdL1(data[0], 20) == 0);
assertTrue(Maths.thresholdL1(data[1], 20) == 0);
assertTrue(Maths.thresholdL1(data[2], 20) == 0);
assertTrue(Maths.thresholdL1(data[3], 20) == 880.0);
assertTrue(Maths.thresholdL1(data[4], 20) == -180.0);
}
@Test public void testThresholdL11() throws Exception {
float data[] = {0.2f, 3f, -4f, 900f, -200f};
assertTrue(Maths.thresholdL1(data[0], 20) == 0f);
assertTrue(Maths.thresholdL1(data[1], 20) == 0f);
assertTrue(Maths.thresholdL1(data[2], 20) == 0f);
assertTrue(Maths.thresholdL1(data[3], 20) == 880.0f);
assertTrue(Maths.thresholdL1(data[4], 20) == -180.0f);
}
@Test public void testIsEven() throws Exception {
int data1[] = {2, 4, 6, 8, 10};
for (int i = 0; i < data1.length; i++)
assertTrue(Maths.isEven(data1[i]));
int data2[] = {1, 3, 5, 7, 9};
for (int i = 0; i < data2.length; i++)
assertFalse(Maths.isEven(data2[i]));
}
@Test public void testPow() throws Exception {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i = 0; i < a.length; i++)
assertTrue(Maths.pow(a[i], 0) == 1);
for (int i = 0; i < a.length; i++)
assertTrue(Maths.pow(a[i], 1) == a[i]);
for (int i = 0; i < a.length; i++)
assertTrue(Maths.pow(a[i], 2) == a[i] * a[i]);
for (int i = 0; i < a.length; i++)
assertTrue(Maths.pow(a[i], 3) == a[i] * a[i] * a[i]);
// when b is a negative number
for (int i = 0; i < a.length; i++)
assertTrue(Maths.pow(a[i], -2) == a[i] * a[i]);
}
@Test public void testShuffle() throws Exception {
}
@Test public void testIntList2Arr() throws Exception {
int data[] = {-1, 2, 3, 900};
List<Integer> integers = new ArrayList();
for (int i = 0; i < data.length; i++)
integers.add(i, data[i]);
int test[] = Maths.intList2Arr(integers);
assertArrayEquals(data, test);
}
@Test public void testFloatList2Arr() throws Exception {
float data[] = {-1f, 2f, 3f, 900f};
List<Float> floats = new ArrayList();
for (int i = 0; i < data.length; i++)
floats.add(i, data[i]);
float test[] = Maths.floatList2Arr(floats);
for (int i = 0; i < data.length; i++)
assertEquals(data[i], test[i], 0.0f);
}
@Test public void testList2Arr() throws Exception {
}
@Test public void testFindMaxIndex() throws Exception {
float data[] = {-1f, 2f, 3f, 900f};
int index = Maths.findMaxIndex(data);
assertEquals(index, 3);
}
@Test public void testDouble2Float() throws Exception {
float data[] = {-1.00f, 2.00f, 3.00f, 900.00f};
double test[] = {-1, 2, 3, 900};
float dataTest[] = Maths.double2Float(test);
for (int i = 0; i < data.length; i++)
assertEquals(data[i], dataTest[i], 0.0f);
}
@Test public void testMain() throws Exception {
}
}
| 33.229299 | 100 | 0.618171 |
8c3e0102ad46c43a7622622f4b3f9ec0058c1271 | 371 | /**
* Created by beyka on 5.1.17.
*/
package com.github.aantonello.tiffbitmapfactory;
public enum Orientation {
TOP_LEFT(1),
TOP_RIGHT(2),
BOT_RIGHT(3),
BOT_LEFT(4),
LEFT_TOP(5),
RIGHT_TOP(6),
RIGHT_BOT(7),
LEFT_BOT(8),
UNAVAILABLE(0);
final int ordinal;
Orientation(int ordinal) {
this.ordinal = ordinal;
}
}
| 16.130435 | 48 | 0.609164 |
e3625855ffc496e1957504895f350dc97d54e9ee | 65,830 | // Copyright (c) YugaByte, 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.yb.pgsql;
import java.io.File;
import java.lang.Math;
import java.sql.Connection;
import java.sql.Statement;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.io.FileUtils;
import org.yb.minicluster.MiniYBCluster;
import org.yb.minicluster.MiniYBClusterBuilder;
import org.yb.util.TableProperties;
import org.yb.util.YBBackupException;
import org.yb.util.YBBackupUtil;
import org.yb.util.YBTestRunnerNonSanitizersOrMac;
import com.google.common.collect.ImmutableMap;
import static org.yb.AssertionWrappers.assertArrayEquals;
import static org.yb.AssertionWrappers.assertEquals;
import static org.yb.AssertionWrappers.assertFalse;
import static org.yb.AssertionWrappers.assertGreaterThan;
import static org.yb.AssertionWrappers.assertLessThan;
import static org.yb.AssertionWrappers.assertTrue;
import static org.yb.AssertionWrappers.fail;
@RunWith(value=YBTestRunnerNonSanitizersOrMac.class)
public class TestYbBackup extends BasePgSQLTest {
private static final Logger LOG = LoggerFactory.getLogger(TestYbBackup.class);
@Before
public void initYBBackupUtil() {
YBBackupUtil.setTSAddresses(miniCluster.getTabletServers());
YBBackupUtil.setMasterAddresses(masterAddresses);
YBBackupUtil.setPostgresContactPoint(miniCluster.getPostgresContactPoints().get(0));
}
@Override
protected void customizeMiniClusterBuilder(MiniYBClusterBuilder builder) {
super.customizeMiniClusterBuilder(builder);
List<Map<String, String>> perTserverZonePlacementFlags = Arrays.asList(
ImmutableMap.of("placement_cloud", "cloud1",
"placement_region", "region1",
"placement_zone", "zone1"),
ImmutableMap.of("placement_cloud", "cloud2",
"placement_region", "region2",
"placement_zone", "zone2"),
ImmutableMap.of("placement_cloud", "cloud3",
"placement_region", "region3",
"placement_zone", "zone3"));
builder.perTServerFlags(perTserverZonePlacementFlags);
}
@Override
public int getTestMethodTimeoutSec() {
return 600; // Usual time for a test ~90 seconds. But can be much more on Jenkins.
}
@Override
protected int getNumShardsPerTServer() {
return 2;
}
public void doAlteredTableBackup(String dbName, TableProperties tp) throws Exception {
String colocString = tp.isColocated() ? "TRUE" : "FALSE";
String initialDBName = dbName + "1";
String restoreDBName = dbName + "2";
try (Statement stmt = connection.createStatement()) {
stmt.execute(String.format("CREATE DATABASE %s COLOCATED=%s", initialDBName, colocString));
}
try (Connection connection2 = getConnectionBuilder().withDatabase(initialDBName).connect();
Statement stmt = connection2.createStatement()) {
stmt.execute("CREATE TABLE test_tbl (h INT PRIMARY KEY, a INT, b FLOAT) " +
String.format("WITH (colocated = %s)", colocString));
for (int i = 1; i <= 2000; ++i) {
stmt.execute("INSERT INTO test_tbl (h, a, b) VALUES" +
" (" + String.valueOf(i) + // h
", " + String.valueOf(100 + i) + // a
", " + String.valueOf(2.14 + (float)i) + ")"); // b
}
stmt.execute("ALTER TABLE test_tbl DROP a");
String backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql." + initialDBName);
backupDir = new JSONObject(output).getString("snapshot_url");
stmt.execute("INSERT INTO test_tbl (h, b) VALUES (9999, 8.9)");
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql." + restoreDBName);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 3.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=2000", new Row(2000, 2002.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=9999", new Row(9999, 8.9));
}
try (Connection connection2 = getConnectionBuilder().withDatabase(restoreDBName).connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 3.14));
assertQuery(stmt, "SELECT b FROM test_tbl WHERE h=1", new Row(3.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=2000", new Row(2000, 2002.14));
assertQuery(stmt, "SELECT h FROM test_tbl WHERE h=2000", new Row(2000));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=9999");
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE " + initialDBName);
stmt.execute("DROP DATABASE " + restoreDBName);
}
}
@Test
public void testAlteredTable() throws Exception {
doAlteredTableBackup("altered_db", new TableProperties(
TableProperties.TP_YSQL | TableProperties.TP_NON_COLOCATED));
}
@Test
public void testAlteredTableInColocatedDB() throws Exception {
doAlteredTableBackup("altered_colocated_db", new TableProperties(
TableProperties.TP_YSQL | TableProperties.TP_COLOCATED));
}
@Test
public void testMixedColocatedDatabase() throws Exception {
String initialDBName = "yb_colocated";
String restoreDBName = "yb_colocated2";
try (Statement stmt = connection.createStatement()) {
stmt.execute(String.format("CREATE DATABASE %s COLOCATED=TRUE", initialDBName));
}
try (Connection connection2 = getConnectionBuilder().withDatabase(initialDBName).connect();
Statement stmt = connection2.createStatement()) {
// Create 3 tables, 2 colocated and 1 non colocated but in the same db.
stmt.execute("CREATE TABLE test_tbl1 (h INT PRIMARY KEY, a INT, b FLOAT) " +
"WITH (COLOCATED=TRUE)");
stmt.execute("CREATE TABLE test_tbl2 (h INT PRIMARY KEY, a INT, b FLOAT) " +
"WITH (COLOCATED=TRUE)");
stmt.execute("CREATE TABLE test_tbl3 (h INT PRIMARY KEY, a INT, b FLOAT) " +
"WITH (COLOCATED=FALSE)");
// Insert random rows/values for tables to snapshot
for (int j = 1; j <= 3; ++j) {
for (int i = 1; i <= 2000; ++i) {
stmt.execute("INSERT INTO test_tbl" + String.valueOf(j) + " (h, a, b) VALUES" +
" (" + String.valueOf(i * j) + // h
", " + String.valueOf((100 + i) * j) + // a
", " + String.valueOf((2.14 + (float)i) * j) + ")"); // b
}
}
String backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql." + initialDBName);
backupDir = new JSONObject(output).getString("snapshot_url");
// Insert more rows after taking the snapshot.
for (int j = 1; j <= 3; ++j) {
stmt.execute("INSERT INTO test_tbl" + String.valueOf(j) + " (h, a, b) VALUES" +
" (" + String.valueOf(9999 * j) + // h
", " + String.valueOf((100 + 9999) * j) + // a
", " + String.valueOf((2.14 + 9999f) * j) + ")"); // b
}
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql." + restoreDBName);
// Verify the original database has the rows we previously inserted.
for (int j = 1; j <= 3; ++j) {
for (int i : new int[] {1, 2000, 9999}) {
assertQuery(stmt, String.format("SELECT * FROM test_tbl%d WHERE h=%d", j, i * j),
new Row(i * j, (100 + i) * j, (2.14 + (float)i) * j));
}
}
}
// Verify that the new database and tables are properly configured.
List<String> tbl1Tablets = YBBackupUtil.getTabletsForTable("ysql." + restoreDBName,
"test_tbl1");
List<String> tbl2Tablets = YBBackupUtil.getTabletsForTable("ysql." + restoreDBName,
"test_tbl2");
List<String> tbl3Tablets = YBBackupUtil.getTabletsForTable("ysql." + restoreDBName,
"test_tbl3");
// test_tbl1 and test_tbl2 are colocated and so should share the exact same tablet.
assertEquals("test_tbl1 is not colocated", 1, tbl1Tablets.size());
assertEquals("test_tbl2 is not colocated", 1, tbl2Tablets.size());
assertArrayEquals("test_tbl1 and test_tbl2 do not share the same colocated tablet",
tbl1Tablets.toArray(), tbl2Tablets.toArray());
// test_tbl3 is not colocated so it should have more tablets.
assertTrue("test_tbl3 should have more than 1 tablet", tbl3Tablets.size() > 1);
assertFalse("test_tbl3 uses the colocated tablet", tbl3Tablets.contains(tbl1Tablets.get(0)));
try (Connection connection2 = getConnectionBuilder().withDatabase(restoreDBName).connect();
Statement stmt = connection2.createStatement()) {
// Verify the new database contains all the rows we inserted before taking the snapshot.
for (int j = 1; j <= 3; ++j) {
for (int i : new int[] {1, 500, 2000}) {
assertQuery(stmt, String.format("SELECT * FROM test_tbl%d WHERE h=%d", j, i * j),
new Row(i * j, (100 + i) * j, (2.14 + (float)i) * j));
assertQuery(stmt, String.format("SELECT h FROM test_tbl%d WHERE h=%d", j, i * j),
new Row(i * j));
assertQuery(stmt, String.format("SELECT a FROM test_tbl%d WHERE h=%d", j, i * j),
new Row((100 + i) * j));
assertQuery(stmt, String.format("SELECT b FROM test_tbl%d WHERE h=%d", j, i * j),
new Row((2.14 + (float)i) * j));
}
// Assert that this returns no rows.
assertQuery(stmt, String.format("SELECT * FROM test_tbl%d WHERE h=%d", j, 9999 * j));
}
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute(String.format("DROP DATABASE %s", initialDBName));
stmt.execute(String.format("DROP DATABASE %s", restoreDBName));
}
}
@Test
public void testAlteredTableInOriginalCluster() throws Exception {
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE test_tbl (h INT PRIMARY KEY, a INT, b FLOAT)");
for (int i = 1; i <= 2000; ++i) {
stmt.execute("INSERT INTO test_tbl (h, a, b) VALUES" +
" (" + String.valueOf(i) + // h
", " + String.valueOf(100 + i) + // a
", " + String.valueOf(2.14 + (float)i) + ")"); // b
}
String backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte");
backupDir = new JSONObject(output).getString("snapshot_url");
stmt.execute("ALTER TABLE test_tbl DROP a");
stmt.execute("INSERT INTO test_tbl (h, b) VALUES (9999, 8.9)");
try {
YBBackupUtil.runYbBackupRestore(backupDir);
fail("Backup restoring did not fail as expected");
} catch (YBBackupException ex) {
LOG.info("Expected exception", ex);
}
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2");
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 3.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=2000", new Row(2000, 2002.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=9999", new Row(9999, 8.9));
}
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 101, 3.14));
assertQuery(stmt, "SELECT b FROM test_tbl WHERE h=1", new Row(3.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=2000", new Row(2000, 2100, 2002.14));
assertQuery(stmt, "SELECT h FROM test_tbl WHERE h=2000", new Row(2000));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=9999");
}
}
@Test
public void testColocatedWithColocationIdAlreadySet() throws Exception {
String ybTablePropsSql = "SELECT c.relname, props.colocation_id"
+ " FROM pg_class c, yb_table_properties(c.oid) props"
+ " WHERE c.oid >= " + FIRST_NORMAL_OID
+ " ORDER BY c.relname";
String uniqueIndexOnlySql = "SELECT b FROM test_tbl WHERE b = 3.14";
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE DATABASE yb1 COLOCATED=TRUE");
}
try (Connection connection2 = getConnectionBuilder().withDatabase("yb1").connect();
Statement stmt = connection2.createStatement()) {
// Create a table with a set colocation_id.
stmt.execute("CREATE TABLE test_tbl ("
+ " h INT PRIMARY KEY,"
+ " a INT,"
+ " b FLOAT CONSTRAINT test_tbl_uniq UNIQUE WITH (colocation_id=654321)"
+ ") WITH (colocation_id=123456)");
stmt.execute("CREATE INDEX test_tbl_a_idx ON test_tbl (a ASC) WITH (colocation_id=11223344)");
stmt.execute("INSERT INTO test_tbl (h, a, b) VALUES (1, 101, 3.14)");
runInvalidQuery(stmt, "INSERT INTO test_tbl (h, a, b) VALUES (2, 202, 3.14)",
"violates unique constraint \"test_tbl_uniq\"");
assertQuery(stmt, ybTablePropsSql,
new Row("test_tbl", 123456),
new Row("test_tbl_a_idx", 11223344),
new Row("test_tbl_pkey", null),
new Row("test_tbl_uniq", 654321));
assertTrue(isIndexOnlyScan(stmt, uniqueIndexOnlySql, "test_tbl_uniq"));
// Check that backup and restore works fine.
String backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yb1");
backupDir = new JSONObject(output).getString("snapshot_url");
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2");
}
// Verify data is correct.
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 101, 3.14));
assertQuery(stmt, "SELECT b FROM test_tbl WHERE h=1", new Row(3.14));
assertQuery(stmt, ybTablePropsSql,
new Row("test_tbl", 123456),
new Row("test_tbl_a_idx", 11223344),
new Row("test_tbl_pkey", null),
new Row("test_tbl_uniq", 654321));
runInvalidQuery(stmt, "INSERT INTO test_tbl (h, a, b) VALUES (2, 202, 3.14)",
"violates unique constraint \"test_tbl_uniq\"");
assertTrue(isIndexOnlyScan(stmt, uniqueIndexOnlySql, "test_tbl_uniq"));
assertQuery(stmt, uniqueIndexOnlySql, new Row(3.14));
// Now try to do a backup/restore of the restored db.
String backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yb2");
backupDir = new JSONObject(output).getString("snapshot_url");
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb3");
}
// Verify data is correct.
try (Connection connection2 = getConnectionBuilder().withDatabase("yb3").connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 101, 3.14));
assertQuery(stmt, "SELECT b FROM test_tbl WHERE h=1", new Row(3.14));
assertQuery(stmt, ybTablePropsSql,
new Row("test_tbl", 123456),
new Row("test_tbl_a_idx", 11223344),
new Row("test_tbl_pkey", null),
new Row("test_tbl_uniq", 654321));
runInvalidQuery(stmt, "INSERT INTO test_tbl (h, a, b) VALUES (2, 202, 3.14)",
"violates unique constraint \"test_tbl_uniq\"");
assertTrue(isIndexOnlyScan(stmt, uniqueIndexOnlySql, "test_tbl_uniq"));
assertQuery(stmt, uniqueIndexOnlySql, new Row(3.14));
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE yb1");
stmt.execute("DROP DATABASE yb2");
stmt.execute("DROP DATABASE yb3");
}
}
@Ignore // TODO(alex): Enable after #11632 is fixed.
public void testTablegroups() throws Exception {
// TODO: Add constraint with a different tablegroup once #11600 is done.
String ybTablePropsSql = "SELECT c.relname, tg.grpname, props.colocation_id"
+ " FROM pg_class c, yb_table_properties(c.oid) props"
+ " LEFT JOIN pg_yb_tablegroup tg ON tg.oid = props.tablegroup_oid"
+ " WHERE c.oid >= " + FIRST_NORMAL_OID
+ " ORDER BY c.relname";
String uniqueIndexOnlySql = "SELECT b FROM test_tbl WHERE b = 3.14";
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE DATABASE yb1");
}
try (Connection connection2 = getConnectionBuilder().withDatabase("yb1").connect();
Statement stmt = connection2.createStatement()) {
stmt.execute("CREATE TABLEGROUP tg1");
stmt.execute("CREATE TABLEGROUP tg2");
stmt.execute("CREATE TABLE test_tbl ("
+ " h INT PRIMARY KEY,"
+ " a INT,"
+ " b FLOAT CONSTRAINT test_tbl_uniq UNIQUE WITH (colocation_id=654321)"
+ ") WITH (colocation_id=123456)"
+ " TABLEGROUP tg1");
stmt.execute("CREATE INDEX test_tbl_tg2_idx ON test_tbl (a ASC)"
+ " WITH (colocation_id=11223344) TABLEGROUP tg2");
stmt.execute("CREATE INDEX test_tbl_notg_idx ON test_tbl (a ASC) NO TABLEGROUP");
stmt.execute("INSERT INTO test_tbl (h, a, b) VALUES (1, 101, 3.14)");
runInvalidQuery(stmt, "INSERT INTO test_tbl (h, a, b) VALUES (2, 202, 3.14)",
"violates unique constraint \"test_tbl_uniq\"");
assertQuery(stmt, ybTablePropsSql,
new Row("test_tbl", "tg1", 123456),
new Row("test_tbl_notg_idx", null, null),
new Row("test_tbl_pkey", null, null),
new Row("test_tbl_tg2_idx", "tg2", 11223344),
new Row("test_tbl_uniq", "tg1", 654321));
assertTrue(isIndexOnlyScan(stmt, uniqueIndexOnlySql, "test_tbl_uniq"));
// Check that backup and restore works fine.
YBBackupUtil.runYbBackupCreate("--keyspace", "ysql.yb1");
YBBackupUtil.runYbBackupRestore("--keyspace", "ysql.yb2");
}
// Verify data is correct.
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 101, 3.14));
assertQuery(stmt, "SELECT b FROM test_tbl WHERE h=1", new Row(3.14));
assertQuery(stmt, ybTablePropsSql,
new Row("test_tbl", "tg1", 123456),
new Row("test_tbl_notg_idx", null, null),
new Row("test_tbl_pkey", null, null),
new Row("test_tbl_tg2_idx", "tg2", 11223344),
new Row("test_tbl_uniq", "tg1", 654321));
runInvalidQuery(stmt, "INSERT INTO test_tbl (h, a, b) VALUES (2, 202, 3.14)",
"violates unique constraint \"test_tbl_uniq\"");
assertTrue(isIndexOnlyScan(stmt, uniqueIndexOnlySql, "test_tbl_uniq"));
assertQuery(stmt, uniqueIndexOnlySql, new Row(3.14));
// Now try to do a backup/restore of the restored db.
YBBackupUtil.runYbBackupCreate("--keyspace", "ysql.yb2");
YBBackupUtil.runYbBackupRestore("--keyspace", "ysql.yb3");
}
// Verify data is correct.
try (Connection connection2 = getConnectionBuilder().withDatabase("yb3").connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 101, 3.14));
assertQuery(stmt, "SELECT b FROM test_tbl WHERE h=1", new Row(3.14));
assertQuery(stmt, ybTablePropsSql,
new Row("test_tbl", "tg1", 123456),
new Row("test_tbl_notg_idx", null, null),
new Row("test_tbl_pkey", null, null),
new Row("test_tbl_tg2_idx", "tg2", 11223344),
new Row("test_tbl_uniq", "tg1", 654321));
runInvalidQuery(stmt, "INSERT INTO test_tbl (h, a, b) VALUES (2, 202, 3.14)",
"violates unique constraint \"test_tbl_uniq\"");
assertTrue(isIndexOnlyScan(stmt, uniqueIndexOnlySql, "test_tbl_uniq"));
assertQuery(stmt, uniqueIndexOnlySql, new Row(3.14));
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE yb1");
stmt.execute("DROP DATABASE yb2");
stmt.execute("DROP DATABASE yb3");
}
}
@Test
public void testColocatedDatabaseRestoreToOriginalDB() throws Exception {
String initialDBName = "yb_colocated";
int num_tables = 2;
try (Statement stmt = connection.createStatement()) {
stmt.execute(String.format("CREATE DATABASE %s COLOCATED=TRUE", initialDBName));
}
try (Connection connection2 = getConnectionBuilder().withDatabase(initialDBName).connect();
Statement stmt = connection2.createStatement()) {
stmt.execute("CREATE TABLE test_tbl1 (h INT PRIMARY KEY, a INT, b FLOAT) " +
"WITH (COLOCATED=TRUE)");
stmt.execute("CREATE TABLE test_tbl2 (h INT PRIMARY KEY, a INT, b FLOAT) " +
"WITH (COLOCATED=TRUE)");
// Insert random rows/values for tables to snapshot
for (int j = 1; j <= num_tables; ++j) {
for (int i = 1; i <= 2000; ++i) {
stmt.execute("INSERT INTO test_tbl" + String.valueOf(j) + " (h, a, b) VALUES" +
" (" + String.valueOf(i * j) + // h
", " + String.valueOf((100 + i) * j) + // a
", " + String.valueOf((2.14 + (float)i) * j) + ")"); // b
}
}
String backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql." + initialDBName);
backupDir = new JSONObject(output).getString("snapshot_url");
// Truncate tables after taking the snapshot.
for (int j = 1; j <= num_tables; ++j) {
stmt.execute("TRUNCATE TABLE test_tbl" + String.valueOf(j));
}
// Restore back into this same database, this way all the ids will happen to be the same.
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql." + initialDBName);
// Verify rows.
for (int j = 1; j <= num_tables; ++j) {
for (int i : new int[] {1, 500, 2000}) {
assertQuery(stmt, String.format("SELECT * FROM test_tbl%d WHERE h=%d", j, i * j),
new Row(i * j, (100 + i) * j, (2.14 + (float)i) * j));
assertQuery(stmt, String.format("SELECT h FROM test_tbl%d WHERE h=%d", j, i * j),
new Row(i * j));
assertQuery(stmt, String.format("SELECT a FROM test_tbl%d WHERE h=%d", j, i * j),
new Row((100 + i) * j));
assertQuery(stmt, String.format("SELECT b FROM test_tbl%d WHERE h=%d", j, i * j),
new Row((2.14 + (float)i) * j));
}
}
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute(String.format("DROP DATABASE %s", initialDBName));
}
}
@Test
public void testAlteredTableWithNotNull() throws Exception {
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE test_tbl(id int)");
stmt.execute("ALTER TABLE test_tbl ADD a int NOT NULL");
stmt.execute("ALTER TABLE test_tbl ADD b int NULL");
stmt.execute("INSERT INTO test_tbl(id, a, b) VALUES (1, 2, 3)");
stmt.execute("INSERT INTO test_tbl(id, a) VALUES (2, 4)");
runInvalidQuery(
stmt, "INSERT INTO test_tbl(id, b) VALUES(3, 6)",
"null value in column \"a\" violates not-null constraint");
String backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte");
backupDir = new JSONObject(output).getString("snapshot_url");
stmt.execute("INSERT INTO test_tbl (id, a, b) VALUES (9999, 9, 9)");
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2");
assertQuery(stmt, "SELECT * FROM test_tbl WHERE id=1", new Row(1, 2, 3));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE id=2", new Row(2, 4, (Integer) null));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE id=3");
assertQuery(stmt, "SELECT * FROM test_tbl WHERE id=9999", new Row(9999, 9, 9));
}
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE id=1", new Row(1, 2, 3));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE id=2", new Row(2, 4, (Integer) null));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE id=3");
assertQuery(stmt, "SELECT * FROM test_tbl WHERE id=9999");
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE yb2");
}
}
@Test
public void testIndex() throws Exception {
String backupDir = null;
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE test_tbl (h INT PRIMARY KEY, a INT, b FLOAT)");
stmt.execute("CREATE INDEX test_idx ON test_tbl (a)");
for (int i = 1; i <= 1000; ++i) {
stmt.execute("INSERT INTO test_tbl (h, a, b) VALUES" +
" (" + String.valueOf(i) + // h
", " + String.valueOf(100 + i) + // a
", " + String.valueOf(2.14 + (float)i) + ")"); // b
}
backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte");
backupDir = new JSONObject(output).getString("snapshot_url");
stmt.execute("INSERT INTO test_tbl (h, a, b) VALUES (9999, 8888, 8.9)");
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 101, 3.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1000", new Row(1000, 1100, 1002.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=9999", new Row(9999, 8888, 8.9));
// Select via the index.
assertQuery(stmt, "SELECT * FROM test_tbl WHERE a=101", new Row(1, 101, 3.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE a=1100", new Row(1000, 1100, 1002.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE a=8888", new Row(9999, 8888, 8.9));
}
// Add a new node.
miniCluster.startTServer(getTServerFlags());
// Wait for node list refresh.
Thread.sleep(MiniYBCluster.CQL_NODE_LIST_REFRESH_SECS * 2 * 1000);
YBBackupUtil.setTSAddresses(miniCluster.getTabletServers());
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2");
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 101, 3.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1000", new Row(1000, 1100, 1002.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=9999");
// Select via the index.
assertQuery(stmt, "SELECT * FROM test_tbl WHERE a=101", new Row(1, 101, 3.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE a=1100", new Row(1000, 1100, 1002.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE a=8888");
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE yb2");
}
}
@Test
public void testIndexTypes() throws Exception {
String backupDir = null;
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE test_tbl (h INT PRIMARY KEY, c1 INT, c2 INT, c3 INT, c4 INT)");
stmt.execute("CREATE INDEX test_idx1 ON test_tbl (c1)");
stmt.execute("CREATE INDEX test_idx2 ON test_tbl (c2 HASH)");
stmt.execute("CREATE INDEX test_idx3 ON test_tbl (c3 ASC)");
stmt.execute("CREATE INDEX test_idx4 ON test_tbl (c4 DESC)");
stmt.execute("INSERT INTO test_tbl (h, c1, c2, c3, c4) VALUES (1, 11, 12, 13, 14)");
backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte");
backupDir = new JSONObject(output).getString("snapshot_url");
stmt.execute("INSERT INTO test_tbl (h, c1, c2, c3, c4) VALUES (9, 21, 22, 23, 24)");
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 11, 12, 13, 14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c1=11", new Row(1, 11, 12, 13, 14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c2=12", new Row(1, 11, 12, 13, 14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c3=13", new Row(1, 11, 12, 13, 14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c4=14", new Row(1, 11, 12, 13, 14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=9", new Row(9, 21, 22, 23, 24));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c1=21", new Row(9, 21, 22, 23, 24));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c2=22", new Row(9, 21, 22, 23, 24));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c3=23", new Row(9, 21, 22, 23, 24));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c4=24", new Row(9, 21, 22, 23, 24));
}
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2");
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 11, 12, 13, 14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c1=11", new Row(1, 11, 12, 13, 14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c2=12", new Row(1, 11, 12, 13, 14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c3=13", new Row(1, 11, 12, 13, 14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c4=14", new Row(1, 11, 12, 13, 14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=9");
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c1=21");
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c2=22");
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c3=23");
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c4=24");
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE yb2");
}
}
private void verifyCollationIndexData(Statement stmt, int test_step) throws Exception {
Row expectedLowerCaseRow = new Row("a", "b", "c", "d", "e");
Row expectedUpperCaseRow = new Row("A", "B", "C", "D", "E");
List<Row> expectedRows = test_step == 2 ? Arrays.asList(new Row("a", "b", "c", "d", "e"),
new Row("A", "B", "C", "D", "E"),
new Row("f", "g", "h", "i", "j"))
: Arrays.asList(new Row("a", "b", "c", "d", "e"),
new Row("A", "B", "C", "D", "E"));
assertRowList(stmt, "SELECT * FROM test_tbl ORDER BY h", expectedRows);
assertRowList(stmt, "SELECT * FROM test_tbl ORDER BY c1", expectedRows);
assertRowList(stmt, "SELECT * FROM test_tbl ORDER BY c2", expectedRows);
assertRowList(stmt, "SELECT * FROM test_tbl ORDER BY c3", expectedRows);
assertRowList(stmt, "SELECT * FROM test_tbl ORDER BY c4", expectedRows);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h='a'", expectedLowerCaseRow);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c1='b'", expectedLowerCaseRow);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c2='c'", expectedLowerCaseRow);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c3='d'", expectedLowerCaseRow);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c4='e'", expectedLowerCaseRow);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h='A'", expectedUpperCaseRow);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c1='B'", expectedUpperCaseRow);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c2='C'", expectedUpperCaseRow);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c3='D'", expectedUpperCaseRow);
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c4='E'", expectedUpperCaseRow);
if (test_step == 2) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h='f'", new Row("f", "g", "h", "i", "j"));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c1='g'", new Row("f", "g", "h", "i", "j"));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c2='h'", new Row("f", "g", "h", "i", "j"));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c3='i'", new Row("f", "g", "h", "i", "j"));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c4='j'", new Row("f", "g", "h", "i", "j"));
} else {
assertNoRows(stmt, "SELECT * FROM test_tbl WHERE h='f'");
assertNoRows(stmt, "SELECT * FROM test_tbl WHERE c1='g'");
assertNoRows(stmt, "SELECT * FROM test_tbl WHERE c2='h'");
assertNoRows(stmt, "SELECT * FROM test_tbl WHERE c3='i'");
assertNoRows(stmt, "SELECT * FROM test_tbl WHERE c4='j'");
}
}
private void testCollationIndexTypesHelper(String collName) throws Exception {
String backupDir = null;
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP TABLE IF EXISTS test_tbl");
stmt.execute("CREATE TABLE test_tbl (h TEXT PRIMARY KEY COLLATE \"" + collName + "\", " +
"c1 TEXT COLLATE \"" + collName + "\", " +
"c2 TEXT COLLATE \"" + collName + "\", " +
"c3 TEXT COLLATE \"" + collName + "\", " +
"c4 TEXT COLLATE \"" + collName + "\")");
stmt.execute("CREATE INDEX test_idx1 ON test_tbl (c1)");
stmt.execute("CREATE INDEX test_idx2 ON test_tbl (c2 HASH)");
stmt.execute("CREATE INDEX test_idx3 ON test_tbl (c3 ASC)");
stmt.execute("CREATE INDEX test_idx4 ON test_tbl (c4 DESC)");
stmt.execute("INSERT INTO test_tbl (h, c1, c2, c3, c4) VALUES ('a', 'b', 'c', 'd', 'e')");
stmt.execute("INSERT INTO test_tbl (h, c1, c2, c3, c4) VALUES ('A', 'B', 'C', 'D', 'E')");
verifyCollationIndexData(stmt, 1);
backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte");
backupDir = new JSONObject(output).getString("snapshot_url");
stmt.execute("INSERT INTO test_tbl (h, c1, c2, c3, c4) VALUES ('f', 'g', 'h', 'i', 'j')");
verifyCollationIndexData(stmt, 2);
}
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2");
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
verifyCollationIndexData(stmt, 3);
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE yb2");
}
}
@Test
public void testCollationIndexTypesEn() throws Exception {
testCollationIndexTypesHelper("en-US-x-icu");
}
@Test
public void testCollationIndexTypesSv() throws Exception {
testCollationIndexTypesHelper("sv-x-icu");
}
@Test
public void testCollationIndexTypesTr() throws Exception {
testCollationIndexTypesHelper("tr-x-icu");
}
private void verifyPartialIndexData(Statement stmt) throws Exception {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 11, 22));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c1=11", new Row(1, 11, 22));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE c2=22", new Row(1, 11, 22));
assertQuery(stmt, "SELECT * FROM \"WHERE_tbl\" WHERE h=1", new Row(1, 11, 22));
assertQuery(stmt, "SELECT * FROM \"WHERE_tbl\" WHERE \"WHERE_c1\"=11", new Row(1, 11, 22));
assertQuery(stmt, "SELECT * FROM \"WHERE_tbl\" WHERE \" WHERE c2\"=22", new Row(1, 11, 22));
}
@Test
public void testPartialIndexes() throws Exception {
String backupDir = null;
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE test_tbl (h INT PRIMARY KEY, c1 INT, c2 INT)");
stmt.execute("CREATE INDEX test_idx1 ON test_tbl (c1) WHERE (c1 IS NOT NULL)");
stmt.execute("CREATE INDEX test_idx2 ON test_tbl (c2 ASC) WHERE (c2 IS NOT NULL)");
stmt.execute("INSERT INTO test_tbl (h, c1, c2) VALUES (1, 11, 22)");
stmt.execute("CREATE TABLE \"WHERE_tbl\" " +
"(h INT PRIMARY KEY, \"WHERE_c1\" INT, \" WHERE c2\" INT)");
stmt.execute("CREATE INDEX ON \"WHERE_tbl\" " +
"(\"WHERE_c1\") WHERE (\"WHERE_c1\" IS NOT NULL)");
stmt.execute("CREATE INDEX ON \"WHERE_tbl\" " +
"(\" WHERE c2\") WHERE (\" WHERE c2\" IS NOT NULL)");
stmt.execute("INSERT INTO \"WHERE_tbl\" (h, \"WHERE_c1\", \" WHERE c2\") VALUES (1, 11, 22)");
backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte");
backupDir = new JSONObject(output).getString("snapshot_url");
verifyPartialIndexData(stmt);
}
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2");
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
verifyPartialIndexData(stmt);
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE yb2");
}
}
@Test
public void testRestoreWithRestoreTime() throws Exception {
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE test_tbl (h INT PRIMARY KEY, a INT, b FLOAT)");
for (int i = 1; i <= 2000; ++i) {
stmt.execute("INSERT INTO test_tbl (h, a, b) VALUES" +
" (" + String.valueOf(i) + // h
", " + String.valueOf(100 + i) + // a
", " + String.valueOf(2.14 + (float)i) + ")"); // b
}
// Get the current timestamp in microseconds.
String ts = Long.toString(ChronoUnit.MICROS.between(Instant.EPOCH, Instant.now()));
// Insert additional values into the table before taking the backup.
stmt.execute("INSERT INTO test_tbl (h, a, b) VALUES (9999, 789, 8.9)");
String backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte");
backupDir = new JSONObject(output).getString("snapshot_url");
// Backup using --restore_time.
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2", "--restore_time", ts);
}
// Verify we only restore the original rows.
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=1", new Row(1, 101, 3.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=2000", new Row(2000, 2100, 2002.14));
assertQuery(stmt, "SELECT * FROM test_tbl WHERE h=9999"); // Should not exist.
}
}
@Test
public void testBackupCreateGetBackupSize() throws Exception {
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE TABLE test_tbl (h INT PRIMARY KEY, a INT, b FLOAT)");
for (int i = 1; i <= 2000; ++i) {
stmt.execute("INSERT INTO test_tbl (h, a, b) VALUES" +
" (" + String.valueOf(i) + // h
", " + String.valueOf(100 + i) + // a
", " + String.valueOf(2.14 + (float)i) + ")"); // b
}
String backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte", "--pg_based_backup", "--disable_checksum");
JSONObject json = new JSONObject(output);
long expectedBackupSize = json.getLong("backup_size_in_bytes");
long actualBackupSize = FileUtils.sizeOfDirectory(new File(json.getString("snapshot_url")));
long allowedDelta = 1 * 1024; // 1 KB
assertLessThan(Math.abs(expectedBackupSize - actualBackupSize), allowedDelta);
}
}
@Test
public void testSedRegExpForYSQLDump() throws Exception {
try (Statement stmt = connection.createStatement()) {
stmt.execute("CREATE ROLE admin");
// Default DB & table owner is ROLE 'yugabyte'.
stmt.execute("CREATE TABLE test_tbl (h INT PRIMARY KEY, a INT)");
String backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte");
backupDir = new JSONObject(output).getString("snapshot_url");
// Restore with the table owner renaming on fly.
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2",
"--edit_ysql_dump_sed_reg_exp", "s|OWNER TO yugabyte_test|OWNER TO admin|");
// In this DB the table owner was not changed.
assertEquals("yugabyte_test", getOwnerForTable(stmt, "test_tbl"));
}
// Verify the changed table owner for the restored table.
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
assertEquals("admin", getOwnerForTable(stmt, "test_tbl"));
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE yb2");
}
}
public Set<String> subDirs(String path) throws Exception {
Set<String> dirs = new HashSet<String>();
for (File f : new File(path).listFiles(File::isDirectory)) {
dirs.add(f.getName());
}
return dirs;
}
public void checkTabletsInDir(String path, List<String>... tabletLists) throws Exception {
Set<String> dirs = subDirs(path);
for(List<String> tablets : tabletLists) {
for (String tabletID : tablets) {
assertTrue(dirs.contains("tablet-" + tabletID));
}
}
}
public String doCreateGeoPartitionedBackup(int numRegions, boolean useTablespaces)
throws Exception {
try (Statement stmt = connection.createStatement()) {
stmt.execute(
" CREATE TABLESPACE region1_ts " +
" WITH (replica_placement=" +
"'{\"num_replicas\":1, \"placement_blocks\":" +
"[{\"cloud\":\"cloud1\",\"region\":\"region1\",\"zone\":\"zone1\"," +
"\"min_num_replicas\":1}]}')");
stmt.execute(
" CREATE TABLESPACE region2_ts " +
" WITH (replica_placement=" +
"'{\"num_replicas\":1, \"placement_blocks\":" +
"[{\"cloud\":\"cloud2\",\"region\":\"region2\",\"zone\":\"zone2\"," +
"\"min_num_replicas\":1}]}')");
stmt.execute(
" CREATE TABLESPACE region3_ts " +
" WITH (replica_placement=" +
"'{\"num_replicas\":1, \"placement_blocks\":" +
"[{\"cloud\":\"cloud3\",\"region\":\"region3\",\"zone\":\"zone3\"," +
"\"min_num_replicas\":1}]}')");
stmt.execute("CREATE TABLE tbl (id INT, geo VARCHAR) PARTITION BY LIST (geo)");
stmt.execute("CREATE TABLE tbl_r1 PARTITION OF tbl (id, geo, PRIMARY KEY (id HASH, geo))" +
"FOR VALUES IN ('R1') TABLESPACE region1_ts");
stmt.execute("CREATE TABLE tbl_r2 PARTITION OF tbl (id, geo, PRIMARY KEY (id HASH, geo))" +
"FOR VALUES IN ('R2') TABLESPACE region2_ts");
stmt.execute("CREATE TABLE tbl_r3 PARTITION OF tbl (id, geo, PRIMARY KEY (id HASH, geo))" +
"FOR VALUES IN ('R3') TABLESPACE region3_ts");
// Check tablespaces for tables.
assertEquals(null, getTablespaceForTable(stmt, "tbl"));
assertEquals("region1_ts", getTablespaceForTable(stmt, "tbl_r1"));
assertEquals("region2_ts", getTablespaceForTable(stmt, "tbl_r2"));
assertEquals("region3_ts", getTablespaceForTable(stmt, "tbl_r3"));
for (int i = 1; i <= 2000; ++i) {
stmt.execute("INSERT INTO tbl (id, geo) VALUES" +
" (" + String.valueOf(i) + // id
", 'R" + String.valueOf(1 + i % 3) + "')"); // geo
}
List<String> tblTablets = getTabletsForTable("yugabyte", "tbl");
List<String> tblR1Tablets = getTabletsForTable("yugabyte", "tbl_r1");
List<String> tblR2Tablets = getTabletsForTable("yugabyte", "tbl_r2");
List<String> tblR3Tablets = getTabletsForTable("yugabyte", "tbl_r3");
String backupDir = YBBackupUtil.getTempBackupDir(), output = null;
List<String> args = new ArrayList<>(Arrays.asList("--keyspace", "ysql.yugabyte"));
if (useTablespaces) {
args.add("--use_tablespaces");
}
switch (numRegions) {
case 0:
args.addAll(Arrays.asList("--backup_location", backupDir));
output = YBBackupUtil.runYbBackupCreate(args);
backupDir = new JSONObject(output).getString("snapshot_url");
checkTabletsInDir(backupDir, tblTablets, tblR1Tablets, tblR2Tablets, tblR3Tablets);
break;
case 1:
args.addAll(Arrays.asList(
"--region", "region1", "--region_location", backupDir + "_reg1",
"--backup_location", backupDir));
output = YBBackupUtil.runYbBackupCreate(args);
backupDir = new JSONObject(output).getString("snapshot_url");
checkTabletsInDir(backupDir, tblR2Tablets, tblR3Tablets);
checkTabletsInDir(backupDir + "_reg1", tblR1Tablets);
break;
case 3:
args.addAll(Arrays.asList(
"--region", "region1", "--region_location", backupDir + "_reg1",
"--region", "region2", "--region_location", backupDir + "_reg2",
"--region", "region3", "--region_location", backupDir + "_reg3",
"--backup_location", backupDir));
output = YBBackupUtil.runYbBackupCreate(args);
backupDir = new JSONObject(output).getString("snapshot_url");
assertTrue(subDirs(backupDir).isEmpty());
checkTabletsInDir(backupDir + "_reg1", tblR1Tablets);
checkTabletsInDir(backupDir + "_reg2", tblR2Tablets);
checkTabletsInDir(backupDir + "_reg3", tblR3Tablets);
break;
default:
throw new IllegalArgumentException("Unexpected numRegions: " + numRegions);
}
return output;
}
}
public String doTestGeoPartitionedBackup(String targetDB, int numRegions, boolean useTablespaces)
throws Exception {
String output = null;
try (Statement stmt = connection.createStatement()) {
output = doCreateGeoPartitionedBackup(numRegions, useTablespaces);
JSONObject json = new JSONObject(output);
String backupDir = json.getString("snapshot_url");
stmt.execute("INSERT INTO tbl (id, geo) VALUES (9999, 'R1')");
assertQuery(stmt, "SELECT * FROM tbl WHERE id=1", new Row(1, "R2"));
assertQuery(stmt, "SELECT * FROM tbl WHERE id=2000", new Row(2000, "R3"));
assertQuery(stmt, "SELECT * FROM tbl WHERE id=9999", new Row(9999, "R1"));
assertQuery(stmt, "SELECT COUNT(*) FROM tbl", new Row(2001));
List<String> args = new ArrayList<>();
if (useTablespaces) {
args.add("--use_tablespaces");
}
if (!targetDB.equals("yugabyte")) {
// Drop TABLEs and TABLESPACEs.
stmt.execute("DROP TABLE tbl_r1");
stmt.execute("DROP TABLE tbl_r2");
stmt.execute("DROP TABLE tbl_r3");
stmt.execute("DROP TABLE tbl");
stmt.execute("DROP TABLESPACE region1_ts");
stmt.execute("DROP TABLESPACE region2_ts");
stmt.execute("DROP TABLESPACE region3_ts");
// Check global TABLESPACEs.
assertRowSet(stmt, "SELECT spcname FROM pg_tablespace",
asSet(new Row("pg_default"), new Row("pg_global")));
args.addAll(Arrays.asList("--keyspace", "ysql." + targetDB));
}
// else - overwriting existing tables in DB "yugabyte".
YBBackupUtil.runYbBackupRestore(backupDir, args);
}
try (Connection connection2 = getConnectionBuilder().withDatabase(targetDB).connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM tbl WHERE id=1", new Row(1, "R2"));
assertQuery(stmt, "SELECT * FROM tbl WHERE id=2000", new Row(2000, "R3"));
assertQuery(stmt, "SELECT COUNT(*) FROM tbl", new Row(2000));
// This row was inserted after backup so it is absent here.
assertNoRows(stmt, "SELECT * FROM tbl WHERE id=9999");
assertEquals(null, getTablespaceForTable(stmt, "tbl"));
// Check global TABLESPACEs.
Set<Row> expectedTablespaces = asSet(new Row("pg_default"), new Row("pg_global"));
if (useTablespaces || targetDB.equals("yugabyte")) {
assertEquals("region1_ts", getTablespaceForTable(stmt, "tbl_r1"));
assertEquals("region2_ts", getTablespaceForTable(stmt, "tbl_r2"));
assertEquals("region3_ts", getTablespaceForTable(stmt, "tbl_r3"));
expectedTablespaces.addAll(
asSet(new Row("region1_ts"), new Row("region2_ts"), new Row("region3_ts")));
} else {
assertEquals(null, getTablespaceForTable(stmt, "tbl_r1"));
assertEquals(null, getTablespaceForTable(stmt, "tbl_r2"));
assertEquals(null, getTablespaceForTable(stmt, "tbl_r3"));
}
assertRowSet(stmt, "SELECT spcname FROM pg_tablespace", expectedTablespaces);
}
if (!targetDB.equals("yugabyte")) {
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE " + targetDB);
}
}
return output;
}
@Test
public void testGeoPartitioning() throws Exception {
doTestGeoPartitionedBackup("db2", 3, false);
}
@Test
public void testGeoPartitioningNoRegions() throws Exception {
doTestGeoPartitionedBackup("db2", 0, false);
}
@Test
public void testGeoPartitioningOneRegion() throws Exception {
doTestGeoPartitionedBackup("db2", 1, false);
}
@Test
public void testGeoPartitioningRestoringIntoExisting() throws Exception {
doTestGeoPartitionedBackup("yugabyte", 3, false);
}
@Test
public void testGeoPartitioningWithTablespaces() throws Exception {
doTestGeoPartitionedBackup("db2", 3, true);
}
@Test
public void testGeoPartitioningNoRegionsWithTablespaces() throws Exception {
doTestGeoPartitionedBackup("db2", 0, true);
}
@Test
public void testGeoPartitioningOneRegionWithTablespaces() throws Exception {
doTestGeoPartitionedBackup("db2", 1, true);
}
@Test
public void testGeoPartitioningRestoringIntoExistingWithTablespaces() throws Exception {
doTestGeoPartitionedBackup("yugabyte", 3, true);
}
@Test
public void testGeoPartitioningDeleteBackup() throws Exception {
String output = doCreateGeoPartitionedBackup(3, false);
JSONObject json = new JSONObject(output);
String backupDir = json.getString("snapshot_url");
List<String> backupDirs = new ArrayList<String>(Arrays.asList(
backupDir, json.getString("region1"),
json.getString("region2"), json.getString("region3")));
LOG.info("Backup folders:" + backupDirs);
// Ensure the backup folders exist.
for (String dirName : backupDirs) {
LOG.info("Checking existing folder: " + dirName);
File dir = new File(dirName);
assertTrue(dir.exists());
assertGreaterThan(dir.length(), 0L);
}
YBBackupUtil.runYbBackupDelete(backupDir);
// Ensure the backup folders were deleted.
for (String dirName : backupDirs) {
LOG.info("Checking deleted folder: " + dirName);
File dir = new File(dirName);
assertFalse(dir.exists());
assertEquals(dir.length(), 0L);
}
}
@Test
public void testUserDefinedTypes() throws Exception {
// TODO(myang): Add ALTER TYPE test after #1893 is fixed.
String backupDir = null;
try (Statement stmt = connection.createStatement()) {
// A enum type.
stmt.execute("CREATE TYPE e_t AS ENUM('c', 'b', 'a')");
// Table column of enum type.
stmt.execute("CREATE TABLE test_tb1(c1 e_t)");
stmt.execute("INSERT INTO test_tb1 VALUES ('b'), ('c')");
// Table column of enum type with default value.
stmt.execute("CREATE TABLE test_tb2(c1 INT, c2 e_t DEFAULT 'a')");
stmt.execute("INSERT INTO test_tb2 VALUES(1)");
// A user-defined type.
stmt.execute("CREATE TYPE udt1 AS (f1 INT, f2 TEXT, f3 e_t)");
// Table column of user-defined type.
stmt.execute("CREATE TABLE test_tb3(c1 udt1)");
stmt.execute("INSERT INTO test_tb3 VALUES((1, '1', 'a'))");
stmt.execute("INSERT INTO test_tb3 VALUES((1, '2', 'b'))");
stmt.execute("INSERT INTO test_tb3 VALUES((1, '2', 'c'))");
// Table column of user-defined type and enum type with default values.
stmt.execute("CREATE TABLE test_tb4(c1 INT, c2 udt1 DEFAULT (1, '2', 'b'), " +
"c3 e_t DEFAULT 'b')");
stmt.execute("INSERT INTO test_tb4 VALUES (1)");
// Table column of enum array type.
stmt.execute("CREATE TABLE test_tb5 (c1 e_t[])");
stmt.execute("INSERT INTO test_tb5 VALUES (ARRAY['a', 'b', 'c']::e_t[])");
// nested user-defined type and enum type.
stmt.execute("CREATE TYPE udt2 AS (f1 INT, f2 udt1, f3 e_t)");
// Table column of nested user-defined type and enum type.
stmt.execute("CREATE TABLE test_tb6(c1 INT, c2 udt2, c3 e_t)");
stmt.execute("INSERT INTO test_tb6 VALUES (1, (1, (1, '1', 'a'), 'b'), 'c')");
// Table column of array of nested user-defined type and enum type.
stmt.execute("CREATE TABLE test_tb7 (c1 udt2[])");
stmt.execute("INSERT INTO test_tb7 VALUES (ARRAY[" +
"(1, (1, (1, '1', 'a'), 'b'), 'c')," +
"(2, (2, (2, '2', 'b'), 'a'), 'c')," +
"(3, (3, (3, '3', 'a'), 'c'), 'b')]::udt2[])");
// A domain type.
stmt.execute("CREATE DOMAIN dom AS TEXT " +
"check(value ~ '^\\d{5}$'or value ~ '^\\d{5}-\\d{4}$')");
// Table column of array of domain type.
stmt.execute("CREATE TABLE test_tb8(c1 dom[])");
stmt.execute("INSERT INTO test_tb8 VALUES (ARRAY['32768', '65536']::dom[])");
// A range type.
stmt.execute("CREATE TYPE inetrange AS RANGE(subtype = inet)");
// Table column of range type.
stmt.execute("CREATE TABLE test_tb9(c1 inetrange)");
stmt.execute("INSERT INTO test_tb9 VALUES ('[10.0.0.1,10.0.0.2]'::inetrange)");
// Table column of array of range type.
stmt.execute("CREATE TABLE test_tb10(c1 inetrange[])");
stmt.execute("INSERT INTO test_tb10 VALUES (ARRAY[" +
"'[10.0.0.1,10.0.0.2]'::inetrange, '[10.0.0.3,10.0.0.8]'::inetrange])");
// Test drop column in the middle.
stmt.execute("CREATE TABLE test_tb11(c1 e_t, c2 e_t, c3 e_t, c4 e_t)");
stmt.execute("INSERT INTO test_tb11 VALUES (" +
"'a', 'b', 'c', 'a'), ('a', 'c', 'b', 'b'), ('b', 'a', 'c', 'c')");
stmt.execute("ALTER TABLE test_tb11 DROP COLUMN c2");
backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte");
backupDir = new JSONObject(output).getString("snapshot_url");
stmt.execute("INSERT INTO test_tb1 VALUES ('a')");
stmt.execute("INSERT INTO test_tb2 VALUES(2)");
stmt.execute("INSERT INTO test_tb3 VALUES((2, '1', 'a'))");
stmt.execute("INSERT INTO test_tb3 VALUES((2, '2', 'b'))");
stmt.execute("INSERT INTO test_tb3 VALUES((2, '2', 'c'))");
stmt.execute("INSERT INTO test_tb4 VALUES (2)");
stmt.execute("INSERT INTO test_tb5 VALUES (ARRAY['c', 'b', 'a']::e_t[])");
stmt.execute("INSERT INTO test_tb6 VALUES (2, (2, (2, '2', 'c'), 'b'), 'a')");
stmt.execute("INSERT INTO test_tb7 VALUES (ARRAY[" +
"(4, (4, (4, '4', 'c'), 'b'), 'a')]::udt2[])");
stmt.execute("INSERT INTO test_tb8 VALUES (ARRAY['16384', '81920']::dom[])");
stmt.execute("INSERT INTO test_tb9 VALUES ('[10.0.0.3,10.0.0.8]'::inetrange)");
stmt.execute("INSERT INTO test_tb10 VALUES (array['[10.0.0.9,10.0.0.12]'::inetrange])");
stmt.execute("ALTER TABLE test_tb11 DROP COLUMN c3");
List<Row> expectedRows1 = Arrays.asList(new Row("c"),
new Row("b"),
new Row("a"));
List<Row> expectedRows2 = Arrays.asList(new Row(1, "a"),
new Row(2, "a"));
List<Row> expectedRows3 = Arrays.asList(new Row("(1,1,a)"),
new Row("(1,2,c)"),
new Row("(1,2,b)"),
new Row("(2,1,a)"),
new Row("(2,2,c)"),
new Row("(2,2,b)"));
List<Row> expectedRows4 = Arrays.asList(new Row(1, "(1,2,b)", "b"),
new Row(2, "(1,2,b)", "b"));
List<Row> expectedRows5 = Arrays.asList(new Row("{a,b,c}"),
new Row("{c,b,a}"));
List<Row> expectedRows6 = Arrays.asList(new Row(1, "(1,\"(1,1,a)\",b)", "c"),
new Row(2, "(2,\"(2,2,c)\",b)", "a"));
List<Row> expectedRows7 = Arrays.asList(
new Row("{\"(1,\\\"(1,\\\"\\\"(1,1,a)\\\"\\\",b)\\\",c)\"," +
"\"(2,\\\"(2,\\\"\\\"(2,2,b)\\\"\\\",a)\\\",c)\"," +
"\"(3,\\\"(3,\\\"\\\"(3,3,a)\\\"\\\",c)\\\",b)\"}"),
new Row("{\"(4,\\\"(4,\\\"\\\"(4,4,c)\\\"\\\",b)\\\",a)\"}"));
List<Row> expectedRows8 = Arrays.asList(new Row("{16384,81920}"),
new Row("{32768,65536}"));
List<Row> expectedRows9 = Arrays.asList(new Row("[10.0.0.1,10.0.0.2]"),
new Row("[10.0.0.3,10.0.0.8]"));
List<Row> expectedRows10 = Arrays.asList(
new Row("{\"[10.0.0.1,10.0.0.2]\",\"[10.0.0.3,10.0.0.8]\"}"),
new Row("{\"[10.0.0.9,10.0.0.12]\"}"));
// Column c2 and c3 are dropped from test_tbl1 so we only expect to see rows for
// column c1 and c4.
List<Row> expectedRows11 = Arrays.asList(new Row("b", "c"),
new Row("a", "b"),
new Row("a", "a"));
assertRowList(stmt, "SELECT * FROM test_tb1 ORDER BY c1", expectedRows1);
assertRowList(stmt, "SELECT * FROM test_tb1 ORDER BY c1", expectedRows1);
assertRowList(stmt, "SELECT * FROM test_tb2 ORDER BY c1", expectedRows2);
assertRowList(stmt, "SELECT * FROM test_tb3 ORDER BY c1", expectedRows3);
assertRowList(stmt, "SELECT * FROM test_tb4 ORDER BY c1", expectedRows4);
assertRowList(stmt, "SELECT c1::TEXT FROM test_tb5 ORDER BY c1", expectedRows5);
assertRowList(stmt, "SELECT * FROM test_tb6 ORDER BY c1", expectedRows6);
assertRowList(stmt, "SELECT c1::TEXT FROM test_tb7 ORDER BY c1", expectedRows7);
assertRowList(stmt, "SELECT c1::TEXT FROM test_tb8 ORDER BY c1", expectedRows8);
assertRowList(stmt, "SELECT * FROM test_tb9 ORDER BY c1", expectedRows9);
assertRowList(stmt, "SELECT c1::TEXT FROM test_tb10 ORDER BY c1", expectedRows10);
assertRowList(stmt, "SELECT * FROM test_tb11 ORDER BY c1, c4", expectedRows11);
}
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2");
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
List<Row> expectedRows1 = Arrays.asList(new Row("c"),
new Row("b"));
List<Row> expectedRows2 = Arrays.asList(new Row(1, "a"));
List<Row> expectedRows3 = Arrays.asList(new Row("(1,1,a)"),
new Row("(1,2,c)"),
new Row("(1,2,b)"));
List<Row> expectedRows4 = Arrays.asList(new Row(1, "(1,2,b)", "b"));
List<Row> expectedRows5 = Arrays.asList(new Row("{a,b,c}"));
List<Row> expectedRows6 = Arrays.asList(new Row(1, "(1,\"(1,1,a)\",b)", "c"));
List<Row> expectedRows7 = Arrays.asList(
new Row("{\"(1,\\\"(1,\\\"\\\"(1,1,a)\\\"\\\",b)\\\",c)\"," +
"\"(2,\\\"(2,\\\"\\\"(2,2,b)\\\"\\\",a)\\\",c)\"," +
"\"(3,\\\"(3,\\\"\\\"(3,3,a)\\\"\\\",c)\\\",b)\"}"));
List<Row> expectedRows8 = Arrays.asList(new Row("{32768,65536}"));
List<Row> expectedRows9 = Arrays.asList(new Row("[10.0.0.1,10.0.0.2]"));
List<Row> expectedRows10 = Arrays.asList(
new Row("{\"[10.0.0.1,10.0.0.2]\",\"[10.0.0.3,10.0.0.8]\"}"));
// Only column c2 is dropped from test_tbl1 before backup, the column c3 was dropped
// after backup and it should be restored. Therefore we expect to see rows for column
// c1, c3 and c4.
List<Row> expectedRows11 = Arrays.asList(new Row("b", "c", "c"),
new Row("a", "c", "a"),
new Row("a", "b", "b"));
assertRowList(stmt, "SELECT * FROM test_tb1 ORDER BY c1", expectedRows1);
assertRowList(stmt, "SELECT * FROM test_tb2 ORDER BY c1", expectedRows2);
assertRowList(stmt, "SELECT * FROM test_tb3 ORDER BY c1", expectedRows3);
assertRowList(stmt, "SELECT * FROM test_tb4 ORDER BY c1", expectedRows4);
assertRowList(stmt, "SELECT c1::TEXT FROM test_tb5 ORDER BY c1", expectedRows5);
assertRowList(stmt, "SELECT * FROM test_tb6 ORDER BY c1", expectedRows6);
assertRowList(stmt, "SELECT c1::TEXT FROM test_tb7 ORDER BY c1", expectedRows7);
assertRowList(stmt, "SELECT c1::TEXT FROM test_tb8 ORDER BY c1", expectedRows8);
assertRowList(stmt, "SELECT * FROM test_tb9 ORDER BY c1", expectedRows9);
assertRowList(stmt, "SELECT c1::TEXT FROM test_tb10 ORDER BY c1", expectedRows10);
assertRowList(stmt, "SELECT * FROM test_tb11 ORDER BY c1, c3, c4", expectedRows11);
}
// Cleanup.
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP DATABASE yb2");
}
}
private void testMaterializedViewsHelper(boolean matviewOnMatview) throws Exception {
String backupDir = null;
try (Statement stmt = connection.createStatement()) {
stmt.execute("DROP TABLE IF EXISTS test_tbl");
stmt.execute("CREATE TABLE test_tbl (t int)");
stmt.execute("CREATE MATERIALIZED VIEW test_mv AS SELECT * FROM test_tbl");
if (matviewOnMatview) {
stmt.execute("CREATE MATERIALIZED VIEW test_mv_2 AS SELECT * FROM test_mv");
}
stmt.execute("INSERT INTO test_tbl VALUES (1)");
stmt.execute("REFRESH MATERIALIZED VIEW test_mv");
if (matviewOnMatview) {
stmt.execute("REFRESH MATERIALIZED VIEW test_mv_2");
}
backupDir = YBBackupUtil.getTempBackupDir();
String output = YBBackupUtil.runYbBackupCreate("--backup_location", backupDir,
"--keyspace", "ysql.yugabyte");
backupDir = new JSONObject(output).getString("snapshot_url");
}
YBBackupUtil.runYbBackupRestore(backupDir, "--keyspace", "ysql.yb2");
try (Connection connection2 = getConnectionBuilder().withDatabase("yb2").connect();
Statement stmt = connection2.createStatement()) {
assertQuery(stmt, "SELECT * FROM test_mv WHERE t=1", new Row(1));
if (matviewOnMatview) {
assertQuery(stmt, "SELECT * FROM test_mv_2 WHERE t=1", new Row(1));
}
}
}
@Test
public void testRefreshedMaterializedViewsBackup() throws Exception {
testMaterializedViewsHelper(false);
}
@Test
public void testRefreshedMaterializedViewsOnMaterializedViewsBackup() throws Exception {
testMaterializedViewsHelper(true);
}
}
| 46.920884 | 100 | 0.619019 |
d865c4dd9ae6ab533de0ddcbbe67d132487552d3 | 2,178 | /*
* 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 de.oheimbrecht.ReadExcelHeader;
import org.pentaho.di.i18n.BaseMessages;
public class Messages {
public static final Class<Messages> PKG = Messages.class;
public static String getString(String key)
{
return BaseMessages.getString(PKG, key);
}
public static String getString(String key, String param1)
{
return BaseMessages.getString(PKG, key, param1);
}
public static String getString(String key, String param1, String param2)
{
return BaseMessages.getString(PKG, key, param1, param2);
}
public static String getString(String key, String param1, String param2, String param3)
{
return BaseMessages.getString(PKG, key, param1, param2, param3);
}
public static String getString(String key, String param1, String param2, String param3, String param4)
{
return BaseMessages.getString(PKG, key, param1, param2, param3, param4);
}
public static String getString(String key, String param1, String param2, String param3, String param4, String param5)
{
return BaseMessages.getString(PKG, key, param1, param2, param3, param4, param5);
}
public static String getString(String key, String param1, String param2, String param3, String param4, String param5, String param6)
{
return BaseMessages.getString(PKG, key, param1, param2, param3, param4, param5, param6);
}
}
| 35.704918 | 134 | 0.735537 |
50186e00f24c666f34901f56429aa0398792b787 | 88 | package eu.ebrains.kg.search.controller.indexing;
public interface InstanceHandler {
}
| 17.6 | 49 | 0.818182 |
d137647b6fadaa4f658a478b7868796859fbbe18 | 1,730 | package thaumcraft.client.renderers.entity.mob;
import net.minecraftforge.fml.relauncher.*;
import thaumcraft.client.renderers.models.entity.*;
import net.minecraft.util.*;
import net.minecraft.client.renderer.entity.*;
import net.minecraft.client.model.*;
import org.lwjgl.opengl.*;
import net.minecraft.entity.*;
@SideOnly(Side.CLIENT)
public class RenderEldritchGolem extends RenderLiving
{
protected ModelEldritchGolem modelMain;
private static final ResourceLocation skin;
public RenderEldritchGolem(final RenderManager rm, final ModelEldritchGolem par1ModelBiped, final float par2) {
super(rm, (ModelBase)par1ModelBiped, par2);
this.modelMain = par1ModelBiped;
}
protected ResourceLocation func_110775_a(final Entity entity) {
return RenderEldritchGolem.skin;
}
protected void func_77041_b(final EntityLivingBase par1EntityLiving, final float par2) {
GL11.glScalef(1.7f, 1.7f, 1.7f);
}
public void doRenderLiving(final EntityLiving golem, final double par2, final double par4, final double par6, final float par8, final float par9) {
GL11.glEnable(3042);
GL11.glAlphaFunc(516, 0.003921569f);
GL11.glBlendFunc(770, 771);
super.func_76986_a(golem, par2, par4, par6, par8, par9);
GL11.glDisable(3042);
GL11.glAlphaFunc(516, 0.1f);
}
public void func_76986_a(final EntityLiving par1Entity, final double par2, final double par4, final double par6, final float par8, final float par9) {
this.doRenderLiving(par1Entity, par2, par4, par6, par8, par9);
}
static {
skin = new ResourceLocation("thaumcraft", "textures/entity/eldritch_golem.png");
}
}
| 36.808511 | 154 | 0.715029 |
24071b512a996f8d6fb22a24dff0e5ee71752cdc | 7,158 | /*
* 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.myfaces.tobago.internal.config;
import org.apache.myfaces.tobago.context.ThemeImpl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class TobagoConfigParserUnitTest {
@Test
public void testParser() throws Exception {
generalTest("tobago-config-2.0.xml");
generalTest("tobago-config-4.0.xml");
}
@Test
public void testParserUntidy() throws Exception {
generalTest("tobago-config-untidy-2.0.xml");
}
private void generalTest(final String name)
throws IOException, SAXException, ParserConfigurationException, URISyntaxException {
final URL url = getClass().getClassLoader().getResource(name);
final TobagoConfigParser parser = new TobagoConfigParser();
final TobagoConfigFragment fragment = parser.parse(url);
Assertions.assertEquals("my-name", fragment.getName());
Assertions.assertEquals(1, fragment.getAfter().size());
Assertions.assertEquals("my-after", fragment.getAfter().get(0));
Assertions.assertEquals(2, fragment.getBefore().size());
Assertions.assertEquals("my-before-1", fragment.getBefore().get(0));
Assertions.assertEquals("my-before-2", fragment.getBefore().get(1));
Assertions.assertFalse(fragment.getCreateSessionSecret());
Assertions.assertFalse(fragment.getCheckSessionSecret());
Assertions.assertFalse(fragment.getPreventFrameAttacks());
final Map<String, String> directiveMap = fragment.getContentSecurityPolicy().getDirectiveMap();
final Set<Map.Entry<String, String>> entries = directiveMap.entrySet();
Assertions.assertEquals(2, entries.size());
Assertions.assertEquals("'self'", directiveMap.get("default-src"));
Assertions.assertEquals("http://apache.org", directiveMap.get("child-src"));
Assertions.assertEquals(2, fragment.getThemeDefinitions().size());
final ThemeImpl theme1 = fragment.getThemeDefinitions().get(0);
Assertions.assertEquals("my-theme-1", theme1.getName());
Assertions.assertEquals("My Theme 1", theme1.getDisplayName());
Assertions.assertEquals("script.js", theme1.getProductionResources().getScriptList().get(0).getName());
Assertions.assertEquals("style.css", theme1.getProductionResources().getStyleList().get(0).getName());
final ThemeImpl theme2 = fragment.getThemeDefinitions().get(1);
Assertions.assertEquals("my-theme-2", theme2.getName());
Assertions.assertEquals("my-theme-1", theme2.getFallbackName());
Assertions.assertEquals(0, theme2.getDevelopmentResources().getScriptList().size());
Assertions.assertEquals(0, theme2.getDevelopmentResources().getStyleList().size());
Assertions.assertEquals(0, theme2.getProductionResources().getScriptList().size());
Assertions.assertEquals(0, theme2.getProductionResources().getStyleList().size());
Assertions.assertFalse(fragment.getSetNosniffHeader(), "set-nosniff-header");
}
@Test
public void testParserFor10() throws Exception {
final URL url = getClass().getClassLoader().getResource("tobago-config-1.0.30.xml");
final TobagoConfigParser parser = new TobagoConfigParser();
final TobagoConfigFragment fragment = parser.parse(url);
Assertions.assertEquals("speyside", fragment.getDefaultThemeName());
}
@Test
public void testFailParserFor10() throws Exception {
final URL url = getClass().getClassLoader().getResource("tobago-config-fail-1.0.30.xml");
final TobagoConfigParser parser = new TobagoConfigParser();
try {
parser.parse(url);
Assertions.fail("No SAXParseException thrown!");
} catch (final SAXException e) {
// okay
}
}
@Test
public void testParserFor15() throws Exception {
final URL url = getClass().getClassLoader().getResource("tobago-config-1.5.xml");
final TobagoConfigParser parser = new TobagoConfigParser();
final TobagoConfigFragment fragment = parser.parse(url);
Assertions.assertEquals("speyside", fragment.getDefaultThemeName());
}
@Test
public void testFailParserFor15() throws Exception {
final URL url = getClass().getClassLoader().getResource("tobago-config-fail-1.5.xml");
final TobagoConfigParser parser = new TobagoConfigParser();
try {
parser.parse(url);
Assertions.fail("No SAXParseException thrown!");
} catch (final SAXException e) {
// okay
}
}
@Test
public void testFailParserFor20() throws Exception {
final URL url = getClass().getClassLoader().getResource("tobago-config-fail-2.0.xml");
final TobagoConfigParser parser = new TobagoConfigParser();
try {
parser.parse(url);
Assertions.fail("No SAXParseException thrown!");
} catch (final SAXException e) {
// okay
}
}
@Test
public void testFailParserForUnknownVersion() throws Exception {
final URL url = getClass().getClassLoader().getResource("tobago-config-fail-unknown-version.xml");
final TobagoConfigParser parser = new TobagoConfigParser();
try {
parser.parse(url);
Assertions.fail("No SAXParseException thrown!");
} catch (final SAXException e) {
// okay
}
}
@Test
public void testUniqueness() throws IllegalAccessException {
final Field[] all = TobagoConfigParser.class.getFields();
final List<Field> fields = new ArrayList<>();
for (final Field field : all) {
if (field.getType().equals(Integer.TYPE)) {
fields.add(field);
}
}
// uniqueness
final TobagoConfigParser dummy = new TobagoConfigParser();
final Set<Integer> hashCodes = new HashSet<>();
for (final Field field : fields) {
hashCodes.add(field.getInt(dummy));
}
Assertions.assertEquals(fields.size(), hashCodes.size(), "All used hash codes must be unique");
// check hash code values
for (final Field field : fields) {
final int hash = field.getInt(dummy);
final String name = field.getName().toLowerCase().replace('_', '-');
Assertions.assertEquals(name.hashCode(), hash, "Are the constants correct?");
}
}
}
| 38.691892 | 107 | 0.722269 |
ecf24b1f7d0f0511b68f0c8d31d408d42804de5c | 3,975 | package com.example.android.justjava;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
int quantity = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the plus button is clicked.
*/
public void increment(View view) {
if (quantity >99 ){
Toast.makeText(this,"sorry! can't accept more than 99 coffee cups per order",Toast.LENGTH_SHORT).show();
return;
}
quantity = quantity + 1;
displayQuantity(quantity);
}
/**
* This method is called when the minus button is clicked.
*/
public void decrement(View view) {
if(quantity<1){
Toast.makeText(this,"Sorry! can't go below 1 cup of coffee",Toast.LENGTH_SHORT).show();
return;
}
quantity = quantity - 1;
displayQuantity(quantity);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
// Figure out if the user wants whipped cream topping
CheckBox whippedCreamCheckBox = (CheckBox) findViewById(R.id.whipped_cream_checkbox);
boolean hasWhippedCream = whippedCreamCheckBox.isChecked();
// Figure out if the user wants chocolate topping
CheckBox chocolateCheckBox = (CheckBox) findViewById(R.id.chocolate_checkbox);
boolean hasChocolate = chocolateCheckBox.isChecked();
EditText nameEditText = (EditText) findViewById(R.id.name_input);
String name = nameEditText.getText().toString();
// Calculate the price
int price = calculatePrice(hasChocolate, hasWhippedCream) ;
// Display the order summary on the screen
String message = createOrderSummary(name ,price, hasWhippedCream, hasChocolate);
displayMessage(message);
}
/**
* Calculates the price of the order.
*
* @return total price
*/
private int calculatePrice(boolean needChocolate, boolean needWhippedCream) {
int basePrice= 5;
if(needChocolate){
basePrice = basePrice+2;
}
if(needWhippedCream){
basePrice = basePrice+1;
}
return basePrice*quantity;
}
/**
* Create summary of the order.
*
* @param price of the order
* @param addWhippedCream is whether or not to add whipped cream to the coffee
* @param addChocolate is whether or not to add chocolate to the coffee
* @return text summary
*/
private String createOrderSummary(String personName, int price, boolean addWhippedCream, boolean addChocolate) {
String priceMessage = "Name: "+personName;
priceMessage += "\nAdd whipped cream? " + addWhippedCream;
priceMessage += "\nAdd chocolate? " + addChocolate;
priceMessage += "\nQuantity: " + quantity;
priceMessage += "\nTotal: $" + price;
priceMessage += "\nThank you!";
return priceMessage;
}
/**
* This method displays the given quantity value on the screen.
*/
private void displayQuantity(int numberOfCoffees) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + numberOfCoffees);
}
/**
* This method displays the given text on the screen.
*/
private void displayMessage(String message) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
orderSummaryTextView.setText(message);
}
} | 31.299213 | 116 | 0.651321 |
62e10ef7a363684664aa95f6fbe1585980da4665 | 314 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package com.microsoft.accessibilityinsightsforandroidservice;
import android.content.Context;
public class ATFAScannerFactory {
public static ATFAScanner createATFAScanner(Context context) {
return new ATFAScanner(context);
}
}
| 24.153846 | 64 | 0.796178 |
661179cf0d5916e0463828cd504e35a57e6e4d28 | 455 | package de.altenerding.biber.pinkie.business.notification.control;
import de.altenerding.biber.pinkie.business.notification.entity.Message;
import org.apache.logging.log4j.Logger;
import javax.enterprise.event.Event;
import javax.inject.Inject;
public class NotificationProcessor {
@Inject
private Event<Message> messageEvent;
@Inject
private Logger logger;
@Inject
private NotificationSettingsProvider notificationSettingsProvider;
}
| 20.681818 | 72 | 0.815385 |
320a700d24e930b63fc0ec5e95c46580fbb00abe | 2,997 | /*
* XML Type: CT_PhoneticPr
* Namespace: http://schemas.openxmlformats.org/spreadsheetml/2006/main
* Java type: org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPhoneticPr
*
* Automatically generated - do not modify.
*/
package org.openxmlformats.schemas.spreadsheetml.x2006.main;
import org.apache.xmlbeans.impl.schema.ElementFactory;
import org.apache.xmlbeans.impl.schema.AbstractDocumentFactory;
import org.apache.xmlbeans.impl.schema.DocumentFactory;
import org.apache.xmlbeans.impl.schema.SimpleTypeFactory;
/**
* An XML CT_PhoneticPr(@http://schemas.openxmlformats.org/spreadsheetml/2006/main).
*
* This is a complex type.
*/
public interface CTPhoneticPr extends org.apache.xmlbeans.XmlObject {
DocumentFactory<org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPhoneticPr> Factory = new DocumentFactory<>(org.apache.poi.schemas.ooxml.system.ooxml.TypeSystemHolder.typeSystem, "ctphoneticpr898btype");
org.apache.xmlbeans.SchemaType type = Factory.getType();
/**
* Gets the "fontId" attribute
*/
long getFontId();
/**
* Gets (as xml) the "fontId" attribute
*/
org.openxmlformats.schemas.spreadsheetml.x2006.main.STFontId xgetFontId();
/**
* Sets the "fontId" attribute
*/
void setFontId(long fontId);
/**
* Sets (as xml) the "fontId" attribute
*/
void xsetFontId(org.openxmlformats.schemas.spreadsheetml.x2006.main.STFontId fontId);
/**
* Gets the "type" attribute
*/
org.openxmlformats.schemas.spreadsheetml.x2006.main.STPhoneticType.Enum getType();
/**
* Gets (as xml) the "type" attribute
*/
org.openxmlformats.schemas.spreadsheetml.x2006.main.STPhoneticType xgetType();
/**
* True if has "type" attribute
*/
boolean isSetType();
/**
* Sets the "type" attribute
*/
void setType(org.openxmlformats.schemas.spreadsheetml.x2006.main.STPhoneticType.Enum type);
/**
* Sets (as xml) the "type" attribute
*/
void xsetType(org.openxmlformats.schemas.spreadsheetml.x2006.main.STPhoneticType type);
/**
* Unsets the "type" attribute
*/
void unsetType();
/**
* Gets the "alignment" attribute
*/
org.openxmlformats.schemas.spreadsheetml.x2006.main.STPhoneticAlignment.Enum getAlignment();
/**
* Gets (as xml) the "alignment" attribute
*/
org.openxmlformats.schemas.spreadsheetml.x2006.main.STPhoneticAlignment xgetAlignment();
/**
* True if has "alignment" attribute
*/
boolean isSetAlignment();
/**
* Sets the "alignment" attribute
*/
void setAlignment(org.openxmlformats.schemas.spreadsheetml.x2006.main.STPhoneticAlignment.Enum alignment);
/**
* Sets (as xml) the "alignment" attribute
*/
void xsetAlignment(org.openxmlformats.schemas.spreadsheetml.x2006.main.STPhoneticAlignment alignment);
/**
* Unsets the "alignment" attribute
*/
void unsetAlignment();
}
| 28.273585 | 213 | 0.692693 |
34871267f475c853fea6639658ddba3d1df8fbb9 | 431 | package cn.cerc.sample.config;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import cn.cerc.mis.core.StartAppDefault;
@Controller
@Scope(WebApplicationContext.SCOPE_REQUEST)
@RequestMapping("/")
public class StartApp extends StartAppDefault {
}
| 26.9375 | 62 | 0.842227 |
7e753a1eb90e941deea15b603753d78e80c794a6 | 839 | package me.aikin.seed.model;
import java.io.Serializable;
import java.sql.Timestamp;
public class User implements Serializable {
private Long id; //TODO: generate auto
private String userName;
private Timestamp createdAt;
public User(Long id, String userName, Timestamp createdAt) {
this.id = id;
this.userName = userName;
this.createdAt = createdAt;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Timestamp getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
}
| 19.97619 | 64 | 0.628129 |
c97830814171e7b547790c42221cb6fff9f81d75 | 1,007 | package com.wagner.projecteuler.problem_004;
import com.wagner.shared.util.AlgorithmUtil;
/**
* User: DanielW
* Date: 07.12.2018
* Time: 15:00
*/
public class LargestPalindromeProduct {
/*
* A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
* Find the largest palindrome made from the product of two 3-digit numbers.
*/
public void test_find_largest_palindrome_product() {
long result = -1;
int factor1Max = -1;
int factor2Max = -1;
for (int factor1 = 999; factor1 > 0; factor1--) {
for (int factor2 = 999; factor2 > 0; factor2--) {
long product = factor1 * factor2;
if (AlgorithmUtil.isPalindromeNumber(product) && product > result) {
result = product;
factor1Max = factor1;
factor2Max = factor2;
}
}
}
System.out.println(result);
System.out.println(factor1Max);
System.out.println(factor2Max);
}
}
| 26.5 | 138 | 0.648461 |
0feae695730bf6a476df1a82c367099fd6a28241 | 1,792 | package com.java.test.ThirdInterface.wx;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.java.test.util.httputil.OkHttpUtil;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
/**
* @author yzm
* @date 2021/5/14 - 22:30
*/
@Service
public class WxService {
private static final String CODE_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
private static final String APP_ID = "wx0e143d0d62a658cb";
private static final String APP_SECRET = "190ff4e9547fe13dfc12ebdbabcea272";
// private static final String APP_ID = "wxef3104dfe2e8352c";
// private static final String APP_SECRET = "0d3130d28994679b9fe40c30b72db955";
private static final String GRANT_TYPE = "authorization_code";
public Map<String, String> getCode2Session(String code) throws Exception {
Map<String, Object> params = new HashMap<>(4);
params.put("appid", APP_ID);
params.put("secret", APP_SECRET);
params.put("js_code", code);
params.put("grant_type", GRANT_TYPE);
String s = OkHttpUtil.doGet(CODE_SESSION_URL, params);
JSONObject object = JSON.parseObject(s);
System.out.println(object);
Map<String, String> r = new HashMap<>(3);
r.put("session_key", object.get("session_key") == null ? null : object.get("session_key").toString());
r.put("openid", object.get("openid") == null ? null : object.get("openid").toString());
return r;
}
}
| 32.581818 | 110 | 0.713728 |
a412736f7138360987bfec7c49ab75636735ec3b | 2,642 | /*
* Testing Class for the analyzeText Function, produces randomly generated strings
*/
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class analyzeText {
public static String analyzeText1() throws IOException {
final int MAX_NUM_CHARS = 280;
Map<String, ArrayList<String>> theData = new HashMap<String, ArrayList<String>>();
Path thePath = Paths.get("/Users/nick/IdeaProjects/TwitterBot/src/main/resources/UserTweetData.txt");
byte[] theBytes = Files.readAllBytes(thePath);
String[] splitWords = new String(theBytes).trim().split(" ");
String userName = splitWords[0];
for (int i = 1; i < splitWords.length - 2; i++) {
String tempString = splitWords[i];
if (!tempString.contains('@' + "")) {
if (theData.containsKey(tempString)) {
if(splitWords[i + 1].contains("@"))
theData.get(tempString).add(splitWords[i + 2]);
else
theData.get(tempString).add(splitWords[i + 1]);
} else {
ArrayList<String> words = new ArrayList<>();
if(!splitWords[i + 1].contains("@"))
words.add(splitWords[i + 1]);
else
words.add(splitWords[i + 2]);
theData.put(tempString, words);
}
}
}
StringBuilder sb = new StringBuilder();
sb.append(userName);
sb.append(" ");
Random random = new Random();
int charCount = userName.length() + 1;
String currentWord = splitWords[random.nextInt(splitWords.length)];
while(currentWord.contains("@")){
currentWord = splitWords[random.nextInt(splitWords.length)];
}
while (charCount < MAX_NUM_CHARS) {
if (theData.get(currentWord) == null) {
currentWord = splitWords[random.nextInt(splitWords.length)];
}
int num = random.nextInt(theData.get(currentWord).size());
String nextWord = theData.get(currentWord).get(num);
sb.append(nextWord);
sb.append(" ");
charCount += nextWord.length() + 1;
currentWord = nextWord;
}
return sb.toString();
}
public static void main(String[] args) throws IOException{
System.out.println(analyzeText1());
}
}
| 33.443038 | 109 | 0.562074 |
287ea04d2afa1d39765552188164fa3b79f86448 | 3,557 | package com.teethen.xsdk.ninegrid.complex.news;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.teethen.sdk.xwidget.ninegrid.complex.ImageInfo;
import com.teethen.sdk.xwidget.ninegrid.complex.NineGridView;
import com.teethen.sdk.xwidget.ninegrid.preview.NineGridViewClickAdapter;
import com.teethen.xsdk.R;
import com.teethen.xsdk.ninegrid.complex.news.bean.NewsContent;
import com.teethen.xsdk.ninegrid.complex.news.bean.NewsImage;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class NewsContentAdapter extends RecyclerView.Adapter<NewsContentAdapter.PostViewHolder> {
private LayoutInflater mInflater;
private Context mContext;
private List<NewsContent> mDataList;
public NewsContentAdapter(Context context, List<NewsContent> data) {
super();
mContext = context;
mDataList = data;
mInflater = LayoutInflater.from(context);
}
@Override
public void onBindViewHolder(PostViewHolder holder, int position) {
holder.bind(mDataList.get(position));
}
@Override
public int getItemCount() {
return mDataList.size();
}
@Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new PostViewHolder(mInflater.inflate(R.layout.item_news, parent, false));
}
public void setData(List<NewsContent> data) {
mDataList = data;
notifyDataSetChanged();
}
public class PostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@BindView(R.id.title) TextView title;
@BindView(R.id.nineGrid) NineGridView nineGrid;
@BindView(R.id.desc) TextView desc;
@BindView(R.id.pubDate) TextView pubDate;
@BindView(R.id.source) TextView source;
private NewsContent item;
private View itemView;
public PostViewHolder(View itemView) {
super(itemView);
this.itemView = itemView;
ButterKnife.bind(this, itemView);
}
public void bind(NewsContent item) {
this.item = item;
title.setText(item.getTitle());
desc.setText(item.getDesc());
pubDate.setText(item.getPubDate());
source.setText(item.getSource());
ArrayList<ImageInfo> imageInfo = new ArrayList<>();
List<NewsImage> images = item.getImageUrls();
if (images != null) {
for (NewsImage image : images) {
ImageInfo info = new ImageInfo();
info.setThumbnailUrl(image.getUrl());
info.setBigImageUrl(image.getUrl());
imageInfo.add(info);
}
}
nineGrid.setAdapter(new NineGridViewClickAdapter(mContext, imageInfo));
if (images != null && images.size() == 1) {
nineGrid.setSingleImageRatio(images.get(0).getWidth() * 1.0f / images.get(0).getHeight());
}
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, NewsLinkActivity.class);
intent.putExtra(NewsLinkActivity.TAG_LINK_URL, item.getLink());
mContext.startActivity(intent);
}
}
}
| 33.87619 | 106 | 0.657295 |
8c8bdbbbc82ab9eb6dd7388ffacc9c28514f260c | 3,392 | package org.egov.waterconnection.web.models;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
import org.egov.common.contract.response.ResponseInfo;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
/**
* Contains the ResponseHeader and the created/updated property
*/
@ApiModel(description = "Contains the ResponseHeader and the created/updated property")
@Validated
@javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2019-10-24T10:29:25.253+05:30[Asia/Kolkata]")
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Builder
public class WaterConnectionResponse {
@JsonProperty("ResponseInfo")
private ResponseInfo responseInfo = null;
@JsonProperty("WaterConnection")
@Valid
private List<WaterConnection> waterConnection = null;
public WaterConnectionResponse responseInfo(ResponseInfo responseInfo) {
this.responseInfo = responseInfo;
return this;
}
/**
* Get responseInfo
*
* @return responseInfo
**/
@ApiModelProperty(value = "")
@Valid
public ResponseInfo getResponseInfo() {
return responseInfo;
}
public void setResponseInfo(ResponseInfo responseInfo) {
this.responseInfo = responseInfo;
}
public WaterConnectionResponse waterConnection(List<WaterConnection> waterConnection) {
this.waterConnection = waterConnection;
return this;
}
public WaterConnectionResponse addWaterConnectionItem(WaterConnection waterConnectionItem) {
if (this.waterConnection == null) {
this.waterConnection = new ArrayList<WaterConnection>();
}
this.waterConnection.add(waterConnectionItem);
return this;
}
/**
* Get waterConnection
*
* @return waterConnection
**/
@ApiModelProperty(value = "")
@Valid
public List<WaterConnection> getWaterConnection() {
return waterConnection;
}
public void setWaterConnection(List<WaterConnection> waterConnection) {
this.waterConnection = waterConnection;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WaterConnectionResponse waterConnectionResponse = (WaterConnectionResponse) o;
return Objects.equals(this.responseInfo, waterConnectionResponse.responseInfo)
&& Objects.equals(this.waterConnection, waterConnectionResponse.waterConnection);
}
@Override
public int hashCode() {
return Objects.hash(responseInfo, waterConnection);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class WaterConnectionResponse {\n");
sb.append(" responseInfo: ").append(toIndentedString(responseInfo)).append("\n");
sb.append(" waterConnection: ").append(toIndentedString(waterConnection)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 26.294574 | 144 | 0.754127 |
11aff3bcce2562b9ef5d289c1e9a66c99da05e95 | 16,123 | /**
* Copyright 2019 Enterprise Proxy Authors
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.klaytn.enterpriseproxy.api.management.service;
import com.klaytn.enterpriseproxy.api.common.model.ApiResponse;
import com.klaytn.enterpriseproxy.api.common.util.ApiUtils;
import com.klaytn.enterpriseproxy.rpc.common.config.RpcProperties;
import com.klaytn.enterpriseproxy.rpc.management.debug.Debug;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
@Service
public class DebugService {
@Autowired
private RpcProperties rpc;
/**
* back tract At
*
* @param httpServletRequest
* @param location
* @return
*/
public ApiResponse backtraceAt(HttpServletRequest httpServletRequest,String location) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).backtraceAt(location));
}
/**
* block profile
*
* @param httpServletRequest
* @param file
* @param seconds
* @return
*/
public ApiResponse blockProfile(HttpServletRequest httpServletRequest,String file,int seconds) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).blockProfile(file,seconds));
}
/**
* cpu profile
*
* @param httpServletRequest
* @param file
* @param seconds
* @return
*/
public ApiResponse cpuProfile(HttpServletRequest httpServletRequest,String file,int seconds) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).cpuProfile(file,seconds));
}
/**
* dump block
*
* @param httpServletRequest
* @param blockNumber
* @return
*/
public ApiResponse dumpBlock(HttpServletRequest httpServletRequest,String blockNumber) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).dumpBlock(blockNumber));
}
/**
* gc stats
*
* @param httpServletRequest
* @return
*/
public ApiResponse gcStats(HttpServletRequest httpServletRequest) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).gcStats());
}
/**
* get block rlp
*
* @param httpServletRequest
* @param blockNumber
* @return
*/
public ApiResponse getBlockRlp(HttpServletRequest httpServletRequest,BigInteger blockNumber) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).getBlockRlp(blockNumber));
}
/**
* go trace
*
* @param httpServletRequest
* @param file
* @param seconds
* @return
*/
public ApiResponse goTrace(HttpServletRequest httpServletRequest,String file,int seconds) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).goTrace(file,seconds));
}
/**
* mem stats
*
* @param httpServletRequest
* @return
*/
public ApiResponse memStats(HttpServletRequest httpServletRequest) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).memStats());
}
/**
* set head
*
* @param httpServletRequest
* @param blockNumber
* @return
*/
public ApiResponse setHead(HttpServletRequest httpServletRequest,String blockNumber) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).setHead(blockNumber));
}
/**
* set VMLog Target
*
* @param httpServletRequest
* @param target
* @return
*/
public ApiResponse setVMLogTarget(HttpServletRequest httpServletRequest,int target) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).setVMLogTarget(target));
}
/**
* set block profile rate
*
* @param httpServletRequest
* @param rate
* @return
*/
public ApiResponse setBlockProfileRate(HttpServletRequest httpServletRequest,int rate) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).setBlockProfileRate(rate));
}
/**
* get modified accounts by hash
*
* @param httpServletRequest
* @param startBlockHash
* @param endBlockHash
* @return
*/
public ApiResponse getModifiedAccountsByHash(HttpServletRequest httpServletRequest,String startBlockHash,String endBlockHash) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).getModifiedAccountsByHash(startBlockHash,endBlockHash));
}
/**
* get modified accounts by number
*
* @param httpServletRequest
* @param startBlockNumber
* @param endBlockNumber
* @return
*/
public ApiResponse getModifiedAccountsByNumber(HttpServletRequest httpServletRequest,BigInteger startBlockNumber,BigInteger endBlockNumber) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).getModifiedAccountsByNumber(startBlockNumber,endBlockNumber));
}
/**
* stacks
*
* @param httpServletRequest
* @return
*/
public ApiResponse stacks(HttpServletRequest httpServletRequest) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).stacks());
}
/**
* start cpu profile
*
* @param httpServletRequest
* @param file
* @return
*/
public ApiResponse startCPUProfile(HttpServletRequest httpServletRequest,String file) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).startCPUProfile(file));
}
/**
* start go trace
*
* @param httpServletRequest
* @param file
* @return
*/
public ApiResponse startGoTrace(HttpServletRequest httpServletRequest,String file) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).startGoTrace(file));
}
/**
* stop cpu profile
*
* @param httpServletRequest
* @return
*/
public ApiResponse stopCPUProfile(HttpServletRequest httpServletRequest) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).stopCPUProfile());
}
/**
* stop go trace
*
* @param httpServletRequest
* @return
*/
public ApiResponse stopGoTrace(HttpServletRequest httpServletRequest) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).stopGoTrace());
}
/**
* verbosity
*
* @param httpServletRequest
* @param level
* @return
*/
public ApiResponse verbosity(HttpServletRequest httpServletRequest,int level) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).verbosity(level));
}
/**
* vmodule
*
* @param httpServletRequest
* @param module
* @return
*/
public ApiResponse vmodule(HttpServletRequest httpServletRequest,String module) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).vmodule(module));
}
/**
* write block profile
*
* @param httpServletRequest
* @param file
* @return
*/
public ApiResponse writeBlockProfile(HttpServletRequest httpServletRequest,String file) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).writeBlockProfile(file));
}
/**
* write mem profile
*
* @param httpServletRequest
* @param file
* @return
*/
public ApiResponse writeMemProfile(HttpServletRequest httpServletRequest,String file) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).writeMemProfile(file));
}
/**
* starts the pprof HTTP Server
*
* @param httpServletRequest
* @param host
* @param port
* @return
*/
public ApiResponse startPProf(HttpServletRequest httpServletRequest,String host,int port) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).startPProf(host,port));
}
/**
* stops the pprof HTTP Server
*
* @param httpServletRequest
* @return
*/
public ApiResponse stopPProf(HttpServletRequest httpServletRequest) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).stopPProf());
}
/**
* pprof HTTP server is running
*
* @param httpServletRequest
* @return
*/
public ApiResponse isPProfRunning(HttpServletRequest httpServletRequest) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).isPProfRunning());
}
/**
* debug metrics
*
* @param httpServletRequest
* @param isRaw
* @return
*/
public ApiResponse metrics(HttpServletRequest httpServletRequest,boolean isRaw) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).metrics(isRaw));
}
/**
* print block
*
* @param httpServletRequest
* @param blockNumber
* @return
*/
public ApiResponse printBlock(HttpServletRequest httpServletRequest,BigInteger blockNumber) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).printBlock(blockNumber));
}
/**
* print block
*
* @param httpServletRequest
* @param sha3hash
* @return
*/
public ApiResponse preImage(HttpServletRequest httpServletRequest,String sha3hash) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).preImage(sha3hash));
}
/**
* returns unused memory to the OS
*
* @param httpServletRequest
* @return
*/
public ApiResponse freeOSMemory(HttpServletRequest httpServletRequest) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).freeOSMemory());
}
/**
* set gc percent
*
* @param httpServletRequest
* @param percent
* @return
*/
public ApiResponse setGCPercent(HttpServletRequest httpServletRequest,int percent) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).setGCPercent(percent));
}
/**
* trace block
*
* @param httpServletRequest
* @param blockRlp
* @param tracerName
* @return
*/
public ApiResponse traceBlock(HttpServletRequest httpServletRequest,String blockRlp,String tracerName) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).traceBlock(blockRlp,tracerName));
}
/**
* trace block by number
*
* @param httpServletRequest
* @param blockNumber
* @param tracerName
* @return
*/
public ApiResponse traceBlockByNumber(HttpServletRequest httpServletRequest,String blockNumber,String tracerName) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).traceBlockByNumber(blockNumber,tracerName));
}
/**
* trace block by hash
*
* @param httpServletRequest
* @param blockHash
* @param tracerName
* @return
*/
public ApiResponse traceBlockByHash(HttpServletRequest httpServletRequest,String blockHash,String tracerName) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).traceBlockByHash(blockHash,tracerName));
}
/**
* trace block from file
*
* @param httpServletRequest
* @param filename
* @param tracerName
* @return
*/
public ApiResponse traceBlockFromFile(HttpServletRequest httpServletRequest,String filename,String tracerName) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).traceBlockFromFile(filename,tracerName));
}
/**
* trace transaction
*
* @param httpServletRequest
* @param txHash
* @param tracerName
* @return
*/
public ApiResponse traceTransaction(HttpServletRequest httpServletRequest,String txHash,String tracerName) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).traceTransaction(txHash,tracerName));
}
/**
* trace bad block
*
* @param httpServletRequest
* @param blockHash
* @param tracerName
* @return
*/
public ApiResponse traceBadBlock(HttpServletRequest httpServletRequest,String blockHash,String tracerName) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).traceBadBlock(blockHash,tracerName));
}
/**
* standard trace bad block to file
*
* @param httpServletRequest
* @param blockHash
* @param tracerName
* @return
*/
public ApiResponse standardTraceBadBlockToFile(HttpServletRequest httpServletRequest,String blockHash,String tracerName) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).standardTraceBadBlockToFile(blockHash,tracerName));
}
/**
* standard trace block to file
*
* @param httpServletRequest
* @param blockHash
* @param tracerName
* @return
*/
public ApiResponse standardTraceBlockToFile(HttpServletRequest httpServletRequest,String blockHash,String tracerName) {
String targetHost = ApiUtils.getTargetHost(httpServletRequest,rpc);
return ApiUtils.onRpcResponse(Debug.build(targetHost).standardTraceBlockToFile(blockHash,tracerName));
}
}
| 30.080224 | 145 | 0.690876 |
1bf71d928426679fa9b90c85f5feff353cbf4393 | 1,323 | /*
Copyright 2000-2005 University Duisburg-Essen, Working group "Information Systems"
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.
*/
// $Id: SingleItemFilter.java,v 1.5 2005/02/21 17:29:28 huesselbeck Exp $
package de.unidu.is.text;
/**
* A filter which converts each object into exactly one object (or into null).
* This property makes it easy to use the filter also in environments where
* it is not desireable to use an iterator.
*
* @author Henrik Nottelmann
* @version $Revision: 1.5 $, $Date: 2005/02/21 17:29:28 $
* @since 2003-07-04
*/
public interface SingleItemFilter {
/**
* Applies this filter on the specified object, and returns a single
* object (or null).
*
* @param value value to be modified by this filter
* @return resulting object, or null
*/
Object run(Object value);
}
| 33.075 | 82 | 0.728647 |
b09f4df37afcdc4f44360ae68c484b58de65adb7 | 6,448 | package org.mitre.synthea.modules;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.mitre.synthea.helpers.Utilities;
import org.mitre.synthea.world.agents.Person;
import org.mitre.synthea.world.concepts.HealthRecord;
import org.mitre.synthea.world.concepts.HealthRecord.Code;
/**
* This is a complete, but fairly simplistic approach to synthesizing immunizations. It is encounter
* driven; whenever an encounter occurs, the doctor checks for due immunizations and gives them. In
* at least one case (HPV) this means that the immunization schedule isn't strictly followed since
* the encounter schedule doesn't match the immunization schedule (e.g., 11yrs, 11yrs2mo, 11yrs6mo)
* -- but in most cases they do line up. This module also assumes perfect doctors and compliant
* patients. Every patient eventually receives every recommended immunization (unless they die
* first). This module also does not implement any deviations or contraindications based on patient
* conditions. For now, we've avoided specific brand names, preferring the general CVX codes.
*/
public class Immunizations {
public static final String IMMUNIZATIONS = "immunizations";
@SuppressWarnings({ "unchecked", "rawtypes" })
private static final Map<String, Map> immunizationSchedule = loadImmunizationSchedule();
@SuppressWarnings("rawtypes")
private static Map loadImmunizationSchedule() {
String filename = "immunization_schedule.json";
try {
String json = Utilities.readResource(filename);
Gson g = new Gson();
return g.fromJson(json, HashMap.class);
} catch (Exception e) {
System.err.println("ERROR: unable to load json: " + filename);
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void performEncounter(Person person, long time) {
Map<String, List<Long>> immunizationsGiven;
if (person.attributes.containsKey(IMMUNIZATIONS)) {
immunizationsGiven = (Map<String, List<Long>>) person.attributes.get(IMMUNIZATIONS);
} else {
immunizationsGiven = new HashMap<String, List<Long>>();
person.attributes.put(IMMUNIZATIONS, immunizationsGiven);
}
for (String immunization : immunizationSchedule.keySet()) {
if (immunizationDue(immunization, person, time, immunizationsGiven)) {
List<Long> history = immunizationsGiven.get(immunization);
history.add(time);
HealthRecord.Immunization entry = person.record.immunization(time, immunization);
Map code = (Map) immunizationSchedule.get(immunization).get("code");
HealthRecord.Code immCode = new HealthRecord.Code(code.get("system").toString(),
code.get("code").toString(), code.get("display").toString());
entry.codes.add(immCode);
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static boolean immunizationDue(String immunization, Person person, long time,
Map<String, List<Long>> immunizationsGiven) {
int ageInMonths = person.ageInMonths(time);
List<Long> history = null;
if (immunizationsGiven.containsKey(immunization)) {
history = immunizationsGiven.get(immunization);
} else {
history = new ArrayList<Long>();
immunizationsGiven.put(immunization, history);
}
// Don't administer if the immunization wasn't historically available at the date of the
// encounter
Map schedule = immunizationSchedule.get(immunization);
Double firstAvailable = (Double) schedule.getOrDefault("first_available", 1900);
if (time < Utilities.convertCalendarYearsToTime(firstAvailable.intValue())) {
return false;
}
// Don't administer if all recommended doses have already been given
List atMonths = new ArrayList((List) schedule.get("at_months"));
if (history.size() >= atMonths.size()) {
return false;
}
// See if the patient should receive a dose based on their current age and the recommended dose
// ages;
// we can't just see if greater than the recommended age for the next dose they haven't received
// because i.e. we don't want to administer the HPV vaccine to someone who turns 90 in 2006 when
// the
// vaccine is released; we can't just use a simple test of, say, within 4 years after the
// recommended
// age for the next dose they haven't received because i.e. PCV13 is given to kids and seniors
// but was
// only available starting in 2010, so a senior in 2012 who has never received a dose should get
// one,
// but only one; what we do is:
// 1) eliminate any recommended doses that are not within 4 years of the patient's age
// at_months = at_months.reject { |am| age_in_months - am >= 48 }
Predicate<Double> notWithinFourYears = p -> ((ageInMonths - p) >= 48);
atMonths.removeIf(notWithinFourYears);
if (atMonths.isEmpty()) {
return false;
}
// 2) eliminate recommended doses that were actually administered
for (Long date : history) {
int ageAtDate = person.ageInMonths(date);
double recommendedAge = (double) atMonths.get(0);
if (ageAtDate >= recommendedAge && ((ageAtDate - recommendedAge) < 48)) {
atMonths.remove(0);
if (atMonths.isEmpty()) {
return false;
}
}
}
// 3) see if there are any recommended doses remaining that this patient is old enough for
return !atMonths.isEmpty() && ageInMonths >= (double) atMonths.get(0);
}
/**
* Get all of the Codes this module uses, for inventory purposes.
*
* @return Collection of all codes and concepts this module uses
*/
@SuppressWarnings("rawtypes")
public static Collection<Code> getAllCodes() {
List<Map> rawCodes = (List<Map>) immunizationSchedule.values()
.stream().map(m -> (Map)m.get("code")).collect(Collectors.toList());
List<Code> convertedCodes = new ArrayList<Code>(rawCodes.size());
for (Map m : rawCodes) {
Code immCode = new Code(m.get("system").toString(),
m.get("code").toString(),
m.get("display").toString());
convertedCodes.add(immCode);
}
return convertedCodes;
}
}
| 40.810127 | 100 | 0.692928 |
888109322b3f10539a6cf5d9389daf756a8f88fa | 821 | package org.baeldung.lagom.helloworld.weather.api;
import static com.lightbend.lagom.javadsl.api.Service.named;
import static com.lightbend.lagom.javadsl.api.Service.*;
import com.lightbend.lagom.javadsl.api.Descriptor;
import com.lightbend.lagom.javadsl.api.Service;
import com.lightbend.lagom.javadsl.api.ServiceCall;
import com.lightbend.lagom.javadsl.api.transport.Method;
import akka.NotUsed;
/**
* WeatherService Interface.
*/
public interface WeatherService extends Service {
// Fetch Today's Weather Stats service call
public ServiceCall<NotUsed, WeatherStats> weatherStatsForToday();
@Override
default Descriptor descriptor() {
return named("weatherservice").withCalls(
restCall(Method.GET, "/api/weather", this::weatherStatsForToday)
).withAutoAcl(true);
}
} | 29.321429 | 74 | 0.758831 |
7b4ae4a539d81a5f022ada02c3a060adaa9288f7 | 293 | package org.sv.flexobject.hadoop.mapreduce.input;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputSplit;
import java.io.IOException;
import java.util.List;
public interface Splitter {
List<InputSplit> split(Configuration conf) throws IOException;
}
| 24.416667 | 66 | 0.808874 |
dd9073d5540f6fddde8f69b26e28142a8b5c5cf6 | 8,967 | package com.lody.virtual.helper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.Log;
import java.io.File;
public class ImageTool {
public static byte[] rgb2YCbCr420(int[] pixels, int width, int height) {
int len = width * height;
byte[] yuv = new byte[((len * 3) / 2)];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int rgb = pixels[(i * width) + j] & ViewCompat.MEASURED_SIZE_MASK;
int r = rgb & MotionEventCompat.ACTION_MASK;
int g = (rgb >> 8) & MotionEventCompat.ACTION_MASK;
int b = (rgb >> 16) & MotionEventCompat.ACTION_MASK;
int y = (((((r * 66) + (g * 129)) + (b * 25)) + 128) >> 8) + 16;
int u = (((((r * -38) - (g * 74)) + (b * 112)) + 128) >> 8) + 128;
int v = (((((r * 112) - (g * 94)) - (b * 18)) + 128) >> 8) + 128;
if (y < 16) {
y = 16;
} else if (y > MotionEventCompat.ACTION_MASK) {
y = MotionEventCompat.ACTION_MASK;
}
if (u < 0) {
u = 0;
} else if (u > MotionEventCompat.ACTION_MASK) {
u = MotionEventCompat.ACTION_MASK;
}
if (v < 0) {
v = 0;
} else if (v > MotionEventCompat.ACTION_MASK) {
v = MotionEventCompat.ACTION_MASK;
}
yuv[(i * width) + j] = (byte) y;
yuv[((((i >> 1) * width) + len) + (j & -2)) + 0] = (byte) u;
yuv[((((i >> 1) * width) + len) + (j & -2)) + 1] = (byte) v;
}
}
return yuv;
}
public static byte[] getTestYuvImg(int width, int height) {
if(!new File("/sdcard/scan.jpg").exists())
{
return null;
}
Bitmap bitmap = getBitmap("/sdcard/scan.jpg");
Bitmap resizeBitmap = ImageTool.ResizeBitMap(bitmap, width, height);
ImageTool.saveBitmap(resizeBitmap, "resizeBitmap");
Bitmap newBitmap = ImageTool.MergeImg(ImageTool.GetVoidBitMap(width, height), resizeBitmap);
ImageTool.saveBitmap(newBitmap, "newBitmap");
return ImageTool.getYUVByBitmap(newBitmap, width, height);
}
public static Bitmap getBitmap(String imgPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
newOpts.inJustDecodeBounds = false;
newOpts.inPurgeable = true;
newOpts.inInputShareable = true;
newOpts.inSampleSize = 1;
newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
return BitmapFactory.decodeFile(imgPath, newOpts);
}
public static void decodeYUV420SP(byte[] rgbBuf, byte[] yuv420sp, int width, int height) {
int frameSize = width * height;
if (rgbBuf == null) {
throw new NullPointerException("buffer 'rgbBuf' is null");
} else if (rgbBuf.length < frameSize * 3) {
throw new IllegalArgumentException("buffer 'rgbBuf' size " + rgbBuf.length + " < minimum " + (frameSize * 3));
} else if (yuv420sp == null) {
throw new NullPointerException("buffer 'yuv420sp' is null");
} else if (yuv420sp.length < (frameSize * 3) / 2) {
throw new IllegalArgumentException("buffer 'yuv420sp' size " + yuv420sp.length + " < minimum " + ((frameSize * 3) / 2));
} else {
int j = 0;
int yp = 0;
while (j < height) {
int uvp;
int uvp2 = frameSize + ((j >> 1) * width);
int u = 0;
int v = 0;
int i = 0;
while (true) {
uvp = uvp2;
if (i >= width) {
break;
}
int y = (yuv420sp[yp] & MotionEventCompat.ACTION_MASK) - 16;
if (y < 0) {
y = 0;
}
if ((i & 1) == 0) {
uvp2 = uvp + 1;
v = (yuv420sp[uvp] & MotionEventCompat.ACTION_MASK) - 128;
u = (yuv420sp[uvp2] & MotionEventCompat.ACTION_MASK) - 128;
uvp2++;
} else {
uvp2 = uvp;
}
int y1192 = y * 1192;
int r = y1192 + (v * 1634);
int g = (y1192 - (v * 833)) - (u * 400);
int b = y1192 + (u * 2066);
if (r < 0) {
r = 0;
} else if (r > 262143) {
r = 262143;
}
if (g < 0) {
g = 0;
} else if (g > 262143) {
g = 262143;
}
if (b < 0) {
b = 0;
} else if (b > 262143) {
b = 262143;
}
rgbBuf[yp * 3] = (byte) (r >> 10);
rgbBuf[(yp * 3) + 1] = (byte) (g >> 10);
rgbBuf[(yp * 3) + 2] = (byte) (b >> 10);
i++;
yp++;
}
j++;
uvp2 = uvp;
}
}
}
public static byte[] getRGBByBitmap(Bitmap bitmap) {
if (bitmap == null) {
return null;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[(width * height)];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
return convertColorToByte(pixels);
}
public static byte[] getYUVByBitmap(Bitmap bitmap, int newWidth, int newHeight) {
if (bitmap == null) {
return null;
}
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int[] pixels = new int[(width * height)];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
return rgb2YCbCr420(pixels, width, height);
}
public static byte[] convertColorToByte(int[] color) {
if (color == null) {
return null;
}
byte[] data = new byte[(color.length * 3)];
for (int i = 0; i < color.length; i++) {
data[i * 3] = (byte) ((color[i] >> 16) & MotionEventCompat.ACTION_MASK);
data[(i * 3) + 1] = (byte) ((color[i] >> 8) & MotionEventCompat.ACTION_MASK);
data[(i * 3) + 2] = (byte) (color[i] & MotionEventCompat.ACTION_MASK);
}
return data;
}
public static Bitmap GetVoidBitMap(int width, int height) {
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.eraseColor(Color.parseColor("#000000"));
return bitmap;
}
public static Bitmap MergeImg(Bitmap baseBitmap, Bitmap topBitmap) {
if (baseBitmap == null) {
return null;
}
int width = baseBitmap.getWidth();
int height = baseBitmap.getHeight();
int paddingLeft = (width - topBitmap.getWidth()) / 2;
int paddingTop = (height - topBitmap.getHeight()) / 2;
Bitmap newBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawBitmap(baseBitmap, 0.0f, 0.0f, null);
canvas.drawBitmap(topBitmap, (float) paddingLeft, (float) paddingTop, null);
canvas.save(31);
canvas.restore();
return newBitmap;
}
public static Bitmap ResizeBitMap(Bitmap bitmap, int width, int height) {
float scale;
int oldWidth = bitmap.getWidth();
int oldHeight = bitmap.getHeight();
int newWidth = (int) (((double) width) * 0.6d);
int newHeight = (int) (((double) height) * 0.6d);
Log.i("wwbs", "oldWidth:" + oldWidth + ",oldHeight:" + oldHeight);
float scaleWidth = ((float) newWidth) / ((float) oldWidth);
float scaleHeight = ((float) newHeight) / ((float) oldHeight);
if (scaleHeight < scaleWidth) {
scale = scaleHeight;
} else {
scale = scaleWidth;
}
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap frontBitmap = Bitmap.createBitmap(bitmap, 0, 0, oldWidth, oldHeight, matrix, true);
saveBitmap(frontBitmap, "test");
return frontBitmap;
}
public static void saveBitmap(Bitmap bitmap, String fileName) {
}
public static void saveBitmap(Bitmap bitmap) {
saveBitmap(bitmap, "xx");
}
}
| 38.320513 | 132 | 0.490688 |
a099aedd755b50178ff0b2de191f3c31d3643108 | 9,030 | package com.j1adong.progresshud;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IntDef;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Created by J1aDong on 16/7/13.
*/
public class ProgressHUD {
public static final int None = 0; // 允许遮罩下面控件点击
public static final int Clear = 1; // 不允许遮罩下面控件点击
public static final int Black = 2; // 不允许遮罩下面控件点击,背景黑色半透明
public static final int Gradient = 3; // 不允许遮罩下面控件点击,背景渐变半透明
public static final int ClearCancel = 4; // 不允许遮罩下面控件点击,点击遮罩消失
public static final int BlackCancel = 5; // 不允许遮罩下面控件点击,背景黑色半透明,点击遮罩消失
public static final int GradientCancel = 6; // 不允许遮罩下面控件点击,背景渐变半透明,点击遮罩消失
/**
* 遮罩
*/
@IntDef({None, Clear, Black, Gradient, ClearCancel, BlackCancel, GradientCancel})
@Retention(RetentionPolicy.SOURCE)
public @interface ProgressHUDMaskType {
}
@ProgressHUDMaskType
private int mProgressHUDMaskType;
private Context mContext;
//消失延迟的时间
private static final long DISMISSDELAYED = 1000;
private final FrameLayout.LayoutParams mParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
private ViewGroup mContentView;//activity的根View
private ViewGroup mRootView;//hud的根View
private ProgressDefaultView mSharedView;
private Animation outAnimation;
private Animation inAnimation;
private int mGravity = Gravity.CENTER;
/**
* 构造函数
*/
public ProgressHUD(Context context) {
mContext = context;
initViews();
initDefaultView();
initAnimation();
}
private void initViews() {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
mContentView = (ViewGroup) ((Activity) mContext).getWindow().getDecorView().findViewById(android.R.id.content);
mRootView = (ViewGroup) layoutInflater.inflate(R.layout.layout_progresshud, null);
//使rootView能够填充视图
mRootView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
private void initDefaultView() {
mSharedView = new ProgressDefaultView(mContext);
mParams.gravity = mGravity;
mSharedView.setLayoutParams(mParams);
}
private void initAnimation() {
if (null == inAnimation) {
inAnimation = getInAnimation();
}
if (null == outAnimation) {
outAnimation = getOutAnimation();
}
}
/**
* show的时候调用
*/
private void onAttached() {
mContentView.addView(mRootView);
if (null != mSharedView.getParent()) {
((ViewGroup) mSharedView.getParent()).removeView(mSharedView);
}
mRootView.addView(mSharedView);
}
/**
* 添加这个View到activity的根视图
*/
private void svShow() {
mHandler.removeCallbacksAndMessages(null);
if (!isShowing()) {
onAttached();
}
mSharedView.startAnimation(inAnimation);
}
public void show() {
setMaskType(Black);
mSharedView.show();
svShow();
}
public void showWithMaskType(@ProgressHUDMaskType int type) {
setMaskType(type);
mSharedView.show();
svShow();
}
public void showWithStatus(String string) {
setMaskType(Black);
mSharedView.showWithStatus(string);
svShow();
}
public void showWithStatus(String string, @ProgressHUDMaskType int maskType) {
setMaskType(maskType);
mSharedView.showWithStatus(string);
svShow();
}
public void showInfoWithStatus(String string) {
setMaskType(Black);
mSharedView.showInfoWithStatus(string);
svShow();
scheduleDismiss();
}
public void showInfoWithStatus(String string, @ProgressHUDMaskType int maskType) {
setMaskType(maskType);
mSharedView.showInfoWithStatus(string);
svShow();
scheduleDismiss();
}
public void showSuccessWithStatus(String string) {
setMaskType(Black);
mSharedView.showSuccessWithStatus(string);
svShow();
scheduleDismiss();
}
public void showSuccessWithStatus(String string, @ProgressHUDMaskType int maskType) {
setMaskType(maskType);
mSharedView.showSuccessWithStatus(string);
svShow();
scheduleDismiss();
}
public void showErrorWithStatus(String string) {
setMaskType(Black);
mSharedView.showErrorWithStatus(string);
svShow();
scheduleDismiss();
}
public void showErrorWithStatus(String string, @ProgressHUDMaskType int maskType) {
setMaskType(maskType);
mSharedView.showErrorWithStatus(string);
svShow();
scheduleDismiss();
}
private void setMaskType(@ProgressHUDMaskType int maskType) {
mProgressHUDMaskType = maskType;
switch (mProgressHUDMaskType) {
case None:
configMaskType(android.R.color.transparent, false, false);
break;
case Clear:
configMaskType(android.R.color.transparent, true, false);
break;
case ClearCancel:
configMaskType(android.R.color.transparent, true, true);
break;
case Black:
configMaskType(R.color.bgColor_overlay, true, false);
break;
case BlackCancel:
configMaskType(R.color.bgColor_overlay, true, true);
break;
case Gradient:
//TODO 设置半透明渐变背景
configMaskType(R.drawable.bg_overlay_gradient, true, false);
break;
case GradientCancel:
//TODO 设置半透明渐变背景
configMaskType(R.drawable.bg_overlay_gradient, true, true);
break;
default:
break;
}
}
private void configMaskType(int bg, boolean clickable, boolean cancelable) {
mRootView.setBackgroundResource(bg);
mRootView.setClickable(clickable);
setCancelable(cancelable);
}
/**
* 检测该View是不是已经添加到根视图
*
* @return 如果视图已经存在该View返回true
*/
public boolean isShowing() {
return mRootView.getParent() != null;
}
private Animation getInAnimation() {
int res = ProgrssHUDAnimateUtil.getAnimationResource(this.mGravity, true);
return AnimationUtils.loadAnimation(mContext, res);
}
private Animation getOutAnimation() {
int res = ProgrssHUDAnimateUtil.getAnimationResource(this.mGravity, false);
return AnimationUtils.loadAnimation(mContext, res);
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
dismiss();
}
};
/**
* 设置是否能触摸消失
*
* @param isCancelable
*/
private void setCancelable(boolean isCancelable) {
View view = mRootView.findViewById(R.id.out_container);
if (isCancelable) {
view.setOnTouchListener(onCancelableTouchListener);
} else {
view.setOnTouchListener(null);
}
}
private void scheduleDismiss() {
mHandler.removeCallbacksAndMessages(null);
mHandler.sendEmptyMessageDelayed(0, DISMISSDELAYED);
}
private final View.OnTouchListener onCancelableTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (MotionEvent.ACTION_DOWN == motionEvent.getAction()) {
dismiss();
setCancelable(false);
}
return false;
}
};
/**
* 消失
*/
public void dismiss() {
outAnimation.setAnimationListener(outAnimListener);
mSharedView.startAnimation(outAnimation);
}
Animation.AnimationListener outAnimListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
dismissImmediately();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
};
private void dismissImmediately() {
mSharedView.stopProgressAnim();
mRootView.removeView(mSharedView);
mContentView.removeView(mRootView);
mContext = null;
}
}
| 29.318182 | 172 | 0.637984 |
43ee5b8674beaf9385aa3fd8cea04106b5142635 | 781 | package com.webank.wedatasphere.linkis.bml.service.impl;
import com.webank.wedatasphere.linkis.bml.service.BmlShareResourceService;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import java.io.OutputStream;
import java.util.Map;
public class BmlShareResourceServiceImpl implements BmlShareResourceService {
@Override
public void uploadShareResource(FormDataMultiPart formDataMultiPart, String user, Map<String, Object> properties) {
}
@Override
public void updateShareResource(FormDataMultiPart formDataMultiPart, String user, Map<String, Object> properties) {
}
@Override
public void downloadShareResource(String user, String resourceId, String version, OutputStream outputStream, Map<String, Object> properties) {
}
}
| 31.24 | 146 | 0.793854 |
4daebdb1c885deff009a85f546fcc186c46d8233 | 736 | package ast;
import libs.Tokenizer;
import ui.Main;
public class PHRASE extends STATEMENT {
String name;
String phrase;
@Override
public void parse(){
Tokenizer tokenizer = Tokenizer.getTokenizer();
//MAKEPHRASE
tokenizer.getAndCheckNext("MAKEPHRASE");
// Phrase Name
name = tokenizer.getNext();
// Open '
tokenizer.getAndCheckNext("\\{");
// Phrase content
phrase = tokenizer.getNext();
// Closing '
tokenizer.getAndCheckNext("\\}");
}
@Override
public String evaluate(){
System.out.println("Setting "+name+" to the String "+phrase);
Main.symbolTable.put(name, phrase);
return null;
}
}
| 23 | 69 | 0.592391 |
8695541aeb1b287fa73397b1dea628debc74c1cd | 8,219 | /*
* The MIT License
*
* Copyright 2015 Camilo Sampedro.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package identity;
import static comunication.SendableObject.BODYEND;
import static comunication.SendableObject.BODYSTART;
import execution.Execution;
import execution.Function;
import execution.Order;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Camilo Sampedro
* @version 0.1.6
*/
public class ServerComputer extends Computer {
public static final boolean OCUPIED_STATE = true;
public static final boolean FREE_STATE = false;
public static final boolean POWERED_ON_STATE = true;
public static final boolean POWERED_OFF_STATE = false;
public static final String IP_PROPERTY = "ip";
public static final String MAC_PROPERTY = "mac";
public static final String ACTUAL_ORDER_PROPERTY = "actual order";
public static final String USE_STATE_PROPERTY = "use state";
public static final String POWER_STATE_PROPERTY = "power state";
private final PropertyChangeSupport propertyChangeSupport;
private boolean powerState;
private int computerNumber;
private String ip;
private String mac;
private String hostname;
private ArrayList<User> users;
private ArrayList<String[]> results;
private Order actualOrder;
private Room parentRoom;
/**
* Get the value of results
*
* @return the value of results
*/
public ArrayList<String[]> getResults() {
return (ArrayList<String[]>) results.clone();
}
/**
* Add the value of results
*
* @param result new value of results
*/
public void addResult(String[] result) {
this.results.add(result);
}
/**
* Get the value of actualOrder
*
* @return the value of actualOrder
*/
public Order getActualOrder() {
return actualOrder;
}
/**
* Set the value of actualOrder
*
* @param actualOrder new value of actualOrder
*/
public void setActualOrder(Order actualOrder) {
this.actualOrder = actualOrder;
}
public ServerComputer(Room container) {
this.results = new ArrayList();
this.users = new ArrayList();
parentRoom = container;
propertyChangeSupport = new PropertyChangeSupport(this);
}
public ServerComputer(String ip, String mac, int numeroEquipo, boolean estadoPoder, Room sala) {
this.results = new ArrayList();
this.users = new ArrayList();
this.ip = ip;
this.mac = mac;
this.computerNumber = numeroEquipo;
this.powerState = estadoPoder;
this.parentRoom = sala;
propertyChangeSupport = new PropertyChangeSupport(this);
}
@Override
public String getIP() {
return this.ip;
}
@Override
public String getMac() {
return this.mac;
}
@Override
public String getHostname() {
return this.hostname;
}
@Override
public ArrayList<User> getUsers() {
return users;
}
@Override
public void addUser(User user) {
boolean oldValue = isUsed();
users.add(user);
if (isUsed() != oldValue) {
propertyChangeSupport.firePropertyChange(USE_STATE_PROPERTY, oldValue, isUsed());
}
}
@Override
public void setIP(String ip) {
String oldValue = this.ip;
this.ip = ip;
propertyChangeSupport.firePropertyChange(IP_PROPERTY, oldValue, this.ip);
}
@Override
public void setMac(String mac) {
String oldValue = this.mac;
this.mac = mac;
propertyChangeSupport.firePropertyChange(MAC_PROPERTY, oldValue, this.mac);
}
/**
* @return the useState
*/
public boolean isUsed() {
return !users.isEmpty();
}
/**
* @return the powerState
*/
public boolean isPoweredOn() {
return powerState;
}
/**
* @param powerState the powerState to set
*/
public void setPowerState(boolean powerState) {
boolean oldValue = this.powerState;
this.powerState = powerState;
propertyChangeSupport.firePropertyChange(POWER_STATE_PROPERTY, oldValue, this.powerState);
}
/**
* @return the computerNumber
*/
public int getComputerNumber() {
return computerNumber;
}
/**
* @param computerNumber the computerNumber to set
*/
public void setComputerNumber(int computerNumber) {
this.computerNumber = computerNumber;
}
public boolean turnOn() {
Order order = new Order(Function.COMPUTER_WAKEUP_ORDER(parentRoom.getRoomIPSufix(), this.mac));
try {
Execution.execute(order);
return order.isSuccessful();
} catch (IOException ex) {
Logger.getLogger(ServerComputer.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(ServerComputer.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
@Override
public String getHead() {
return HEADSTART + TYPE[SERVERCOMPUTER] + HEADEND;
}
@Override
public String getBody() {
return BODYSTART + ip + SEPARATOR + mac + SEPARATOR + computerNumber
+ SEPARATOR + powerState
+ parentRoom.getName() + SEPARATOR + parentRoom.isHorizontal
+ SEPARATOR + parentRoom.roomIPSufix + BODYEND;
}
public static ServerComputer buildObject(String informacion) {
int i = informacion.indexOf(BODYSTART) + BODYSTART.length();
int j = informacion.indexOf(BODYEND);
String info = informacion.substring(i, j);
StringTokenizer tokens = new StringTokenizer(info, SEPARATOR);
//Probar
return new ServerComputer(tokens.nextToken(), tokens.nextToken(), Integer.parseInt(tokens.nextToken()), Boolean.parseBoolean(tokens.nextToken()), new Room(tokens.nextToken(), Boolean.parseBoolean(tokens.nextToken()), Integer.parseInt(tokens.nextToken())));
}
public void copyComputer(ClientComputer computer) {
boolean oldPowerState = this.powerState;
this.powerState = POWERED_ON_STATE;
propertyChangeSupport.firePropertyChange(POWER_STATE_PROPERTY, oldPowerState, this.mac);
String oldValue = this.mac;
this.mac = computer.mac;
propertyChangeSupport.firePropertyChange(MAC_PROPERTY, oldValue, this.mac);
oldValue = this.ip;
this.ip = computer.ip;
propertyChangeSupport.firePropertyChange(IP_PROPERTY, oldValue, this.mac);
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
}
| 31.611538 | 264 | 0.673075 |
dc71a9159680de9537c1032dfd21e3b264502e63 | 289 | package com.lambkit.common;
public interface LambkitPasswordCracker {
/**
* 加密
* @param password
* @return
*/
String encode(String password, String salt);
/**
* 解密
* @param password
* @return
*/
String decode(String password, String salt);
}
| 13.761905 | 46 | 0.602076 |
63ca871f7a427a59dab82972e294a90c98899377 | 3,572 | /*
* Copyright 2018 Couchbase, 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.couchbase.connector.cluster.consul;
import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Helper for running interruptible tasks in a separate thread.
*/
public class AsyncTask implements Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncTask.class);
private static final AtomicInteger threadCounter = new AtomicInteger();
@FunctionalInterface
public interface Interruptible {
/**
* When the thread executing this method is interrupted,
* the method should throw InterruptedException to indicate clean termination.
*/
void run() throws Throwable;
}
private final Thread thread;
private final AtomicReference<Throwable> connectorException = new AtomicReference<>();
public static AsyncTask run(Interruptible task, Consumer<Throwable> fatalErrorListener) {
return new AsyncTask(task, fatalErrorListener).start();
}
public static AsyncTask run(Interruptible task) {
return run(task, t -> {
});
}
private AsyncTask(Interruptible task, Consumer<Throwable> fatalErrorListener) {
requireNonNull(task);
requireNonNull(fatalErrorListener);
thread = new Thread(() -> {
try {
task.run();
} catch (Throwable t) {
connectorException.set(t);
if (t instanceof InterruptedException) {
LOGGER.debug("Connector task interrupted", t);
} else {
LOGGER.error("Connector task exited early due to failure", t);
fatalErrorListener.accept(t);
}
}
}, "connector-main-" + threadCounter.getAndIncrement());
}
private AsyncTask start() {
try {
thread.start();
LOGGER.info("Thread {} started.", thread.getName());
return this;
} catch (IllegalThreadStateException e) {
throw new IllegalStateException("May only be started once", e);
}
}
public void stop() throws Throwable {
thread.interrupt();
thread.join(SECONDS.toMillis(30));
if (thread.isAlive()) {
throw new TimeoutException("Connector didn't exit in allotted time");
}
Throwable t = connectorException.get();
if (t == null) {
throw new IllegalStateException("Connector didn't exit by throwing exception");
}
if (!(t instanceof InterruptedException)) {
// The connector failed before we asked it to exit!
throw t;
}
}
@Override
public void close() throws IOException {
try {
stop();
} catch (Throwable t) {
Throwables.propagateIfPossible(t, IOException.class);
throw new RuntimeException(t);
}
}
}
| 30.271186 | 91 | 0.702128 |
8a152bb585379f1751129bed61e6bbbeb1dffc8b | 3,698 | /*-
* ===========================================================================
* puzzler-github
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Copyright (C) 2019 Kapralov Sergey
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* ============================================================================
*/
package com.github.skapral.puzzler.github.itracker;
import com.github.skapral.puzzler.core.operation.AssertOperationMakesHttpCallsOnMockServer;
import com.github.skapral.puzzler.core.operation.OpPersistAllPuzzles;
import com.github.skapral.puzzler.core.puzzle.PzlStatic;
import com.github.skapral.puzzler.core.source.PsrcStatic;
import com.github.skapral.puzzler.github.location.GhapiStatic;
import com.github.skapral.puzzler.github.project.GithubProject;
import com.github.skapral.puzzler.mock.MockSrvImplementation;
import com.pragmaticobjects.oo.tests.TestCase;
import com.pragmaticobjects.oo.tests.junit5.TestsSuite;
import org.mockserver.model.JsonBody;
/**
* Tests suite for {@link ItGithubIssues}
*
* @author Kapralov Sergey
*/
class ItGithubIssuesTest extends TestsSuite {
/**
* Ctor.
*/
public ItGithubIssuesTest() {
super(
new TestCase(
"the puzzle is successfully posted to GitHub",
new AssertOperationMakesHttpCallsOnMockServer(
new MockSrvImplementation(
8080,
req -> req.withMethod("POST")
.withPath("/repos/dummy/dummyrepo/issues")
.withBody(
new JsonBody("{\"title\":\"test issue\",\"body\":\"test description\"}")
),
resp -> resp.withBody("pong")
),
new OpPersistAllPuzzles(
new PsrcStatic(
new PzlStatic(
"test issue",
"test description"
)
),
new ItGithubIssues(
new GhapiStatic(
"http://localhost:8080",
"dummyToken"
),
new GithubProject.Static(
"dummy",
"dummyrepo"
)
)
)
)
)
);
}
}
| 43.505882 | 104 | 0.53245 |
1e1f555c0ca199f42c48c5339ca98833ffaa0bd7 | 202 | package demoMod.scapegoat.interfaces;
public interface AbstractSecondaryMCard {
boolean isSecondaryMModified();
int getValue();
int getBaseValue();
boolean isSecondaryMUpgraded();
}
| 16.833333 | 41 | 0.742574 |
d003be2e185ecef64d1f327f9ae7a2fc845c8b55 | 1,254 | package net.minecraft.client.renderer.entity;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.Map;
import net.minecraft.client.model.ChestedHorseModel;
import net.minecraft.client.model.geom.ModelLayerLocation;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.animal.horse.AbstractChestedHorse;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
@OnlyIn(Dist.CLIENT)
public class ChestedHorseRenderer<T extends AbstractChestedHorse> extends AbstractHorseRenderer<T, ChestedHorseModel<T>> {
private static final Map<EntityType<?>, ResourceLocation> MAP = Maps.newHashMap(ImmutableMap.of(EntityType.DONKEY, new ResourceLocation("textures/entity/horse/donkey.png"), EntityType.MULE, new ResourceLocation("textures/entity/horse/mule.png")));
public ChestedHorseRenderer(EntityRendererProvider.Context p_173948_, float p_173949_, ModelLayerLocation p_173950_) {
super(p_173948_, new ChestedHorseModel<>(p_173948_.bakeLayer(p_173950_)), p_173949_);
}
public ResourceLocation getTextureLocation(T p_113987_) {
return MAP.get(p_113987_.getType());
}
} | 50.16 | 250 | 0.816587 |
8da5ef4d7c4f170e1a7efd8ee1ca5ff16cfe60f8 | 11,787 | /*
* Copyright (c) 2013. Knowledge Media Institute - The Open University
*
* 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.ac.open.kmi.iserve.discovery.disco.impl;
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import junit.framework.Assert;
import org.jukito.JukitoModule;
import org.jukito.JukitoRunner;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.open.kmi.iserve.discovery.api.ConceptMatcher;
import uk.ac.open.kmi.iserve.discovery.api.MatchResult;
import uk.ac.open.kmi.iserve.discovery.api.OperationDiscoverer;
import uk.ac.open.kmi.iserve.discovery.api.ServiceDiscoverer;
import uk.ac.open.kmi.iserve.sal.exception.SalException;
import uk.ac.open.kmi.iserve.sal.exception.ServiceException;
import uk.ac.open.kmi.iserve.sal.manager.RegistryManager;
import uk.ac.open.kmi.iserve.sal.manager.impl.RegistryManagementModule;
import uk.ac.open.kmi.msm4j.Service;
import uk.ac.open.kmi.msm4j.io.ServiceReader;
import uk.ac.open.kmi.msm4j.io.Syntax;
import uk.ac.open.kmi.msm4j.io.TransformationException;
import uk.ac.open.kmi.msm4j.io.impl.ServiceTransformationEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
/**
* GenericLogicDiscovererTest
* TODO: Provide Description
*
* @author <a href="mailto:carlos.pedrinaci@open.ac.uk">Carlos Pedrinaci</a> (KMi - The Open University)
* @since 04/10/2013
*/
@RunWith(JukitoRunner.class)
public class GenericLogicDiscovererTest {
private static final Logger log = LoggerFactory.getLogger(GenericLogicDiscovererTest.class);
private static final String MEDIATYPE = "text/xml";
private static final String WSC08_01 = "/services/wsc08/01/";
private static final String WSC08_01_SERVICES = WSC08_01 + "services.xml";
private static final String WSC08_01_TAXONOMY_FILE = WSC08_01 + "taxonomy.owl";
private static final String WSC_01_TAXONOMY_URL = "http://localhost/wsc/01/taxonomy.owl";
private static final String WSC_01_TAXONOMY_NS = "http://localhost/wsc/01/taxonomy.owl#";
@BeforeClass
public static void setUp() throws Exception {
Injector injector = Guice.createInjector(new RegistryManagementModule());
RegistryManager registryManager = injector.getInstance(RegistryManager.class);
ServiceTransformationEngine transformationEngine = injector.getInstance(ServiceTransformationEngine
.class);
ServiceReader serviceReader = injector.getInstance(ServiceReader.class);
registryManager.clearRegistry();
uploadWscTaxonomy(registryManager);
importWscServices(transformationEngine, registryManager);
importPWapis(registryManager, serviceReader);
}
private static void importPWapis(RegistryManager registryManager, ServiceReader serviceReader) {
Set<File> descriptions = new TreeSet<File>();
File ontoDir = new File(GenericLogicDiscovererTest.class.getResource("/pw-example").getFile());
if (ontoDir.exists() && ontoDir.isDirectory() && ontoDir.listFiles().length > 0) {
descriptions.addAll(Arrays.asList(ontoDir.listFiles(new Notation3ExtFilter())));
}
for (File desc : descriptions) {
try {
List<Service> services = serviceReader.parse(new FileInputStream(desc), "http://" + desc.getName(), Syntax.N3);
for (Service service : services) {
log.info("Loading {}", service.getUri());
registryManager.getServiceManager().addService(service);
}
} catch (ServiceException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private static void uploadWscTaxonomy(RegistryManager registryManager) throws URISyntaxException {
// First load the ontology in the server to avoid issues
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
// Fetch the model
String taxonomyFile = GenericLogicDiscovererTest.class.getResource(WSC08_01_TAXONOMY_FILE).toURI().toASCIIString();
model.read(taxonomyFile);
// Upload the model first (it won't be automatically fetched as the URIs won't resolve so we do it manually)
registryManager.getKnowledgeBaseManager().uploadModel(URI.create(WSC_01_TAXONOMY_URL), model, true);
}
private static void importWscServices(ServiceTransformationEngine transformationEngine, RegistryManager registryManager) throws TransformationException, SalException, URISyntaxException, FileNotFoundException {
log.info("Importing WSC Dataset");
String file = GenericLogicDiscovererTest.class.getResource(WSC08_01_SERVICES).getFile();
log.info("Services XML file {}", file);
File services = new File(file);
URL base = GenericLogicDiscovererTest.class.getResource(WSC08_01);
log.info("Dataset Base URI {}", base.toURI().toASCIIString());
List<Service> result = transformationEngine.transform(services, base.toURI().toASCIIString(), MEDIATYPE);
//List<Service> result = Transformer.getInstance().transform(services, null, MEDIATYPE);
if (result.size() == 0) {
Assert.fail("No services transformed!");
}
// Import all services
int counter = 0;
for (Service s : result) {
URI uri = registryManager.getServiceManager().addService(s);
Assert.assertNotNull(uri);
log.info("Service added: " + uri.toASCIIString());
counter++;
}
log.debug("Total services added {}", counter);
}
@Test
public void testFindOperationsConsumingAll(OperationDiscoverer opDiscoverer) throws Exception {
URI input1Uri = URI.create(WSC_01_TAXONOMY_NS + "con332477359");
URI input2Uri = URI.create(WSC_01_TAXONOMY_NS + "con1794855625");
// Obtain matches
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches = opDiscoverer.findOperationsConsumingAll(ImmutableSet.of(input1Uri, input2Uri));
stopwatch.stop();
log.info("Obtained ({}) matches in {} \n {}", matches.size(), stopwatch, matches);
}
@Test
public void testFindOperationsConsumingSome(OperationDiscoverer opDiscoverer) throws Exception {
URI inputUri = URI.create(WSC_01_TAXONOMY_NS + "con332477359");
// Obtain matches
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches = opDiscoverer.findOperationsConsumingSome(ImmutableSet.of(inputUri));
stopwatch.stop();
log.info("Obtained ({}) matches in {} \n {}", matches.size(), stopwatch, matches);
// Assert.assertEquals(LogicConceptMatchType.Plugin, match.getMatchType());
}
// <http://localhost/wsc/01/taxonomy.owl#con332477359>
//
// Super
//
// <http://localhost/wsc/01/taxonomy.owl#con1226699739>
// <http://localhost/wsc/01/taxonomy.owl#con1233457844>
// <http://localhost/wsc/01/taxonomy.owl#con1653328292>
// <http://localhost/wsc/01/taxonomy.owl#con1988815758>
//
// Input exact
// <http://localhost:9090/iserve/id/services/db05b706-5457-448b-9d3b-9161dbe9518e/serv904934656/Operation>
// <http://localhost:9090/iserve/id/services/db05b706-5457-448b-9d3b-9161dbe9518e/serv904934656>
//
// Further Inputs
// <http://localhost/wsc/01/taxonomy.owl#con1794855625>
//
// Outputs
// <http://localhost/wsc/01/taxonomy.owl#con512919114>
// <http://localhost/wsc/01/taxonomy.owl#con633555781>
@Test
@Ignore
public void testFindOperationsProducingAll() throws Exception {
}
@Test
@Ignore
public void testFindOperationsProducingSome() throws Exception {
}
@Test
@Ignore
public void testFindOperationsClassifiedByAll() throws Exception {
}
@Test
@Ignore
public void testFindOperationsClassifiedBySome() throws Exception {
}
@Test
@Ignore
public void testFindOperationsInvocableWith() throws Exception {
}
@Test
@Ignore
public void testFindServicesConsumingAll() throws Exception {
}
@Test
@Ignore
public void testFindServicesConsumingSome() throws Exception {
}
@Test
@Ignore
public void testFindServicesProducingAll() throws Exception {
}
@Test
@Ignore
public void testFindServicesProducingSome() throws Exception {
}
@Test
@Ignore
public void testFindServicesClassifiedByAll(ServiceDiscoverer serviceDiscoverer) throws Exception {
URI modelA = URI.create("http://schema.org/CreateAction");
URI modelB = URI.create("http://schema.org/SearchAction");
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches = serviceDiscoverer.findServicesClassifiedByAll(ImmutableSet.of(modelA, modelB));
stopwatch.stop();
log.info("Obtained ({}) matches in {} \n {}", matches.size(), stopwatch, matches);
Assert.assertTrue(matches.size() == 1);
}
@Test
@Ignore
public void testFindServicesClassifiedBySome(ServiceDiscoverer serviceDiscoverer) throws Exception {
URI modelA = URI.create("http://schema.org/CreateAction");
URI modelB = URI.create("http://schema.org/SearchAction");
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches = serviceDiscoverer.findServicesClassifiedBySome(ImmutableSet.of(modelA, modelB));
stopwatch.stop();
log.info("Obtained ({}) matches in {} \n {}", matches.size(), stopwatch, matches);
Assert.assertTrue(matches.size() == 13);
}
@Test
@Ignore
public void testFindServicesInvocableWith() throws Exception {
}
/**
* JukitoModule.
*/
public static class InnerModule extends JukitoModule {
@Override
protected void configureTest() {
// Add dependency
install(new RegistryManagementModule());
// bind
bind(ConceptMatcher.class).to(SparqlLogicConceptMatcher.class);
// bind(ConceptMatcher.class).to(SparqlIndexedLogicConceptMatcher.class);
// bind
// bind(GenericLogicDiscoverer.class).in(Singleton.class);
bind(OperationDiscoverer.class).to(GenericLogicDiscoverer.class);
bind(ServiceDiscoverer.class).to(GenericLogicDiscoverer.class);
// Necessary to verify interaction with the real object
bindSpy(GenericLogicDiscoverer.class);
}
}
public static class Notation3ExtFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".n3"));
}
}
}
| 36.60559 | 214 | 0.698736 |
ab6287fe4a82c91c37ffff70eb0ba52aa1f2082f | 1,347 | package it.dbruni.commandwhitelist.listeners;
import it.dbruni.commandwhitelist.CommandWhitelist;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import java.util.Arrays;
import java.util.List;
public class Listeners implements Listener {
private List<String> allowedCommands = CommandWhitelist.getInstance().getConfig().getStringList("commands");
private final String bypass = "commandwhitelist.bypass";
@EventHandler
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
boolean allow = false;
for (String allowedCommand : allowedCommands) {
if (StringUtils.startsWithIgnoreCase(event.getMessage(), allowedCommand)) {
allow = true;
break;
}
}
if (event.getPlayer().hasPermission(bypass)) allow = true;
if (!allow) {
event.setCancelled(true);
event.getPlayer().sendMessage(format(CommandWhitelist.getInstance().getConfig().getString("message")));
}
}
public String format(String string) {
return ChatColor.translateAlternateColorCodes('&', string);
}
}
| 32.071429 | 115 | 0.703786 |
0b3187368c92775eebfb2936fc95d6a85090830e | 1,268 | //Deobfuscated with https://github.com/SimplyProgrammer/Minecraft-Deobfuscator3000 using mappings "C:\Users\Admin\Desktop\Minecraft-Deobfuscator3000-1.2.2\1.12 stable mappings"!
//Decompiled by Procyon!
package org.spongepowered.asm.mixin.injection.throwables;
import org.spongepowered.asm.mixin.refmap.*;
import org.spongepowered.asm.mixin.injection.struct.*;
public class InvalidInjectionPointException extends InvalidInjectionException
{
private static final long serialVersionUID = 2L;
public InvalidInjectionPointException(final IMixinContext context, final String format, final Object... args) {
super(context, String.format(format, args));
}
public InvalidInjectionPointException(final InjectionInfo info, final String format, final Object... args) {
super(info, String.format(format, args));
}
public InvalidInjectionPointException(final IMixinContext context, final Throwable cause, final String format, final Object... args) {
super(context, String.format(format, args), cause);
}
public InvalidInjectionPointException(final InjectionInfo info, final Throwable cause, final String format, final Object... args) {
super(info, String.format(format, args), cause);
}
}
| 42.266667 | 177 | 0.752366 |
4fd199c2c505406f75917e3187c9b0c520086d4c | 571 | package com.github.hewking.encryptlib;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class EncryptActivity extends AppCompatActivity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_encrypt);
tv = (TextView) findViewById(R.id.tv);
EncryptUtil encryptUtil = new EncryptUtil();
tv.setText(encryptUtil.clientDencrypt("hah",4).result);
}
}
| 27.190476 | 63 | 0.732049 |
4c361ada07c0e5cf761e6df7d6e780eb225decf7 | 513 | package edu.fiuba.algo3.modelo.tipoTarjeta;
public class Globo implements TipoTarjeta {
private final String nombre;
public Globo(){
this.nombre = "Globo";
}
public String obtenerNombre(){return nombre;}
public boolean esGlobo(){
return true;
}
public boolean esCanion(){
return false;
}
public boolean esBarco(){
return false;
}
@Override
public boolean esIgual(TipoTarjeta unTipo) {
return unTipo.esGlobo();
}
} | 20.52 | 49 | 0.619883 |
8e65bc3b021b9ab15fb2cb581b5bb733566763b7 | 3,199 | /*
* 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.aliyuncs.vod.transform.v20170321;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.vod.model.v20170321.DescribePlayUserTotalResponse;
import com.aliyuncs.vod.model.v20170321.DescribePlayUserTotalResponse.UserPlayStatisTotal;
import com.aliyuncs.vod.model.v20170321.DescribePlayUserTotalResponse.UserPlayStatisTotal.UV;
import com.aliyuncs.vod.model.v20170321.DescribePlayUserTotalResponse.UserPlayStatisTotal.VV;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribePlayUserTotalResponseUnmarshaller {
public static DescribePlayUserTotalResponse unmarshall(DescribePlayUserTotalResponse describePlayUserTotalResponse, UnmarshallerContext _ctx) {
describePlayUserTotalResponse.setRequestId(_ctx.stringValue("DescribePlayUserTotalResponse.RequestId"));
List<UserPlayStatisTotal> userPlayStatisTotals = new ArrayList<UserPlayStatisTotal>();
for (int i = 0; i < _ctx.lengthValue("DescribePlayUserTotalResponse.UserPlayStatisTotals.Length"); i++) {
UserPlayStatisTotal userPlayStatisTotal = new UserPlayStatisTotal();
userPlayStatisTotal.setDate(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].Date"));
userPlayStatisTotal.setPlayDuration(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].PlayDuration"));
userPlayStatisTotal.setPlayRange(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].PlayRange"));
VV vV = new VV();
vV.setFlash(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].VV.Flash"));
vV.setIOS(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].VV.iOS"));
vV.setHTML5(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].VV.HTML5"));
vV.setAndroid(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].VV.Android"));
userPlayStatisTotal.setVV(vV);
UV uV = new UV();
uV.setFlash(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].UV.Flash"));
uV.setIOS(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].UV.iOS"));
uV.setHTML5(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].UV.HTML5"));
uV.setAndroid(_ctx.stringValue("DescribePlayUserTotalResponse.UserPlayStatisTotals["+ i +"].UV.Android"));
userPlayStatisTotal.setUV(uV);
userPlayStatisTotals.add(userPlayStatisTotal);
}
describePlayUserTotalResponse.setUserPlayStatisTotals(userPlayStatisTotals);
return describePlayUserTotalResponse;
}
} | 53.316667 | 144 | 0.791497 |
1a17c96b2b3671904d410af73f600bb5dffcfe17 | 874 | package edu.cmu.ml.proppr.util;
import static org.junit.Assert.*;
import java.util.Collections;
import org.junit.Test;
import edu.cmu.ml.proppr.util.math.MuParamVector;
public class MuParamVectorTest {
private static final double EPS=1e-6;
@Test
public void testMap() {
MuParamVector foo = new MuParamVector();
foo.put("abc",1.0);
foo.put("def",10.0);
assertEquals(2,foo.size());
assertEquals(1.0,foo.get("abc"),EPS);
assertEquals(10.0,foo.get("def"),EPS);
}
@Test
public void testTimestamp() {
MuParamVector foo = new MuParamVector();
foo.put("abc",1.0);
foo.put("def",10.0);
assertEquals(0,foo.getLast("abc"));
foo.count();
assertEquals(1,foo.getLast("abc"));
assertEquals(1,foo.getLast("def"));
foo.setLast(Collections.singleton("abc"));
assertEquals(0,foo.getLast("abc"));
assertEquals(1,foo.getLast("def"));
}
}
| 20.809524 | 49 | 0.680778 |
57e1b9a24e7d8a56160456e6268f402a6d4779a5 | 1,704 | package de.ids_mannheim.korap.query.object;
import java.util.LinkedHashMap;
import java.util.Map;
/** Definition of koral:distance in KoralQuery.
*
* @author margaretha
*
*/
public class KoralDistance implements KoralObject {
private final KoralType type = KoralType.DISTANCE;
private String key = "w";
private String foundry;
private String layer;
private KoralBoundary boundary;
public KoralDistance (KoralBoundary boundary) {
this.boundary = boundary;
}
public KoralDistance (String key, KoralBoundary boundary) {
this(boundary);
this.key = key;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getFoundry() {
return foundry;
}
public void setFoundry(String foundry) {
this.foundry = foundry;
}
public String getLayer() {
return layer;
}
public void setLayer(String layer) {
this.layer = layer;
}
public KoralBoundary getBoundary() {
return boundary;
}
public void setBoundary(KoralBoundary boundary) {
this.boundary = boundary;
}
@Override
public Map<String, Object> buildMap() {
Map<String, Object> distanceMap = new LinkedHashMap<String, Object>();
distanceMap.put("@type", type.toString());
distanceMap.put("key", key);
if (foundry != null){
distanceMap.put("foundry", foundry);
}
if (layer!=null){
distanceMap.put("layer", layer);
}
distanceMap.put("boundary", boundary.buildMap());
return distanceMap;
}
}
| 22.72 | 78 | 0.607394 |
4bd347872065c6bf69cd5f397524e47db1bfad1b | 1,400 | /*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.quartz;
import java.util.Properties;
import org.quartz.impl.StdSchedulerFactory;
public class RAMSchedulerTest extends AbstractSchedulerTest {
@Override
protected Scheduler createScheduler(String name, int threadPoolSize) throws SchedulerException {
Properties config = new Properties();
config.setProperty("org.quartz.scheduler.instanceName", name + "Scheduler");
config.setProperty("org.quartz.scheduler.instanceId", "AUTO");
config.setProperty("org.quartz.threadPool.threadCount", Integer.toString(threadPoolSize));
config.setProperty("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
return new StdSchedulerFactory(config).getScheduler();
}
}
| 41.176471 | 100 | 0.746429 |
0dc3addcf1c94a8c1fe0bd14994516de133ca0fe | 3,409 | package seedu.address.logic.parser.addcommandparser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.commands.CommandTestUtil.VALID_GENERAL_EVENT_DATE_1;
import static seedu.address.logic.commands.CommandTestUtil.VALID_GENERAL_EVENT_DESCRIPTION_1;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DATE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_GENERAL_EVENT;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess;
import static seedu.address.testutil.TypicalRemindMe.VALID_GENERAL_EVENT_1;
import org.junit.jupiter.api.Test;
import seedu.address.logic.commands.addcommand.AddEventCommand;
import seedu.address.model.event.GeneralEvent;
public class AddEventCommandParserTest {
private AddEventCommandParser parser = new AddEventCommandParser();
@Test
public void parse_allFieldPresent_success() {
String userInput = " " + PREFIX_GENERAL_EVENT + VALID_GENERAL_EVENT_DESCRIPTION_1 + " "
+ PREFIX_DATE + VALID_GENERAL_EVENT_DATE_1;
assertParseSuccess(parser, userInput , new AddEventCommand(VALID_GENERAL_EVENT_1));
}
@Test
public void parse_missingValue_failure() {
//missing event description
String userInput1 = " " + PREFIX_GENERAL_EVENT + " " + PREFIX_DATE + VALID_GENERAL_EVENT_DATE_1;
assertParseFailure(parser, userInput1, GeneralEvent.DESCRIPTION_CONSTRAINT);
//missing date
String userInput2 = " " + PREFIX_GENERAL_EVENT + VALID_GENERAL_EVENT_DESCRIPTION_1 + " " + PREFIX_DATE;
assertParseFailure(parser, userInput2, GeneralEvent.DATE_CONSTRAINT);
//missing date
String userInput3 = " " + PREFIX_GENERAL_EVENT + VALID_GENERAL_EVENT_DESCRIPTION_1 + " " + PREFIX_DATE + " ";
assertParseFailure(parser, userInput3, GeneralEvent.DATE_CONSTRAINT);
}
@Test
public void parse_wrongValue_failure() {
//wrong values for date
String userInput1 = " " + PREFIX_GENERAL_EVENT + VALID_GENERAL_EVENT_DESCRIPTION_1 + " " + PREFIX_DATE + "hi";
assertParseFailure(parser, userInput1, GeneralEvent.DATE_CONSTRAINT);
String userInput2 = " " + PREFIX_GENERAL_EVENT + VALID_GENERAL_EVENT_DESCRIPTION_1 + " " + PREFIX_DATE
+ "01/01/1998";
assertParseFailure(parser, userInput2, GeneralEvent.DATE_CONSTRAINT);
String userInput3 = " " + PREFIX_GENERAL_EVENT + VALID_GENERAL_EVENT_DESCRIPTION_1 + " " + PREFIX_DATE
+ "1200";
assertParseFailure(parser, userInput3, GeneralEvent.DATE_CONSTRAINT);
}
@Test
public void parse_missingPrefix_failure() {
//missing general event prefix
String userInput1 = " " + VALID_GENERAL_EVENT_DESCRIPTION_1 + " " + PREFIX_DATE + VALID_GENERAL_EVENT_DATE_1;
assertParseFailure(parser, userInput1,
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddEventCommand.MESSAGE_USAGE));
//missing date prefix
String userInput2 = " " + PREFIX_GENERAL_EVENT + VALID_GENERAL_EVENT_DESCRIPTION_1 + " "
+ VALID_GENERAL_EVENT_DATE_1;
assertParseFailure(parser, userInput2,
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddEventCommand.MESSAGE_USAGE));
}
}
| 48.014085 | 118 | 0.741566 |
65f7d77d86c7c04ec6842e78de64b4c8e4359462 | 194 | package rss_to_telegram.dto_layer;
public class Article {
public String title;
public String link;
public String description;
public String pubDate;
public String author;
}
| 19.4 | 34 | 0.731959 |
99bf650f0bf2a78e48ed289264d50fcb47e3148c | 3,668 |
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.olap.data.impl;
/**
*
*/
public class NamingUtil
{
private static final String OLAP_PREFIX = "olap/";
private static final String CUBE_PREFIX = OLAP_PREFIX + "cube_";
private static final String DIMENSION_PREFIX = OLAP_PREFIX + "dim_";
private static final String HIERARCHY_PREFIX = OLAP_PREFIX + "hierarchy_";
private static final String LEVEL_INDEX = OLAP_PREFIX + "level_index_";
private static final String HIERARCHY_OFFSET = OLAP_PREFIX + "hierarchy_offset_";
private static final String FACT_TABLE = OLAP_PREFIX + "fact_table_";
private static final String FTSU_LIST = OLAP_PREFIX + "ftsu_list_";
private static final String AGGREGATION_RS_DOC = OLAP_PREFIX + "rs_doc_";
public static final String DERIVED_MEASURE_PREFIX = "_${DERIVED_MEASURE}$_";
/**
*
* @param cubeName
* @return
*/
public static String getCubeDocName( String cubeName )
{
return CUBE_PREFIX + cubeName;
}
/**
*
* @param dimensionName
* @return
*/
public static String getDimensionDocName( String dimensionName )
{
return DIMENSION_PREFIX + dimensionName;
}
/**
*
* @param hierarchylName
* @return
*/
public static String getHierarchyDocName( String dimensionName, String hierarchylName )
{
return HIERARCHY_PREFIX + dimensionName + hierarchylName;
}
/**
*
* @param dimensionName
* @param levelName
* @return
*/
public static String getLevelIndexDocName( String dimensionName, String levelName )
{
return LEVEL_INDEX + dimensionName + '_' + levelName;
}
public static String getLevelIndexOffsetDocName( String dimensionName, String levelName )
{
return getLevelIndexDocName( dimensionName, levelName )+"_offset";
}
/**
*
* @param levelName
* @return
*/
public static String getHierarchyOffsetDocName( String dimensionName, String hierarchylName )
{
return HIERARCHY_OFFSET + dimensionName + hierarchylName;
}
/**
*
* @param cubeName
* @return
*/
public static String getFactTableName( String factTableName )
{
return FACT_TABLE + factTableName;
}
/**
* construct derived measure name with prefix DERIVED_MEASURE_PREFIX
*/
public static String getDerivedMeasureName( String measureName )
{
return DERIVED_MEASURE_PREFIX + measureName;
}
/**
* construct derived measure name with prefix DERIVED_MEASURE_PREFIX
*/
public static String getMeasureName( String name )
{
if( name!= null )
{
if( name.startsWith( DERIVED_MEASURE_PREFIX ) )
return name.substring( DERIVED_MEASURE_PREFIX.length( ) );
}
return name;
}
/**
* construct derived measure name with prefix DERIVED_MEASURE_PREFIX
*/
public static boolean isDerivedMeasureName( String name )
{
if( name!= null )
{
return name.startsWith( DERIVED_MEASURE_PREFIX );
}
return false;
}
/**
*
* @param factTableName
* @return
*/
public static String getFTSUListName( String factTableName )
{
return FTSU_LIST + factTableName;
}
/**
*
* @param ID
* @return
*/
public static String getAggregationRSDocName( String ID )
{
return AGGREGATION_RS_DOC + ID;
}
}
| 24.131579 | 94 | 0.688659 |
135a67a5520beb259e51062bb694dd8bd832e9ba | 914 | package br.com.microservice.fornecedor.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.microservice.fornecedor.entities.InfoProvider;
import br.com.microservice.fornecedor.service.IInfoProviderService;
import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("/info")
@Slf4j
public class InfoProviderController {
@Autowired
private IInfoProviderService infoProviderService;
@GetMapping("/{state}")
public InfoProvider getInfoProviderByState(@PathVariable String state) {
log.info("information request from the service provider {} " + state);
return this.infoProviderService.getInfoByState(state);
}
}
| 32.642857 | 73 | 0.828228 |
99f5072eb3c34acb209e661b3657d86d4d87946c | 1,276 | package top.jsjkxyjs.service;
import top.jsjkxyjs.entity.Class;
import top.jsjkxyjs.entity.User;
import java.util.List;
public interface CounselorService {
/**
* 调用此方法获取辅导员对应的班级成员信息
*
* @param classId 班级id
* @return list集合
*/
List<User> doGetClassUser(int classId);
/**
* 调用此方法,删除相应用户的信息
*
* @param userId 学生id
* @return 删除成功信息
*/
int doDelUser(int userId);
/**
* 调用此方法,批量删除用户信息
*
* @param a 用户列表
* @return 删除成功信息
*/
int doDelUserList(int[] a);
/**
* 增加学生用户
*
* @param student 学生信息
* @return 增加成功信息
*/
int doAddUser(User student);
/**
* 获取辅导员对应的班级信息
*
* @param userId uerId
* @return class对象
*/
Class doGetClass(int userId);
/**
* 更新单元格
*
* @param field 字段
* @param value 值
* @return 更改结果信息
*/
int doUpdate(String field, String value, int userId);
/**
* 搜索用户
*
* @param userId id
* @param userName name
* @return 结果
*/
List<User> doSearch(int userId, String userName, int classId);
/**
* 获取班级学生每门课的成绩
*
* @param classId 班级编号
* @return 成绩列表
*/
List<User> doGetGradeByClass(int classId);
}
| 16.571429 | 66 | 0.543103 |
926b4bbc90bd5fa3c139506fd741de4838545a85 | 23,255 | /**
* 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.fineract.infrastructure.creditbureau.service;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.fineract.commands.domain.CommandWrapper;
import org.apache.fineract.commands.service.CommandWrapperBuilder;
import org.apache.fineract.infrastructure.core.api.JsonCommand;
import org.apache.fineract.infrastructure.core.data.ApiParameterError;
import org.apache.fineract.infrastructure.core.data.DataValidatorBuilder;
import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException;
import org.apache.fineract.infrastructure.core.exception.PlatformDataIntegrityException;
import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper;
import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauConfigurations;
import org.apache.fineract.infrastructure.creditbureau.data.CreditBureauReportData;
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfiguration;
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfigurationRepository;
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauConfigurationRepositoryWrapper;
import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauToken;
import org.apache.fineract.infrastructure.creditbureau.domain.CreditReportRepository;
import org.apache.fineract.infrastructure.creditbureau.domain.TokenRepositoryWrapper;
import org.apache.fineract.infrastructure.creditbureau.serialization.CreditBureauTokenCommandFromApiJsonDeserializer;
import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Component
@Service
public class ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl implements ThitsaWorksCreditBureauIntegrationWritePlatformService {
private final PlatformSecurityContext context;
private final FromJsonHelper fromApiJsonHelper;
private final TokenRepositoryWrapper tokenRepositoryWrapper;
private final CreditBureauConfigurationRepositoryWrapper configDataRepository;
private final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer;
private final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
private final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
.resource("ThitsaWorksCreditBureauIntegration");
@Autowired
public ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl(final PlatformSecurityContext context,
final FromJsonHelper fromApiJsonHelper, final TokenRepositoryWrapper tokenRepositoryWrapper,
final CreditBureauConfigurationRepositoryWrapper configDataRepository,
final CreditBureauConfigurationRepository configurationDataRepository,
final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer,
final CreditReportRepository creditReportRepository) {
this.context = context;
this.tokenRepositoryWrapper = tokenRepositoryWrapper;
this.configDataRepository = configDataRepository;
this.fromApiJsonHelper = fromApiJsonHelper;
this.fromApiJsonDeserializer = fromApiJsonDeserializer;
}
private static final Logger LOG = LoggerFactory.getLogger(ThitsaWorksCreditBureauIntegrationWritePlatformServiceImpl.class);
@Transactional
@Override
@SuppressWarnings("deprecation")
public String okHttpConnectionMethod(String userName, String password, String subscriptionKey, String subscriptionId, String url,
String token, File file, FormDataContentDisposition fileData, Long uniqueId, String nrcId, String process) {
String reponseMessage = null;
RequestBody requestBody = null;
OkHttpClient client = new OkHttpClient();
if (process.equals("UploadCreditReport")) {
String fileName = fileData.getFileName();
requestBody = RequestBody.create(file, MediaType.parse("multipart/form-data"));
requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", fileName, requestBody)
.addFormDataPart("BODY", "formdata").addFormDataPart("userName", userName).build();
} else if (process.equals("token")) {
final MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
String jsonBody = "" + "BODY=x-www-form-urlencoded&\r" + "grant_type=password&\r" + "userName=" + userName + "&\r" + "password="
+ password + "&\r";
requestBody = RequestBody.create(jsonBody, mediaType);
} else if (process.equals("NRC")) {
final MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
String jsonBody = "BODY=x-www-form-urlencoded&nrc=" + nrcId + "&";
requestBody = RequestBody.create(jsonBody, mediaType);
}
HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
String urlokhttp = urlBuilder.build().toString();
Request request = null;
if (token == null) {
request = new Request.Builder().header("mcix-subscription-key", subscriptionKey).header("mcix-subscription-id", subscriptionId)
.header("Content-Type", "application/x-www-form-urlencoded").url(urlokhttp).post(requestBody).build();
}
if (token != null) {
if (process.equals("CreditReport")) { // GET method for fetching credit report
request = new Request.Builder().header("mcix-subscription-key", subscriptionKey)
.header("mcix-subscription-id", subscriptionId).header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Bearer " + token).url(urlokhttp).get().build();
} else if (process.equals("UploadCreditReport")) { // POST for uploading Credit-Report(multipart/form-data)
// To ThitsaWork
request = new Request.Builder().header("mcix-subscription-key", subscriptionKey)
.header("mcix-subscription-id", subscriptionId).header("Content-Type", "multipart/form-data")
.header("Authorization", "Bearer " + token).url(urlokhttp).post(requestBody).build();
} else { // POST method for application/x-www-form-urlencoded
request = new Request.Builder().header("mcix-subscription-key", subscriptionKey)
.header("mcix-subscription-id", subscriptionId).header("Content-Type", "application/x-www-form-urlencoded")
.header("Authorization", "Bearer " + token).url(urlokhttp).post(requestBody).build();
}
}
Response response;
Integer responseCode = 0;
try {
response = client.newCall(request).execute();
responseCode = response.code();
reponseMessage = response.body().string();
} catch (IOException e) {
LOG.error("error occured in HTTP request-response method.", e);
}
if (responseCode != HttpURLConnection.HTTP_OK) {
this.httpResponse(responseCode, reponseMessage);
}
if (process.equals("UploadCreditReport")) { // to show the Response on frontEnd
JsonObject reportObject = JsonParser.parseString(reponseMessage).getAsJsonObject();
String ResponseMessageJson = reportObject.get("ResponseMessage").getAsString();
this.handleAPIIntegrityIssues(ResponseMessageJson);
}
return reponseMessage;
}
private void httpResponse(Integer responseCode, String responseMessage) {
if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
String httpResponse = "HTTP_UNAUTHORIZED";
this.handleAPIIntegrityIssues(httpResponse);
} else if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
String httpResponse = "HTTP_FORBIDDEN";
this.handleAPIIntegrityIssues(httpResponse);
} else {
String responseResult = "HTTP Response Code: " + responseCode + "/" + "Response Message: " + responseMessage;
this.handleAPIIntegrityIssues(responseResult);
}
}
@Transactional
@Override
public CreditBureauReportData getCreditReportFromThitsaWorks(final JsonCommand command) {
this.context.authenticatedUser();
String nrcId = command.stringValueOfParameterNamed("NRC");
String bureauID = command.stringValueOfParameterNamed("creditBureauID");
Integer creditBureauId = Integer.parseInt(bureauID);
String token = null;
String userName = getCreditBureauConfiguration(creditBureauId, CreditBureauConfigurations.USERNAME.toString());
String password = getCreditBureauConfiguration(creditBureauId, CreditBureauConfigurations.PASSWORD.toString());
String subscriptionId = getCreditBureauConfiguration(creditBureauId, CreditBureauConfigurations.SUBSCRIPTIONID.toString());
String subscriptionKey = getCreditBureauConfiguration(creditBureauId, CreditBureauConfigurations.SUBSCRIPTIONKEY.toString());
CreditBureauToken creditbureautoken = createToken(creditBureauId.longValue());
token = creditbureautoken.getCurrentToken();
// will use only "NRC" part of code from common http method to get data based on nrc
String process = "NRC";
String url = getCreditBureauConfiguration(creditBureauId, CreditBureauConfigurations.SEARCHURL.toString());
String nrcUrl = url + nrcId;
String searchResult = this.okHttpConnectionMethod(userName, password, subscriptionKey, subscriptionId, nrcUrl, token, null, null,
0L, nrcId, process);
if (process.equals("NRC")) {
Long uniqueID = this.extractUniqueId(searchResult);
process = "CreditReport";
url = getCreditBureauConfiguration(creditBureauId, CreditBureauConfigurations.CREDITREPORTURL.toString());
String creditReportUrl = url + uniqueID;
searchResult = this.okHttpConnectionMethod(userName, password, subscriptionKey, subscriptionId, creditReportUrl, token, null,
null, uniqueID, null, process);
}
// after getting the result(creditreport) from httpconnection-response it will assign creditreport to generic
// creditreportdata object
JsonObject reportObject = JsonParser.parseString(searchResult).getAsJsonObject();
// Credit Reports Stored into Generic CreditReportData
JsonObject jsonData = null;
JsonElement element = reportObject.get("Data");
if (!(element instanceof JsonNull)) { // NOTE : "element instanceof JsonNull" is for handling empty values (and
// assigning null) while fetching data from results
jsonData = (JsonObject) element;
}
JsonObject borrowerInfos = null;
String borrowerInfo = null;
element = jsonData.get("BorrowerInfo");
if (!(element instanceof JsonNull)) {
borrowerInfos = (JsonObject) element;
Gson gson = new Gson();
borrowerInfo = gson.toJson(borrowerInfos);
}
String Name = borrowerInfos.get("Name").toString();
String Gender = borrowerInfos.get("Gender").toString();
String Address = borrowerInfos.get("Address").toString();
String creditScore = "CreditScore";
creditScore = getJsonObjectToString(creditScore, element, jsonData);
String activeLoans = "ActiveLoans";
JsonArray activeLoansArray = getJsonObjectToArray(activeLoans, element, jsonData);
String[] activeLoanStringArray = null;
if (activeLoansArray != null) {
activeLoanStringArray = convertArrayintoStringArray(activeLoansArray);
}
String writeOffLoans = "WriteOffLoans";
JsonArray writeOffLoansArray = getJsonObjectToArray(writeOffLoans, element, jsonData);
String[] writeoffLoanStringArray = null;
if (writeOffLoansArray != null) {
writeoffLoanStringArray = convertArrayintoStringArray(writeOffLoansArray);
}
return CreditBureauReportData.instance(Name, Gender, Address, creditScore, borrowerInfo, activeLoanStringArray,
writeoffLoanStringArray);
}
@Override
@Transactional
public String addCreditReport(Long bureauId, File creditReport, FormDataContentDisposition fileDetail) {
Integer creditBureauId = bureauId.intValue();
String userName = this.getCreditBureauConfiguration(creditBureauId, CreditBureauConfigurations.USERNAME.toString());
String password = this.getCreditBureauConfiguration(creditBureauId, CreditBureauConfigurations.PASSWORD.toString());
String subscriptionId = this.getCreditBureauConfiguration(creditBureauId, CreditBureauConfigurations.SUBSCRIPTIONID.toString());
String subscriptionKey = this.getCreditBureauConfiguration(creditBureauId, CreditBureauConfigurations.SUBSCRIPTIONKEY.toString());
CreditBureauToken creditbureautoken = this.createToken(creditBureauId.longValue());
String token = creditbureautoken.getCurrentToken();
CreditBureauConfiguration addReportURL = this.configDataRepository.getCreditBureauConfigData(creditBureauId, "addCreditReporturl");
String url = addReportURL.getValue();
String process = "UploadCreditReport";
String responseMessage = this.okHttpConnectionMethod(userName, password, subscriptionKey, subscriptionId, url, token, creditReport,
fileDetail, 0L, null, process);
return responseMessage;
}
private String[] convertArrayintoStringArray(JsonArray jsonResult) {
String[] loanAccounts = new String[jsonResult.size()];
Integer i = 0;
for (JsonElement ele : jsonResult) {
loanAccounts[i++] = ele.toString();
}
return loanAccounts;
}
@Override
@Transactional
public Long extractUniqueId(String jsonResult) {
JsonObject reportObject = JsonParser.parseString(jsonResult).getAsJsonObject();
JsonElement element = reportObject.get("Data");
if (element.isJsonNull()) {
String ResponseMessage = reportObject.get("ResponseMessage").getAsString();
handleAPIIntegrityIssues(ResponseMessage);
}
// to fetch the Unique ID from Result
JsonObject jsonObject = JsonParser.parseString(jsonResult).getAsJsonObject();
Long uniqueID = 0L;
try {
JsonArray dataArray = jsonObject.getAsJsonArray("Data");
if (dataArray.size() == 1) {
JsonObject jobject = dataArray.get(0).getAsJsonObject();
String uniqueIdString = jobject.get("UniqueID").toString();
String TrimUniqueId = uniqueIdString.substring(1, uniqueIdString.length() - 1);
uniqueID = Long.parseLong(TrimUniqueId);
} else if (dataArray.size() == 0) {
String ResponseMessage = reportObject.get("ResponseMessage").getAsString();
handleAPIIntegrityIssues(ResponseMessage);
} else {
String nrc = null;
List<String> arrlist = new ArrayList<String>();
for (int i = 0; i < dataArray.size(); ++i) {
JsonObject data = dataArray.get(i).getAsJsonObject();
nrc = data.get("NRC").toString();
arrlist.add(nrc);
}
String listString = String.join(", ", arrlist);
this.handleMultipleNRC(listString);
}
} catch (IndexOutOfBoundsException e) {
String ResponseMessage = jsonObject.get("ResponseMessage").getAsString();
handleAPIIntegrityIssues(ResponseMessage);
}
return uniqueID;
}
private String getJsonObjectToString(String fetchData, JsonElement element, JsonObject jsonData) {
String jsonString = null;
element = jsonData.get(fetchData);
if (!(element instanceof JsonNull)) {
JsonObject fetchJson = (JsonObject) element;
Gson gson = new Gson();
jsonString = gson.toJson(fetchJson);
}
return jsonString;
}
private JsonArray getJsonObjectToArray(String fetchData, JsonElement element, JsonObject jsonData) {
JsonArray fetchJson = null;
element = jsonData.get(fetchData);
if (!(element instanceof JsonNull)) {
fetchJson = (JsonArray) element;
}
return fetchJson;
}
@Transactional
@Override
public CreditBureauToken createToken(Long bureauID) {
CreditBureauToken creditBureauToken = this.tokenRepositoryWrapper.getToken();
// check the expiry date of the previous token.
if (creditBureauToken != null) {
Date current = new Date();
Date getExpiryDate = creditBureauToken.getTokenExpiryDate();
if (getExpiryDate.before(current)) {
this.tokenRepositoryWrapper.delete(creditBureauToken);
creditBureauToken = null;
}
}
// storing token if it is valid token(not expired)
if (creditBureauToken != null) {
creditBureauToken = this.tokenRepositoryWrapper.getToken();
}
String userName = getCreditBureauConfiguration(bureauID.intValue(), CreditBureauConfigurations.USERNAME.toString());
String password = getCreditBureauConfiguration(bureauID.intValue(), CreditBureauConfigurations.PASSWORD.toString());
String subscriptionId = getCreditBureauConfiguration(bureauID.intValue(), CreditBureauConfigurations.SUBSCRIPTIONID.toString());
String subscriptionKey = getCreditBureauConfiguration(bureauID.intValue(), CreditBureauConfigurations.SUBSCRIPTIONKEY.toString());
if (creditBureauToken == null) {
String url = getCreditBureauConfiguration(bureauID.intValue(), CreditBureauConfigurations.TOKENURL.toString());
String process = "token";
String nrcId = null;
Long uniqueID = 0L;
String result = this.okHttpConnectionMethod(userName, password, subscriptionKey, subscriptionId, url, null, null, null,
uniqueID, nrcId, process);
// created token will be storing it into database
final CommandWrapper wrapper = new CommandWrapperBuilder().withJson(result).build();
final String json = wrapper.getJson();
JsonCommand apicommand = null;
final JsonElement parsedCommand = this.fromApiJsonHelper.parse(json);
apicommand = JsonCommand.from(json, parsedCommand, this.fromApiJsonHelper, wrapper.getEntityName(), wrapper.getEntityId(),
wrapper.getSubentityId(), wrapper.getGroupId(), wrapper.getClientId(), wrapper.getLoanId(), wrapper.getSavingsId(),
wrapper.getTransactionId(), wrapper.getHref(), wrapper.getProductId(), wrapper.getCreditBureauId(),
wrapper.getOrganisationCreditBureauId());
this.fromApiJsonDeserializer.validateForCreate(apicommand.json());
final CreditBureauToken generatedtoken = CreditBureauToken.fromJson(apicommand);
final CreditBureauToken credittoken = this.tokenRepositoryWrapper.getToken();
if (credittoken != null) {
this.tokenRepositoryWrapper.delete(credittoken);
}
this.tokenRepositoryWrapper.save(generatedtoken);
creditBureauToken = this.tokenRepositoryWrapper.getToken();
}
return creditBureauToken;
}
public String getCreditBureauConfiguration(Integer creditBureauId, String configurationParameterName) {
String creditBureauConfigurationValue = null;
try {
CreditBureauConfiguration configurationParameterValue = this.configDataRepository.getCreditBureauConfigData(creditBureauId,
configurationParameterName);
creditBureauConfigurationValue = configurationParameterValue.getValue();
if (creditBureauConfigurationValue.isEmpty()) {
baseDataValidator.reset().failWithCode("creditBureau.configuration." + configurationParameterName + ".is.not.available");
throw new PlatformDataIntegrityException("creditBureau.Configuration." + configurationParameterName + ".is.not.available",
"creditBureau.Configuration." + configurationParameterName + ".is.not.available");
}
} catch (NullPointerException ex) {
baseDataValidator.reset().failWithCode("creditBureau.configuration.is.not.available");
throw new PlatformApiDataValidationException("creditBureau.Configuration.is.not.available" + ex,
"creditBureau.Configuration.is.not.available", dataValidationErrors);
}
return creditBureauConfigurationValue;
}
private void handleAPIIntegrityIssues(String httpResponse) {
throw new PlatformDataIntegrityException(httpResponse, httpResponse);
}
private void handleMultipleNRC(String nrc) {
String showMessageForMultipleNRC = "Found Multiple NRC's, Enter one from the given:" + nrc + "." + "";
throw new PlatformDataIntegrityException(showMessageForMultipleNRC, showMessageForMultipleNRC);
}
}
| 45.331384 | 140 | 0.700194 |
295e14faba86a5fd0bf98cee6a8d41a1b2e34d5b | 2,089 | /*
* Testerra
*
* (C) 2020, Peter Lehmann, T-Systems Multimedia Solutions GmbH, Deutsche Telekom AG
*
* Deutsche Telekom AG and all other contributors /
* copyright owners license 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 eu.tsystems.mms.tic.testframework.hooks;
import eu.tsystems.mms.tic.testframework.constants.Browsers;
import eu.tsystems.mms.tic.testframework.execution.testng.RetryAnalyzer;
import eu.tsystems.mms.tic.testframework.execution.testng.SeleniumRetryAnalyzer;
import eu.tsystems.mms.tic.testframework.pageobjects.GuiElement;
import eu.tsystems.mms.tic.testframework.pageobjects.internal.core.DesktopGuiElementCoreFactory;
import eu.tsystems.mms.tic.testframework.webdrivermanager.DesktopWebDriverFactory;
import eu.tsystems.mms.tic.testframework.webdrivermanager.WebDriverManager;
public class DriverUiHookDesktop implements ModuleHook {
private static final String[] browsers = {
Browsers.safari,
Browsers.ie,
Browsers.chrome,
Browsers.chromeHeadless,
Browsers.edge,
Browsers.firefox,
Browsers.phantomjs
};
@Override
public void init() {
WebDriverManager.registerWebDriverFactory(new DesktopWebDriverFactory(), browsers);
GuiElement.registerGuiElementCoreFactory(new DesktopGuiElementCoreFactory(), browsers);
RetryAnalyzer.registerAdditionalRetryAnalyzer(new SeleniumRetryAnalyzer());
}
@Override
public void terminate() {
}
}
| 37.981818 | 97 | 0.7281 |
4fb000abf115d133d44a560dded5fe67a1140765 | 3,750 | package com.quanyan.yhy.ui.wallet.view;
/**
* Created by Administrator on 2016/10/31.
*/
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import com.harwkin.nb.camera.CameraHandler;
import com.harwkin.nb.camera.CropBuilder;
import com.harwkin.nb.camera.callback.CameraImageListener;
import com.harwkin.nb.camera.pop.CameraPopListener;
import com.quanyan.yhy.R;
/**
* Custom PopWindow
*
* @author tianhaibo
*/
public class IDCardOptionDailog {
private Context mContext;
private CameraPopListener mPopListern;
private CameraHandler mCameraHandler;
private int clickId;
public IDCardOptionDailog(Context context, CameraPopListener listener,
CameraImageListener imageListener) {
initContext(context, listener);
this.mContext = context;
mCameraHandler = new CameraHandler(context, imageListener);
mCameraHandler.getOptions().setNeedCameraCompress(true);
mCameraHandler.getOptions().setImageHeightCompress(2200);
mCameraHandler.getOptions().setImageWidthCompress(2200);
}
public void showOptionDialog() {
View view = LayoutInflater.from(mContext).inflate(
R.layout.dialog_upload_idcard_layout, null);
RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.rl);
relativeLayout.getBackground().setAlpha(5);
final Dialog dialog = new Dialog(mContext, R.style.MenuDialogStyle);
dialog.setContentView(view);
dialog.show();
Window window = dialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
int screenW = getScreenWidth(mContext);
lp.width = screenW;
window.setGravity(Gravity.BOTTOM);
window.setWindowAnimations(R.style.MenuDialogAnimation); // 添加动画
view.findViewById(R.id.rl_takephoto).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPopListern.onCamreaClick(mCameraHandler.getOptions());
dialog.dismiss();
}
});
view.findViewById(R.id.rl_ablum).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mPopListern.onPickClick(mCameraHandler.getOptions());
dialog.dismiss();
}
});
view.findViewById(R.id.tv_cancel_photo).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
public static int getScreenWidth(Context context) {
DisplayMetrics dm = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
return dm.widthPixels;
}
private void initContext(Context context, CameraPopListener listener) {
this.mContext = context;
this.mPopListern = listener;
}
public void setCropBuilder(CropBuilder builder) {
mCameraHandler.getOptions().setCropBuilder(builder);
}
public void process() {
try {
mCameraHandler.process();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void forResult(int requestCode, int resultCode, Intent data) {
mCameraHandler.forResult(requestCode, resultCode, data);
}
}
| 32.051282 | 95 | 0.672267 |
7eeffa8faaf06df72dbe0c84fa1ecb172687b7e4 | 3,005 | package com.jonss.fluid27.actitities;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import com.jonss.fluid27.R;
import com.jonss.fluid27.connection.Connectivity;
import com.jonss.fluid27.layout.PostAdapter;
import com.jonss.fluid27.model.Post;
import com.jonss.fluid27.task.PostAsyncTask;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private List<Post> posts = new ArrayList<>();
private ListView postsListView;
private SwipeRefreshLayout swipe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Connectivity.isConnected(this)) {
listAllPosts();
this.swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(this);
} else {
dialogIfOffline();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_about) {
Intent about = new Intent(this, AboutActivity.class);
startActivity(about);
return false;
}
return super.onOptionsItemSelected(item);
}
private void listAllPosts() {
try {
posts = new PostAsyncTask().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
setPostsOnView();
}
private void setPostsOnView() {
postsListView = (ListView) findViewById(R.id.posts_list_view);
PostAdapter postAdapter = new PostAdapter(posts, this);
postsListView.setAdapter(postAdapter);
}
@Override
public void onRefresh() {
listAllPosts();
swipe.setColorSchemeColors(R.color.fluid_blue);
swipe.setRefreshing(false);
swipe.clearAnimation();
}
private void dialogIfOffline() {
new AlertDialog.Builder(this)
.setTitle("Erro")
.setMessage("Houve um erro ao acessar o app, verifique sua conexão.")
.setNegativeButton("Sair", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).show();
}
}
| 30.353535 | 101 | 0.649584 |
39566b1cc0c471f71212f9319e1497d0e3dcac66 | 288 | package at.tuwien.repository.jpa;
import at.tuwien.entities.container.Container;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ContainerRepository extends JpaRepository<Container, Long> {
}
| 26.181818 | 77 | 0.84375 |
467257e9595c804739f186d5826667c81ea430e4 | 1,698 | /*
* 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.
*/
/*
* ObjectState.java
*
*/
package javax.jdo;
/**
* This class defines the object states for JDO instances.
*
* @version 2.1
*/
public enum ObjectState {
TRANSIENT("transient"),
TRANSIENT_CLEAN("transient-clean"),
TRANSIENT_DIRTY("transient-dirty"),
PERSISTENT_NEW("persistent-new"),
HOLLOW_PERSISTENT_NONTRANSACTIONAL("hollow/persistent-nontransactional"),
PERSISTENT_NONTRANSACTIONAL_DIRTY("persistent-nontransactional-dirty"),
PERSISTENT_CLEAN("persistent-clean"),
PERSISTENT_DIRTY("persistent-dirty"),
PERSISTENT_DELETED("persistent-deleted"),
PERSISTENT_NEW_DELETED("persistent-new-deleted"),
DETACHED_CLEAN("detached-clean"),
DETACHED_DIRTY("detached-dirty");
private final String value;
private ObjectState(String value) {
this.value = value;
}
public String toString() {
return value;
}
}
| 30.321429 | 77 | 0.727915 |
0115ce990a97dceb2f8c2b8aa7c8ff96a50b8212 | 3,011 | package com.mexus.homeleisure.api.image;
import com.mexus.homeleisure.common.BaseControllerTest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.hateoas.MediaTypes;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.io.File;
import java.io.FileInputStream;
import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.pathParameters;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@DisplayName("프로필 이미지 업로드 테스트")
class UploadProfileImageTest extends BaseControllerTest {
@Test
@DisplayName("프로필 이미지 업로드")
void uploadProfileImageSuccess() throws Exception {
String accessToken = accountFactory.generateUser(1).getAccessToken();
File targetFile = new File("./files/profileImg/test.jpg");
MockMultipartFile image = new MockMultipartFile(
"image", targetFile.getName(), "image/jpeg", new FileInputStream(targetFile));
this.mockMvc.perform(RestDocumentationRequestBuilders.fileUpload("/profile/{userId}/image", "TestUser1").file(image)
.accept(MediaTypes.HAL_JSON)
.header("Authorization", "Bearer " + accessToken)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(print())
.andDo(document("uploadProfileImage",
pathParameters(
parameterWithName("userId").description("user id")
)
))
;
this.mockMvc.perform(get("/profile/{userId}/image", "TestUser1"))
.andExpect(status().isOk())
.andDo(print());
}
@Test
@DisplayName("프로필 이미지 업로드")
void uploadProfileImageFailBecauseBadFileName() throws Exception {
String accessToken = accountFactory.generateUser(1).getAccessToken();
File targetFile = new File("./files/test..jpg");
MockMultipartFile image = new MockMultipartFile(
"image", targetFile.getName(), "image/jpeg", new FileInputStream(targetFile));
this.mockMvc.perform(RestDocumentationRequestBuilders.fileUpload("/profile/{userId}/image", "TestUser1").file(image)
.accept(MediaTypes.HAL_JSON)
.header("Authorization", "Bearer " + accessToken)
)
.andExpect(MockMvcResultMatchers.status().isBadRequest())
.andDo(print())
.andDo(document("3001"));
}
} | 46.323077 | 124 | 0.697443 |
76f6a8539d79484699cd2df3fc2147cb039a74f2 | 3,195 | package it.polimi.ingsw.model;
/**
* Class that is used to store general player's information
*/
public class Player {
/**
* Player's username
*/
private final String username;
/**
* Player's status
*/
private StatusPlayer status;
/**
* Player's color
*/
private Color color;
/**
* Player's god
*/
private God god;
/**
* Player's number of worker to place
*/
private int workers;
/**
* Create a Player instance with a username
*
* @param username player's username
* @exception NullPointerException if username is null
*/
public Player(String username) {
if (username == null)
throw new NullPointerException();
this.username = username;
this.status = StatusPlayer.IDLE;
workers = 2;
}
/**
* Create a Player's instance from a Player instance
*
* @param player Player's instance
* @exception NullPointerException if player is null
*/
public Player(Player player) {
if (player == null)
throw new NullPointerException();
this.username = player.username;
this.color = player.getColor();
this.god = player.god;
this.workers = player.workers;
this.status = player.getStatusPlayer();
}
/**
* Set player's status
*
* @param status status to set
* @exception NullPointerException if status is null
*/
public void setStatusPlayer(StatusPlayer status) {
if (status == null)
throw new NullPointerException();
this.status = status;
}
/**
* Get player's status
*
* @return player's status
*/
public StatusPlayer getStatusPlayer() {
return status;
}
/**
* Set player color
*
* @param color color to be set
* @exception NullPointerException if color is null
*/
public void setColor(Color color) {
if (color == null)
throw new NullPointerException();
this.color = color;
}
/**
* Get Player's color
*
* @return player's color
*/
public Color getColor() {
return color;
}
/**
* Set player's god
*
* @param god god to be set
* @exception NullPointerException if god is null
*/
public void setGod(God god) {
if (god == null)
throw new NullPointerException();
this.god = god;
}
/**
* Delete a worker to place
*
* @return remaining number of workers to place
*/
public int placeWoker() {
if (workers == 0)
throw new IllegalAccessError();
workers--;
return workers;
}
/**
* Get player's god
*
* @return player's god
*/
public God getGod() {
return god;
}
/**
* Get player's username
*
* @return player's username
*/
public String getUsername() {
return username;
}
} | 22.659574 | 60 | 0.523005 |
25d0d027f2f81c86cf1624bd668035ac88454617 | 18 | package Classes;
| 6 | 16 | 0.777778 |
f2735acdc90a7e52a6ec7cb1798b6b18487760f8 | 3,165 | /*===========================================================================
Copyright (C) 2009 by the Okapi Framework contributors
-----------------------------------------------------------------------------
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
===========================================================================*/
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URL;
import net.sf.okapi.common.LocaleId;
import net.sf.okapi.common.filters.FilterConfigurationMapper;
import net.sf.okapi.common.filters.IFilterConfigurationMapper;
import net.sf.okapi.common.pipelinedriver.IPipelineDriver;
import net.sf.okapi.common.pipelinedriver.PipelineDriver;
import net.sf.okapi.common.resource.RawDocument;
import net.sf.okapi.steps.common.FilterEventsWriterStep;
import net.sf.okapi.steps.common.RawDocumentToFilterEventsStep;
/**
* Example showing an Okapi pipeline running XSLT transformations on a file. The
* transformed file is then run through the XML filter (broken down into Okapi
* Events) and then re-written using the generic Event writer.
*/
public class Main {
public static void main (String[] args)
throws URISyntaxException, UnsupportedEncodingException
{
IPipelineDriver driver = new PipelineDriver();
IFilterConfigurationMapper fcMapper = new FilterConfigurationMapper();
fcMapper.addConfigurations("net.sf.okapi.filters.xml.XMLFilter");
driver.setFilterConfigurationMapper(fcMapper);
// Input resource as URL
URL inputXml = Main.class.getResource("test.xml");
// Make copy of input using identity XSLT
InputStream in = Main.class.getResourceAsStream("identity.xsl");
driver.addStep(new XsltTransformStep(in));
// Remove b tags from input using remove_b_tags XSLT
in = Main.class.getResourceAsStream("remove_b_tags.xsl");
driver.addStep(new XsltTransformStep(in));
// Filtering step - converts raw resource to events
driver.addStep(new RawDocumentToFilterEventsStep());
// Writer step - converts events to a raw resource
driver.addStep(new FilterEventsWriterStep());
// Set the info for the input and output
RawDocument rawDoc = new RawDocument(inputXml.toURI(), "UTF-8",
new LocaleId("en"), new LocaleId("fr"));
rawDoc.setFilterConfigId("okf_xml");
driver.addBatchItem(rawDoc, (new File("output.xml")).toURI(), "UTF-8");
// Run the pipeline:
// (1) XSLT identity conversion step
// (2) XSLT replace b tag conversion step
// (3) XML filtering step creates IResource Events
// (4) Writer step takes Events and writes them out to outStream
driver.processBatch();
}
}
| 40.063291 | 80 | 0.71406 |
b07e834b176b8f9328b342ae221bc8c4c18f64d6 | 50,430 | /*
* 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.ambari.server.controller.internal;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.ClusterNotFoundException;
import org.apache.ambari.server.DuplicateResourceException;
import org.apache.ambari.server.HostNotFoundException;
import org.apache.ambari.server.ObjectNotFoundException;
import org.apache.ambari.server.ParentObjectNotFoundException;
import org.apache.ambari.server.agent.RecoveryConfigHelper;
import org.apache.ambari.server.agent.stomp.HostLevelParamsHolder;
import org.apache.ambari.server.agent.stomp.TopologyHolder;
import org.apache.ambari.server.agent.stomp.dto.HostLevelParamsCluster;
import org.apache.ambari.server.agent.stomp.dto.TopologyCluster;
import org.apache.ambari.server.agent.stomp.dto.TopologyHost;
import org.apache.ambari.server.api.services.AmbariMetaInfo;
import org.apache.ambari.server.controller.AmbariManagementController;
import org.apache.ambari.server.controller.ConfigurationRequest;
import org.apache.ambari.server.controller.HostRequest;
import org.apache.ambari.server.controller.HostResponse;
import org.apache.ambari.server.controller.MaintenanceStateHelper;
import org.apache.ambari.server.controller.RequestStatusResponse;
import org.apache.ambari.server.controller.ServiceComponentHostRequest;
import org.apache.ambari.server.controller.spi.NoSuchParentResourceException;
import org.apache.ambari.server.controller.spi.NoSuchResourceException;
import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.RequestStatus;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.ResourceAlreadyExistsException;
import org.apache.ambari.server.controller.spi.SystemException;
import org.apache.ambari.server.controller.spi.UnsupportedPropertyException;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
import org.apache.ambari.server.events.HostLevelParamsUpdateEvent;
import org.apache.ambari.server.events.TopologyUpdateEvent;
import org.apache.ambari.server.security.authorization.AuthorizationException;
import org.apache.ambari.server.security.authorization.AuthorizationHelper;
import org.apache.ambari.server.security.authorization.ResourceType;
import org.apache.ambari.server.security.authorization.RoleAuthorization;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.Config;
import org.apache.ambari.server.state.DesiredConfig;
import org.apache.ambari.server.state.Host;
import org.apache.ambari.server.state.MaintenanceState;
import org.apache.ambari.server.state.ServiceComponentHost;
import org.apache.ambari.server.state.stack.OsFamily;
import org.apache.ambari.server.topology.ClusterTopology;
import org.apache.ambari.server.topology.InvalidTopologyException;
import org.apache.ambari.server.topology.InvalidTopologyTemplateException;
import org.apache.ambari.server.topology.LogicalRequest;
import org.apache.ambari.server.topology.TopologyManager;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.google.inject.persist.Transactional;
/**
* Resource provider for host resources.
*/
public class HostResourceProvider extends AbstractControllerResourceProvider {
private static final Logger LOG = LoggerFactory.getLogger(HostResourceProvider.class);
// ----- Property ID constants ---------------------------------------------
// Hosts
public static final String RESPONSE_KEY = "Hosts";
public static final String ALL_PROPERTIES = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + "*";
public static final String CLUSTER_NAME_PROPERTY_ID = "cluster_name";
public static final String CPU_COUNT_PROPERTY_ID = "cpu_count";
public static final String DESIRED_CONFIGS_PROPERTY_ID = "desired_configs";
public static final String DISK_INFO_PROPERTY_ID = "disk_info";
public static final String HOST_HEALTH_REPORT_PROPERTY_ID = "host_health_report";
public static final String HOST_NAME_PROPERTY_ID = "host_name";
public static final String HOST_STATUS_PROPERTY_ID = "host_status";
public static final String IP_PROPERTY_ID = "ip";
public static final String LAST_AGENT_ENV_PROPERTY_ID = "last_agent_env";
public static final String LAST_HEARTBEAT_TIME_PROPERTY_ID = "last_heartbeat_time";
public static final String LAST_REGISTRATION_TIME_PROPERTY_ID = "last_registration_time";
public static final String MAINTENANCE_STATE_PROPERTY_ID = "maintenance_state";
public static final String OS_ARCH_PROPERTY_ID = "os_arch";
public static final String OS_FAMILY_PROPERTY_ID = "os_family";
public static final String OS_TYPE_PROPERTY_ID = "os_type";
public static final String PHYSICAL_CPU_COUNT_PROPERTY_ID = "ph_cpu_count";
public static final String PUBLIC_NAME_PROPERTY_ID = "public_host_name";
public static final String RACK_INFO_PROPERTY_ID = "rack_info";
public static final String RECOVERY_REPORT_PROPERTY_ID = "recovery_report";
public static final String RECOVERY_SUMMARY_PROPERTY_ID = "recovery_summary";
public static final String STATE_PROPERTY_ID = "host_state";
public static final String TOTAL_MEM_PROPERTY_ID = "total_mem";
public static final String ATTRIBUTES_PROPERTY_ID = "attributes";
public static final String HOST_CLUSTER_NAME_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + CLUSTER_NAME_PROPERTY_ID;
public static final String HOST_CPU_COUNT_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + CPU_COUNT_PROPERTY_ID;
public static final String HOST_DESIRED_CONFIGS_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + DESIRED_CONFIGS_PROPERTY_ID;
public static final String HOST_DISK_INFO_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + DISK_INFO_PROPERTY_ID;
public static final String HOST_HOST_HEALTH_REPORT_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + HOST_HEALTH_REPORT_PROPERTY_ID;
public static final String HOST_HOST_STATUS_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + HOST_STATUS_PROPERTY_ID;
public static final String HOST_IP_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + IP_PROPERTY_ID;
public static final String HOST_LAST_AGENT_ENV_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + LAST_AGENT_ENV_PROPERTY_ID;
public static final String HOST_LAST_HEARTBEAT_TIME_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + LAST_HEARTBEAT_TIME_PROPERTY_ID;
public static final String HOST_LAST_REGISTRATION_TIME_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + LAST_REGISTRATION_TIME_PROPERTY_ID;
public static final String HOST_MAINTENANCE_STATE_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + MAINTENANCE_STATE_PROPERTY_ID;
public static final String HOST_HOST_NAME_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + HOST_NAME_PROPERTY_ID;
public static final String HOST_OS_ARCH_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + OS_ARCH_PROPERTY_ID;
public static final String HOST_OS_FAMILY_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + OS_FAMILY_PROPERTY_ID;
public static final String HOST_OS_TYPE_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + OS_TYPE_PROPERTY_ID;
public static final String HOST_PHYSICAL_CPU_COUNT_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + PHYSICAL_CPU_COUNT_PROPERTY_ID;
public static final String HOST_PUBLIC_NAME_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + PUBLIC_NAME_PROPERTY_ID;
public static final String HOST_RACK_INFO_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + RACK_INFO_PROPERTY_ID;
public static final String HOST_RECOVERY_REPORT_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + RECOVERY_REPORT_PROPERTY_ID;
public static final String HOST_RECOVERY_SUMMARY_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + RECOVERY_SUMMARY_PROPERTY_ID;
public static final String HOST_STATE_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + STATE_PROPERTY_ID;
public static final String HOST_TOTAL_MEM_PROPERTY_ID = RESPONSE_KEY + PropertyHelper.EXTERNAL_PATH_SEP + TOTAL_MEM_PROPERTY_ID;
public static final String HOST_ATTRIBUTES_PROPERTY_ID = PropertyHelper.getPropertyId(RESPONSE_KEY,ATTRIBUTES_PROPERTY_ID);
public static final String BLUEPRINT_PROPERTY_ID = "blueprint";
public static final String HOST_GROUP_PROPERTY_ID = "host_group";
public static final String HOST_COUNT_PROPERTY_ID = "host_count";
public static final String HOST_PREDICATE_PROPERTY_ID = "host_predicate";
//todo use the same json structure for cluster host addition (cluster template and upscale)
/**
* The key property ids for a Host resource.
*/
public static Map<Resource.Type, String> keyPropertyIds = ImmutableMap.<Resource.Type, String>builder()
.put(Resource.Type.Host, HOST_HOST_NAME_PROPERTY_ID)
.put(Resource.Type.Cluster, HOST_CLUSTER_NAME_PROPERTY_ID)
.build();
/**
* The property ids for a Host resource.
*/
public static Set<String> propertyIds = Sets.newHashSet(
HOST_CLUSTER_NAME_PROPERTY_ID,
HOST_CPU_COUNT_PROPERTY_ID,
HOST_DESIRED_CONFIGS_PROPERTY_ID,
HOST_DISK_INFO_PROPERTY_ID,
HOST_HOST_HEALTH_REPORT_PROPERTY_ID,
HOST_HOST_STATUS_PROPERTY_ID,
HOST_IP_PROPERTY_ID,
HOST_LAST_AGENT_ENV_PROPERTY_ID,
HOST_LAST_HEARTBEAT_TIME_PROPERTY_ID,
HOST_LAST_REGISTRATION_TIME_PROPERTY_ID,
HOST_MAINTENANCE_STATE_PROPERTY_ID,
HOST_HOST_NAME_PROPERTY_ID,
HOST_OS_ARCH_PROPERTY_ID,
HOST_OS_FAMILY_PROPERTY_ID,
HOST_OS_TYPE_PROPERTY_ID,
HOST_PHYSICAL_CPU_COUNT_PROPERTY_ID,
HOST_PUBLIC_NAME_PROPERTY_ID,
HOST_RACK_INFO_PROPERTY_ID,
HOST_RECOVERY_REPORT_PROPERTY_ID,
HOST_RECOVERY_SUMMARY_PROPERTY_ID,
HOST_STATE_PROPERTY_ID,
HOST_TOTAL_MEM_PROPERTY_ID,
HOST_ATTRIBUTES_PROPERTY_ID);
@Inject
private MaintenanceStateHelper maintenanceStateHelper;
@Inject
private OsFamily osFamily;
@Inject
private static TopologyManager topologyManager;
@Inject
private TopologyHolder topologyHolder;
@Inject
private HostLevelParamsHolder hostLevelParamsHolder;
@Inject
private RecoveryConfigHelper recoveryConfigHelper;
@Inject
private AmbariMetaInfo ambariMetaInfo;
// ----- Constructors ----------------------------------------------------
/**
* Create a new resource provider for the given management controller.
*
* @param managementController the management controller
*/
@AssistedInject
HostResourceProvider(@Assisted AmbariManagementController managementController) {
super(Resource.Type.Host, propertyIds, keyPropertyIds, managementController);
Set<RoleAuthorization> authorizationsAddDelete = EnumSet.of(RoleAuthorization.HOST_ADD_DELETE_HOSTS);
setRequiredCreateAuthorizations(authorizationsAddDelete);
setRequiredDeleteAuthorizations(authorizationsAddDelete);
setRequiredGetAuthorizations(RoleAuthorization.AUTHORIZATIONS_VIEW_CLUSTER);
setRequiredUpdateAuthorizations(RoleAuthorization.AUTHORIZATIONS_UPDATE_CLUSTER);
}
// ----- ResourceProvider ------------------------------------------------
@Override
protected RequestStatus createResourcesAuthorized(final Request request)
throws SystemException,
UnsupportedPropertyException,
ResourceAlreadyExistsException,
NoSuchParentResourceException {
RequestStatusResponse createResponse = null;
if (isHostGroupRequest(request)) {
createResponse = submitHostRequests(request);
} else {
createResources(new Command<Void>() {
@Override
public Void invoke() throws AmbariException, AuthorizationException {
createHosts(request);
return null;
}
});
}
notifyCreate(Resource.Type.Host, request);
return getRequestStatus(createResponse);
}
@Override
protected Set<Resource> getResourcesAuthorized(Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
final Set<HostRequest> requests = new HashSet<>();
if (predicate == null) {
requests.add(getRequest(null));
}
else {
for (Map<String, Object> propertyMap : getPropertyMaps(predicate)) {
requests.add(getRequest(propertyMap));
}
}
Set<HostResponse> responses = getResources(new Command<Set<HostResponse>>() {
@Override
public Set<HostResponse> invoke() throws AmbariException {
return getHosts(requests);
}
});
Set<String> requestedIds = getRequestPropertyIds(request, predicate);
Set<Resource> resources = new HashSet<>();
for (HostResponse response : responses) {
Resource resource = new ResourceImpl(Resource.Type.Host);
// TODO : properly handle more than one cluster
if (response.getClusterName() != null
&& !response.getClusterName().isEmpty()) {
setResourceProperty(resource, HOST_CLUSTER_NAME_PROPERTY_ID,
response.getClusterName(), requestedIds);
}
setResourceProperty(resource, HOST_HOST_NAME_PROPERTY_ID,
response.getHostname(), requestedIds);
setResourceProperty(resource, HOST_PUBLIC_NAME_PROPERTY_ID,
response.getPublicHostName(), requestedIds);
setResourceProperty(resource, HOST_IP_PROPERTY_ID,
response.getIpv4(), requestedIds);
setResourceProperty(resource, HOST_TOTAL_MEM_PROPERTY_ID,
response.getTotalMemBytes(), requestedIds);
setResourceProperty(resource, HOST_CPU_COUNT_PROPERTY_ID,
response.getCpuCount(), requestedIds);
setResourceProperty(resource, HOST_PHYSICAL_CPU_COUNT_PROPERTY_ID,
response.getPhCpuCount(), requestedIds);
setResourceProperty(resource, HOST_OS_ARCH_PROPERTY_ID,
response.getOsArch(), requestedIds);
setResourceProperty(resource, HOST_OS_TYPE_PROPERTY_ID,
response.getOsType(), requestedIds);
setResourceProperty(resource, HOST_OS_FAMILY_PROPERTY_ID,
response.getOsFamily(), requestedIds);
setResourceProperty(resource, HOST_RACK_INFO_PROPERTY_ID,
response.getRackInfo(), requestedIds);
setResourceProperty(resource, HOST_LAST_HEARTBEAT_TIME_PROPERTY_ID,
response.getLastHeartbeatTime(), requestedIds);
setResourceProperty(resource, HOST_LAST_AGENT_ENV_PROPERTY_ID,
response.getLastAgentEnv(), requestedIds);
setResourceProperty(resource, HOST_LAST_REGISTRATION_TIME_PROPERTY_ID,
response.getLastRegistrationTime(), requestedIds);
setResourceProperty(resource, HOST_HOST_STATUS_PROPERTY_ID,
response.getStatus(),requestedIds);
setResourceProperty(resource, HOST_HOST_HEALTH_REPORT_PROPERTY_ID,
response.getHealthReport(), requestedIds);
setResourceProperty(resource, HOST_RECOVERY_REPORT_PROPERTY_ID,
response.getRecoveryReport(), requestedIds);
setResourceProperty(resource, HOST_RECOVERY_SUMMARY_PROPERTY_ID,
response.getRecoverySummary(), requestedIds);
setResourceProperty(resource, HOST_DISK_INFO_PROPERTY_ID,
response.getDisksInfo(), requestedIds);
setResourceProperty(resource, HOST_STATE_PROPERTY_ID,
response.getHostState(), requestedIds);
setResourceProperty(resource, HOST_DESIRED_CONFIGS_PROPERTY_ID,
response.getDesiredHostConfigs(), requestedIds);
// only when a cluster request
if (null != response.getMaintenanceState()) {
setResourceProperty(resource, HOST_MAINTENANCE_STATE_PROPERTY_ID,
response.getMaintenanceState(), requestedIds);
}
resources.add(resource);
}
return resources;
}
@Override
protected RequestStatus updateResourcesAuthorized(final Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
final Set<HostRequest> requests = new HashSet<>();
for (Map<String, Object> propertyMap : getPropertyMaps(request.getProperties().iterator().next(), predicate)) {
requests.add(getRequest(propertyMap));
}
modifyResources(new Command<Void>() {
@Override
public Void invoke() throws AmbariException, AuthorizationException {
updateHosts(requests);
return null;
}
});
notifyUpdate(Resource.Type.Host, request, predicate);
return getRequestStatus(null);
}
@Override
protected RequestStatus deleteResourcesAuthorized(final Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
final Set<HostRequest> requests = new HashSet<>();
Map<String, String> requestInfoProperties = request.getRequestInfoProperties();
for (Map<String, Object> propertyMap : getPropertyMaps(predicate)) {
requests.add(getRequest(propertyMap));
}
DeleteStatusMetaData deleteStatusMetaData = modifyResources(new Command<DeleteStatusMetaData>() {
@Override
public DeleteStatusMetaData invoke() throws AmbariException {
return deleteHosts(requests, request.isDryRunRequest());
}
});
if (!request.isDryRunRequest()) {
notifyDelete(Resource.Type.Host, predicate);
}
return getRequestStatus(null, null, deleteStatusMetaData);
}
@Override
public Set<String> checkPropertyIds(Set<String> propertyIds) {
Set<String> baseUnsupported = super.checkPropertyIds(propertyIds);
baseUnsupported.remove(BLUEPRINT_PROPERTY_ID);
baseUnsupported.remove(HOST_GROUP_PROPERTY_ID);
baseUnsupported.remove(HOST_NAME_PROPERTY_ID);
baseUnsupported.remove(HOST_COUNT_PROPERTY_ID);
baseUnsupported.remove(HOST_PREDICATE_PROPERTY_ID);
baseUnsupported.remove(RACK_INFO_PROPERTY_ID);
return checkConfigPropertyIds(baseUnsupported, "Hosts");
}
// ----- AbstractResourceProvider ------------------------------------------
@Override
protected Set<String> getPKPropertyIds() {
return new HashSet<>(keyPropertyIds.values());
}
// ----- utility methods ---------------------------------------------------
/**
* Determine if a request is a high level "add hosts" call or a simple lower level request
* to add a host resources.
*
* @param request current request
* @return true if this is a high level "add hosts" request;
* false if it is a simple create host resources request
*/
private boolean isHostGroupRequest(Request request) {
boolean isHostGroupRequest = false;
Set<Map<String, Object>> properties = request.getProperties();
if (properties != null && ! properties.isEmpty()) {
//todo: for now, either all or none of the hosts need to specify a hg. Unable to mix.
String hgName = (String) properties.iterator().next().get(HOST_GROUP_PROPERTY_ID);
isHostGroupRequest = hgName != null && ! hgName.isEmpty();
}
return isHostGroupRequest;
}
/**
* Get a host request object from a map of property values.
*
* @param properties the predicate
*
* @return the component request object
*/
private HostRequest getRequest(Map<String, Object> properties) {
if (properties == null) {
return new HostRequest(null, null);
}
HostRequest hostRequest = new HostRequest(
getHostNameFromProperties(properties),
(String) properties.get(HOST_CLUSTER_NAME_PROPERTY_ID)
);
hostRequest.setPublicHostName((String) properties.get(HOST_PUBLIC_NAME_PROPERTY_ID));
String rackInfo = (String) ((null != properties.get(HOST_RACK_INFO_PROPERTY_ID))? properties.get(HOST_RACK_INFO_PROPERTY_ID):
properties.get(RACK_INFO_PROPERTY_ID));
hostRequest.setRackInfo(rackInfo);
hostRequest.setBlueprintName((String) properties.get(BLUEPRINT_PROPERTY_ID));
hostRequest.setHostGroupName((String) properties.get(HOST_GROUP_PROPERTY_ID));
Object o = properties.get(HOST_MAINTENANCE_STATE_PROPERTY_ID);
if (null != o) {
hostRequest.setMaintenanceState(o.toString());
}
List<ConfigurationRequest> cr = getConfigurationRequests("Hosts", properties);
hostRequest.setDesiredConfigs(cr);
return hostRequest;
}
/**
* Accepts a request with registered hosts and if the request contains a cluster name then will map all of the
* hosts onto that cluster.
* @param request Request that must contain registered hosts, and optionally a cluster.
*/
public synchronized void createHosts(Request request)
throws AmbariException, AuthorizationException {
Set<Map<String, Object>> propertySet = request.getProperties();
if (propertySet == null || propertySet.isEmpty()) {
LOG.warn("Received a create host request with no associated property sets");
return;
}
AmbariManagementController controller = getManagementController();
Clusters clusters = controller.getClusters();
Set<String> duplicates = new HashSet<>();
Set<String> unknowns = new HashSet<>();
Set<String> allHosts = new HashSet<>();
Set<HostRequest> hostRequests = new HashSet<>();
for (Map<String, Object> propertyMap : propertySet) {
HostRequest hostRequest = getRequest(propertyMap);
hostRequests.add(hostRequest);
if (! propertyMap.containsKey(HOST_GROUP_PROPERTY_ID)) {
createHostResource(clusters, duplicates, unknowns, allHosts, hostRequest);
}
}
if (!duplicates.isEmpty()) {
StringBuilder names = new StringBuilder();
boolean first = true;
for (String hName : duplicates) {
if (!first) {
names.append(",");
}
first = false;
names.append(hName);
}
throw new IllegalArgumentException("Invalid request contains"
+ " duplicate hostnames"
+ ", hostnames=" + names);
}
if (!unknowns.isEmpty()) {
StringBuilder names = new StringBuilder();
boolean first = true;
for (String hName : unknowns) {
if (!first) {
names.append(",");
}
first = false;
names.append(hName);
}
throw new IllegalArgumentException("Attempted to add unknown hosts to a cluster. " +
"These hosts have not been registered with the server: " + names);
}
Map<String, Set<String>> hostClustersMap = new HashMap<>();
Map<String, Map<String, String>> hostAttributes = new HashMap<>();
Set<String> allClusterSet = new HashSet<>();
TreeMap<String, TopologyCluster> addedTopologies = new TreeMap<>();
List<HostLevelParamsUpdateEvent> hostLevelParamsUpdateEvents = new ArrayList<>();
for (HostRequest hostRequest : hostRequests) {
if (hostRequest.getHostname() != null &&
!hostRequest.getHostname().isEmpty() &&
hostRequest.getClusterName() != null &&
!hostRequest.getClusterName().isEmpty()){
Set<String> clusterSet = new HashSet<>();
clusterSet.add(hostRequest.getClusterName());
allClusterSet.add(hostRequest.getClusterName());
hostClustersMap.put(hostRequest.getHostname(), clusterSet);
Cluster cl = clusters.getCluster(hostRequest.getClusterName());
String clusterId = Long.toString(cl.getClusterId());
if (!addedTopologies.containsKey(clusterId)) {
addedTopologies.put(clusterId, new TopologyCluster());
}
Host addedHost = clusters.getHost(hostRequest.getHostname());
addedTopologies.get(clusterId).addTopologyHost(new TopologyHost(addedHost.getHostId(),
addedHost.getHostName(),
addedHost.getRackInfo(),
addedHost.getIPv4()));
HostLevelParamsUpdateEvent hostLevelParamsUpdateEvent = new HostLevelParamsUpdateEvent(clusterId, new HostLevelParamsCluster(
getManagementController().retrieveHostRepositories(cl, addedHost),
recoveryConfigHelper.getRecoveryConfig(cl.getClusterName(),
addedHost.getHostName())
));
hostLevelParamsUpdateEvent.setHostId(addedHost.getHostId());
hostLevelParamsUpdateEvents.add(hostLevelParamsUpdateEvent);
}
}
clusters.updateHostWithClusterAndAttributes(hostClustersMap, hostAttributes);
// TODO add rack change to topology update
updateHostRackInfoIfChanged(clusters, hostRequests);
for (HostLevelParamsUpdateEvent hostLevelParamsUpdateEvent : hostLevelParamsUpdateEvents) {
hostLevelParamsHolder.updateData(hostLevelParamsUpdateEvent);
}
TopologyUpdateEvent topologyUpdateEvent =
new TopologyUpdateEvent(addedTopologies, TopologyUpdateEvent.EventType.UPDATE);
topologyHolder.updateData(topologyUpdateEvent);
}
/**
* Iterates through the provided host request and checks if there is rack info provided.
* If the rack info differs from the rack info of the host than updates it with the value from
* the host request.
* @param clusters
* @param hostRequests
* @throws AmbariException
* @throws AuthorizationException
*/
private void updateHostRackInfoIfChanged(Clusters clusters, Set<HostRequest> hostRequests)
throws AmbariException, AuthorizationException {
HashSet<String> rackChangeAffectedClusters = new HashSet<>();
for (HostRequest hostRequest : hostRequests) {
String clusterName = hostRequest.getClusterName();
if (StringUtils.isNotBlank(clusterName)) {
Cluster cluster = clusters.getCluster(clusterName);
Host host = clusters.getHost(hostRequest.getHostname());
if (updateHostRackInfoIfChanged(cluster, host, hostRequest))
rackChangeAffectedClusters.add(clusterName);
}
}
// TODO rack change topology update
for (String clusterName: rackChangeAffectedClusters) {
getManagementController().registerRackChange(clusterName);
}
}
/**
* If the rack info provided in the request differs from the rack info of the host
* update the rack info of the host with the value from the host request
*
* @param cluster The cluster to check user privileges against. User is required
* to have {@link RoleAuthorization#HOST_ADD_DELETE_HOSTS} rights on the cluster.
* @param host The host of which rack information is to be updated
* @param hostRequest
* @return true is host was updated otherwise false
* @throws AmbariException
* @throws AuthorizationException
*/
private boolean updateHostRackInfoIfChanged(Cluster cluster, Host host, HostRequest hostRequest)
throws AmbariException, AuthorizationException {
Long resourceId = cluster.getResourceId();
String hostRackInfo = host.getRackInfo();
String requestRackInfo = hostRequest.getRackInfo();
boolean rackChange = requestRackInfo != null && !requestRackInfo.equals(hostRackInfo);
if (rackChange) {
if(!AuthorizationHelper.isAuthorized(ResourceType.CLUSTER, resourceId, RoleAuthorization.HOST_ADD_DELETE_HOSTS)) {
throw new AuthorizationException("The authenticated user is not authorized to update host rack information");
}
//TODO topology update
host.setRackInfo(requestRackInfo);
}
return rackChange;
}
private void createHostResource(Clusters clusters, Set<String> duplicates,
Set<String> unknowns, Set<String> allHosts,
HostRequest request)
throws AmbariException {
if (request.getHostname() == null
|| request.getHostname().isEmpty()) {
throw new IllegalArgumentException("Invalid arguments, hostname"
+ " cannot be null");
}
if (LOG.isDebugEnabled()) {
LOG.debug("Received a createHost request, hostname={}, request={}", request.getHostname(), request);
}
if (allHosts.contains(request.getHostname())) {
// throw dup error later
duplicates.add(request.getHostname());
return;
}
allHosts.add(request.getHostname());
try {
// ensure host is registered
clusters.getHost(request.getHostname());
}
catch (HostNotFoundException e) {
unknowns.add(request.getHostname());
return;
}
if (request.getClusterName() != null) {
try {
// validate that cluster_name is valid
clusters.getCluster(request.getClusterName());
} catch (ClusterNotFoundException e) {
throw new ParentObjectNotFoundException("Attempted to add a host to a cluster which doesn't exist: "
+ " clusterName=" + request.getClusterName());
}
}
}
public RequestStatusResponse install(final String cluster, final String hostname, Collection<String> skipInstallForComponents, Collection<String> dontSkipInstallForComponents, final boolean skipFailure)
throws ResourceAlreadyExistsException,
SystemException,
NoSuchParentResourceException,
UnsupportedPropertyException {
return ((HostComponentResourceProvider) getResourceProvider(Resource.Type.HostComponent)).
install(cluster, hostname, skipInstallForComponents, dontSkipInstallForComponents, skipFailure);
}
public RequestStatusResponse start(final String cluster, final String hostname)
throws ResourceAlreadyExistsException,
SystemException,
NoSuchParentResourceException,
UnsupportedPropertyException {
return ((HostComponentResourceProvider) getResourceProvider(Resource.Type.HostComponent)).
start(cluster, hostname);
}
protected Set<HostResponse> getHosts(Set<HostRequest> requests) throws AmbariException {
Set<HostResponse> response = new HashSet<>();
AmbariManagementController controller = getManagementController();
for (HostRequest request : requests) {
try {
response.addAll(getHosts(controller, request, osFamily));
} catch (HostNotFoundException e) {
if (requests.size() == 1) {
// only throw exception if 1 request.
// there will be > 1 request in case of OR predicate
throw e;
}
}
}
return response;
}
/**
* @param osFamily provides OS to OS family lookup; may be null if OS family is ignored anyway (eg. for liveness check)
*/
protected static Set<HostResponse> getHosts(AmbariManagementController controller, HostRequest request, OsFamily osFamily)
throws AmbariException {
//TODO/FIXME host can only belong to a single cluster so get host directly from Cluster
//TODO/FIXME what is the requirement for filtering on host attributes?
List<Host> hosts;
Set<HostResponse> response = new HashSet<>();
Cluster cluster = null;
Clusters clusters = controller.getClusters();
String clusterName = request.getClusterName();
String hostName = request.getHostname();
if (clusterName != null) {
//validate that cluster exists, throws exception if it doesn't.
try {
cluster = clusters.getCluster(clusterName);
} catch (ObjectNotFoundException e) {
throw new ParentObjectNotFoundException("Parent Cluster resource doesn't exist", e);
}
}
if (hostName == null) {
hosts = clusters.getHosts();
} else {
hosts = new ArrayList<>();
try {
hosts.add(clusters.getHost(request.getHostname()));
} catch (HostNotFoundException e) {
// add cluster name
throw new HostNotFoundException(clusterName, hostName);
}
}
// retrieve the cluster desired configs once instead of per host
Map<String, DesiredConfig> desiredConfigs = null;
if (null != cluster) {
desiredConfigs = cluster.getDesiredConfigs();
}
for (Host h : hosts) {
if (clusterName != null) {
if (clusters.getClustersForHost(h.getHostName()).contains(cluster)) {
HostResponse r = h.convertToResponse();
r.setClusterName(clusterName);
r.setDesiredHostConfigs(h.getDesiredHostConfigs(cluster, desiredConfigs));
r.setMaintenanceState(h.getMaintenanceState(cluster.getClusterId()));
if (osFamily != null) {
String hostOsFamily = osFamily.find(r.getOsType());
if (hostOsFamily == null) {
LOG.error("Can not find host OS family. For OS type = '{}' and host name = '{}'", r.getOsType(), r.getHostname());
}
r.setOsFamily(hostOsFamily);
}
response.add(r);
} else if (hostName != null) {
throw new HostNotFoundException(clusterName, hostName);
}
} else {
HostResponse r = h.convertToResponse();
Set<Cluster> clustersForHost = clusters.getClustersForHost(h.getHostName());
//todo: host can only belong to a single cluster
if (clustersForHost != null && clustersForHost.size() != 0) {
Cluster clusterForHost = clustersForHost.iterator().next();
r.setClusterName(clusterForHost.getClusterName());
r.setDesiredHostConfigs(h.getDesiredHostConfigs(clusterForHost, null));
r.setMaintenanceState(h.getMaintenanceState(clusterForHost.getClusterId()));
}
response.add(r);
}
}
return response;
}
protected synchronized void updateHosts(Set<HostRequest> requests) throws AmbariException, AuthorizationException {
if (requests.isEmpty()) {
LOG.warn("Received an empty requests set");
return;
}
AmbariManagementController controller = getManagementController();
Clusters clusters = controller.getClusters();
for (HostRequest request : requests) {
if (request.getHostname() == null || request.getHostname().isEmpty()) {
throw new IllegalArgumentException("Invalid arguments, hostname should be provided");
}
}
TreeMap<String, TopologyCluster> topologyUpdates = new TreeMap<>();
for (HostRequest request : requests) {
if (LOG.isDebugEnabled()) {
LOG.debug("Received an updateHost request, hostname={}, request={}", request.getHostname(), request);
}
TopologyHost topologyHost = new TopologyHost();
Host host = clusters.getHost(request.getHostname());
String clusterName = request.getClusterName();
Cluster cluster = clusters.getCluster(clusterName);
Long clusterId = cluster.getClusterId();
Long resourceId = cluster.getResourceId();
topologyHost.setHostId(host.getHostId());
try {
// The below method call throws an exception when trying to create a duplicate mapping in the clusterhostmapping
// table. This is done to detect duplicates during host create. In order to be robust, handle these gracefully.
clusters.mapAndPublishHostsToCluster(new HashSet<>(Arrays.asList(request.getHostname())), clusterName);
} catch (DuplicateResourceException e) {
// do nothing
}
boolean rackChange = updateHostRackInfoIfChanged(cluster, host, request);
if (null != request.getPublicHostName()) {
if(!AuthorizationHelper.isAuthorized(ResourceType.CLUSTER, resourceId, RoleAuthorization.HOST_ADD_DELETE_HOSTS)) {
throw new AuthorizationException("The authenticated user is not authorized to update host attributes");
}
host.setPublicHostName(request.getPublicHostName());
topologyHost.setHostName(request.getPublicHostName());
}
if (null != clusterName && null != request.getMaintenanceState()) {
if(!AuthorizationHelper.isAuthorized(ResourceType.CLUSTER, resourceId, RoleAuthorization.HOST_TOGGLE_MAINTENANCE)) {
throw new AuthorizationException("The authenticated user is not authorized to update host maintenance state");
}
MaintenanceState newState = MaintenanceState.valueOf(request.getMaintenanceState());
MaintenanceState oldState = host.getMaintenanceState(clusterId);
if (!newState.equals(oldState)) {
if (newState.equals(MaintenanceState.IMPLIED_FROM_HOST)
|| newState.equals(MaintenanceState.IMPLIED_FROM_SERVICE)) {
throw new IllegalArgumentException("Invalid arguments, can only set " +
"maintenance state to one of " + EnumSet.of(MaintenanceState.OFF, MaintenanceState.ON));
} else {
host.setMaintenanceState(clusterId, newState);
}
}
}
// Create configurations
if (null != clusterName && null != request.getDesiredConfigs()) {
if (clusters.getHostsForCluster(clusterName).containsKey(host.getHostName())) {
for (ConfigurationRequest cr : request.getDesiredConfigs()) {
if (null != cr.getProperties() && cr.getProperties().size() > 0) {
LOG.info(MessageFormat.format("Applying configuration with tag ''{0}'' to host ''{1}'' in cluster ''{2}''",
cr.getVersionTag(),
request.getHostname(),
clusterName));
cr.setClusterName(cluster.getClusterName());
controller.createConfiguration(cr);
}
Config baseConfig = cluster.getConfig(cr.getType(), cr.getVersionTag());
if (null != baseConfig) {
String authName = controller.getAuthName();
DesiredConfig oldConfig = host.getDesiredConfigs(clusterId).get(cr.getType());
if (host.addDesiredConfig(clusterId, cr.isSelected(), authName, baseConfig)) {
Logger logger = LoggerFactory.getLogger("configchange");
logger.info("(configchange) cluster '" + cluster.getClusterName() + "', "
+ "host '" + host.getHostName() + "' "
+ "changed by: '" + authName + "'; "
+ "type='" + baseConfig.getType() + "' "
+ "version='" + baseConfig.getVersion() + "'"
+ "tag='" + baseConfig.getTag() + "'"
+ (null == oldConfig ? "" : ", from='" + oldConfig.getTag() + "'"));
}
}
}
}
}
if (StringUtils.isNotBlank(clusterName) && rackChange) {
// Authorization check for this update was performed before we got to this point.
controller.registerRackChange(clusterName);
}
if (!topologyUpdates.containsKey(clusterId.toString())) {
topologyUpdates.put(clusterId.toString(), new TopologyCluster());
}
topologyUpdates.get(clusterId.toString()).addTopologyHost(topologyHost);
TopologyUpdateEvent topologyUpdateEvent = new TopologyUpdateEvent(topologyUpdates,
TopologyUpdateEvent.EventType.UPDATE);
topologyHolder.updateData(topologyUpdateEvent);
//todo: if attempt was made to update a property other than those
//todo: that are allowed above, should throw exception
}
}
@Transactional
protected DeleteStatusMetaData deleteHosts(Set<HostRequest> requests, boolean dryRun)
throws AmbariException {
AmbariManagementController controller = getManagementController();
Clusters clusters = controller.getClusters();
DeleteStatusMetaData deleteStatusMetaData = new DeleteStatusMetaData();
List<HostRequest> okToRemove = new ArrayList<>();
for (HostRequest hostRequest : requests) {
String hostName = hostRequest.getHostname();
if (null == hostName) {
continue;
}
try {
validateHostInDeleteFriendlyState(hostRequest, clusters);
okToRemove.add(hostRequest);
} catch (Exception ex) {
deleteStatusMetaData.addException(hostName, ex);
}
}
//If dry run, don't delete. just assume it can be successfully deleted.
if (dryRun) {
for (HostRequest request : okToRemove) {
deleteStatusMetaData.addDeletedKey(request.getHostname());
}
} else {
processDeleteHostRequests(okToRemove, clusters, deleteStatusMetaData);
}
//Do not break behavior for existing clients where delete request contains only 1 host.
//Response for these requests will have empty body with appropriate error code.
//dryRun is a new feature so its ok to unify the behavior
if (!dryRun) {
if (deleteStatusMetaData.getDeletedKeys().size() + deleteStatusMetaData.getExceptionForKeys().size() == 1) {
if (deleteStatusMetaData.getDeletedKeys().size() == 1) {
return null;
}
for (Map.Entry<String, Exception> entry : deleteStatusMetaData.getExceptionForKeys().entrySet()) {
Exception ex = entry.getValue();
if (ex instanceof AmbariException) {
throw (AmbariException) ex;
} else {
throw new AmbariException(ex.getMessage(), ex);
}
}
}
}
return deleteStatusMetaData;
}
private void processDeleteHostRequests(List<HostRequest> requests, Clusters clusters, DeleteStatusMetaData deleteStatusMetaData) throws AmbariException {
Set<String> hostsClusters = new HashSet<>();
Set<String> hostNames = new HashSet<>();
Set<Cluster> allClustersWithHosts = new HashSet<>();
TreeMap<String, TopologyCluster> topologyUpdates = new TreeMap<>();
for (HostRequest hostRequest : requests) {
// Assume the user also wants to delete it entirely, including all clusters.
String hostname = hostRequest.getHostname();
Long hostId = clusters.getHost(hostname).getHostId();
hostNames.add(hostname);
if (hostRequest.getClusterName() != null) {
hostsClusters.add(hostRequest.getClusterName());
}
LOG.info("Received Delete request for host {} from cluster {}.", hostname, hostRequest.getClusterName());
// delete all host components
Set<ServiceComponentHostRequest> schrs = new HashSet<>();
for (Cluster cluster : clusters.getClustersForHost(hostname)) {
List<ServiceComponentHost> list = cluster.getServiceComponentHosts(hostname);
for (ServiceComponentHost sch : list) {
ServiceComponentHostRequest schr = new ServiceComponentHostRequest(cluster.getClusterName(),
sch.getServiceName(),
sch.getServiceComponentName(),
sch.getHostName(),
null);
schrs.add(schr);
}
}
DeleteStatusMetaData componentDeleteStatus = null;
if (schrs.size() > 0) {
try {
componentDeleteStatus = getManagementController().deleteHostComponents(schrs);
} catch (Exception ex) {
deleteStatusMetaData.addException(hostname, ex);
}
}
if (componentDeleteStatus != null) {
for (String key : componentDeleteStatus.getDeletedKeys()) {
deleteStatusMetaData.addDeletedKey(key);
}
for (String key : componentDeleteStatus.getExceptionForKeys().keySet()) {
deleteStatusMetaData.addException(key, componentDeleteStatus.getExceptionForKeys().get(key));
}
}
if (hostRequest.getClusterName() != null) {
hostsClusters.add(hostRequest.getClusterName());
}
try {
Set<Cluster> hostClusters = new HashSet<>(clusters.getClustersForHost(hostname));
clusters.deleteHost(hostname);
for (Cluster cluster : hostClusters) {
String clusterId = Long.toString(cluster.getClusterId());
if (!topologyUpdates.containsKey(clusterId)) {
topologyUpdates.put(clusterId, new TopologyCluster());
}
topologyUpdates.get(clusterId).getTopologyHosts().add(new TopologyHost(hostId, hostname));
}
deleteStatusMetaData.addDeletedKey(hostname);
} catch (Exception ex) {
deleteStatusMetaData.addException(hostname, ex);
}
removeHostFromClusterTopology(clusters, hostRequest);
for (LogicalRequest logicalRequest: topologyManager.getRequests(Collections.emptyList())) {
logicalRequest.removeHostRequestByHostName(hostname);
}
}
clusters.publishHostsDeletion(allClustersWithHosts, hostNames);
TopologyUpdateEvent topologyUpdateEvent = new TopologyUpdateEvent(topologyUpdates,
TopologyUpdateEvent.EventType.DELETE);
topologyHolder.updateData(topologyUpdateEvent);
}
private void validateHostInDeleteFriendlyState(HostRequest hostRequest, Clusters clusters) throws AmbariException {
Set<String> clusterNamesForHost = new HashSet<>();
String hostName = hostRequest.getHostname();
if (null != hostRequest.getClusterName()) {
clusterNamesForHost.add(hostRequest.getClusterName());
} else {
Set<Cluster> clustersForHost = clusters.getClustersForHost(hostRequest.getHostname());
if (null != clustersForHost) {
for (Cluster c : clustersForHost) {
clusterNamesForHost.add(c.getClusterName());
}
}
}
for (String clusterName : clusterNamesForHost) {
Cluster cluster = clusters.getCluster(clusterName);
List<ServiceComponentHost> list = cluster.getServiceComponentHosts(hostName);
if (!list.isEmpty()) {
List<String> componentsStarted = new ArrayList<>();
for (ServiceComponentHost sch : list) {
if (!sch.canBeRemoved()) {
componentsStarted.add(sch.getServiceComponentName());
}
}
// error if components are running
if (!componentsStarted.isEmpty()) {
StringBuilder reason = new StringBuilder("Cannot remove host ")
.append(hostName)
.append(" from ")
.append(hostRequest.getClusterName())
.append(
". The following roles exist, and these components are not in the removable state: ");
reason.append(StringUtils.join(componentsStarted, ", "));
throw new AmbariException(reason.toString());
}
}
}
}
/**
* Removes hostname from the stateful cluster topology
*/
private void removeHostFromClusterTopology(Clusters clusters, HostRequest hostRequest) throws AmbariException{
if (hostRequest.getClusterName() == null) {
for (Cluster c : clusters.getClusters().values()) {
removeHostFromClusterTopology(c.getClusterId(), hostRequest.getHostname());
}
} else {
long clusterId = clusters.getCluster(hostRequest.getClusterName()).getClusterId();
removeHostFromClusterTopology(clusterId, hostRequest.getHostname());
}
}
private void removeHostFromClusterTopology(long clusterId, String hostname) {
ClusterTopology clusterTopology = topologyManager.getClusterTopology(clusterId);
if(clusterTopology != null) {
clusterTopology.removeHost(hostname);
}
}
/**
* Obtain the hostname from the request properties. The hostname property name may differ
* depending on the request type. For the low level host resource creation calls, it is always
* "Hosts/host_name". For multi host "add host from hostgroup", the hostname property is a top level
* property "host_name".
*
* @param properties request properties
*
* @return the host name for the host request
*/
public static String getHostNameFromProperties(Map<String, Object> properties) {
String hostname = (String) properties.get(HOST_HOST_NAME_PROPERTY_ID);
return hostname != null ? hostname :
(String) properties.get(HOST_NAME_PROPERTY_ID);
}
//todo: for api/v1/hosts we also end up here so we need to ensure proper 400 response
//todo: since a user shouldn't be posing to that endpoint
private RequestStatusResponse submitHostRequests(Request request) throws SystemException {
ScaleClusterRequest requestRequest;
try {
requestRequest = new ScaleClusterRequest(request.getProperties());
} catch (InvalidTopologyTemplateException e) {
throw new IllegalArgumentException("Invalid Add Hosts Template: " + e, e);
}
try {
return topologyManager.scaleHosts(requestRequest);
} catch (InvalidTopologyException e) {
throw new IllegalArgumentException("Topology validation failed: " + e, e);
} catch (AmbariException e) {
//todo: handle non-system exceptions
e.printStackTrace();
//todo: for now just throw SystemException
throw new SystemException("Unable to add hosts", e);
}
}
//todo: proper static injection of topology manager
public static void setTopologyManager(TopologyManager topologyManager) {
HostResourceProvider.topologyManager = topologyManager;
}
}
| 42.737288 | 204 | 0.712512 |
f6d9dcf1ee68ac5aaf5747956a2183c2c1d98b84 | 1,588 | /*
* Copyright 2018 EPAM Systems, 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.syndicate.deployment.success.syndicate;
import com.syndicate.deployment.annotations.environment.EnvironmentVariable;
import com.syndicate.deployment.annotations.events.SnsEventSource;
import com.syndicate.deployment.annotations.lambda.LambdaHandler;
import com.syndicate.deployment.annotations.resources.DependsOn;
import com.syndicate.deployment.model.RegionScope;
import com.syndicate.deployment.model.ResourceType;
import com.syndicate.deployment.model.TracingMode;
/**
* Created by Oleksandr Onsha on 10/30/18
*/
@LambdaHandler(tracingMode = TracingMode.Active,
lambdaName = "lambda_execute_notification",
roleName = "lr_get_notification_content")
@EnvironmentVariable(key = "name", value = "lambda_execute_notification")
@DependsOn(name = "stackAuditTopic", resourceType = ResourceType.SNS_TOPIC)
@SnsEventSource(targetTopic = "stackAuditTopic", regionScope = RegionScope.ALL)
public class SnsLambdaExecutor {
// test lambda class to be processed
}
| 41.789474 | 79 | 0.785894 |
8aa44adf8a5497e0bdeddef1e64fdc08db4c2158 | 9,314 | package net.minecraft.gametest.framework;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import it.unimi.dsi.fastutil.objects.Object2LongMap;
import it.unimi.dsi.fastutil.objects.Object2LongMap.Entry;
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectIterator;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import net.minecraft.core.BaseBlockPosition;
import net.minecraft.core.BlockPosition;
import net.minecraft.server.level.WorldServer;
import net.minecraft.world.level.block.EnumBlockRotation;
import net.minecraft.world.level.block.entity.TileEntityStructure;
import net.minecraft.world.level.levelgen.structure.StructureBoundingBox;
import net.minecraft.world.phys.AxisAlignedBB;
public class GameTestHarnessInfo {
private final GameTestHarnessTestFunction testFunction;
@Nullable
private BlockPosition structureBlockPos;
private final WorldServer level;
private final Collection<GameTestHarnessListener> listeners = Lists.newArrayList();
private final int timeoutTicks;
private final Collection<GameTestHarnessSequence> sequences = Lists.newCopyOnWriteArrayList();
private final Object2LongMap<Runnable> runAtTickTimeMap = new Object2LongOpenHashMap();
private long startTick;
private long tickCount;
private boolean started;
private final Stopwatch timer = Stopwatch.createUnstarted();
private boolean done;
private final EnumBlockRotation rotation;
@Nullable
private Throwable error;
@Nullable
private TileEntityStructure structureBlockEntity;
public GameTestHarnessInfo(GameTestHarnessTestFunction gametestharnesstestfunction, EnumBlockRotation enumblockrotation, WorldServer worldserver) {
this.testFunction = gametestharnesstestfunction;
this.level = worldserver;
this.timeoutTicks = gametestharnesstestfunction.getMaxTicks();
this.rotation = gametestharnesstestfunction.getRotation().getRotated(enumblockrotation);
}
void setStructureBlockPos(BlockPosition blockposition) {
this.structureBlockPos = blockposition;
}
void startExecution() {
this.startTick = this.level.getGameTime() + 1L + this.testFunction.getSetupTicks();
this.timer.start();
}
public void tick() {
if (!this.isDone()) {
this.tickInternal();
if (this.isDone()) {
if (this.error != null) {
this.listeners.forEach((gametestharnesslistener) -> {
gametestharnesslistener.testFailed(this);
});
} else {
this.listeners.forEach((gametestharnesslistener) -> {
gametestharnesslistener.testPassed(this);
});
}
}
}
}
private void tickInternal() {
this.tickCount = this.level.getGameTime() - this.startTick;
if (this.tickCount >= 0L) {
if (this.tickCount == 0L) {
this.startTest();
}
ObjectIterator objectiterator = this.runAtTickTimeMap.object2LongEntrySet().iterator();
while (objectiterator.hasNext()) {
Entry<Runnable> entry = (Entry) objectiterator.next();
if (entry.getLongValue() <= this.tickCount) {
try {
((Runnable) entry.getKey()).run();
} catch (Exception exception) {
this.fail(exception);
}
objectiterator.remove();
}
}
if (this.tickCount > (long) this.timeoutTicks) {
if (this.sequences.isEmpty()) {
this.fail(new GameTestHarnessTimeout("Didn't succeed or fail within " + this.testFunction.getMaxTicks() + " ticks"));
} else {
this.sequences.forEach((gametestharnesssequence) -> {
gametestharnesssequence.tickAndFailIfNotComplete(this.tickCount);
});
if (this.error == null) {
this.fail(new GameTestHarnessTimeout("No sequences finished"));
}
}
} else {
this.sequences.forEach((gametestharnesssequence) -> {
gametestharnesssequence.tickAndContinue(this.tickCount);
});
}
}
}
private void startTest() {
if (this.started) {
throw new IllegalStateException("Test already started");
} else {
this.started = true;
try {
this.testFunction.run(new GameTestHarnessHelper(this));
} catch (Exception exception) {
this.fail(exception);
}
}
}
public void setRunAtTickTime(long i, Runnable runnable) {
this.runAtTickTimeMap.put(runnable, i);
}
public String getTestName() {
return this.testFunction.getTestName();
}
public BlockPosition getStructureBlockPos() {
return this.structureBlockPos;
}
@Nullable
public BaseBlockPosition getStructureSize() {
TileEntityStructure tileentitystructure = this.getStructureBlockEntity();
return tileentitystructure == null ? null : tileentitystructure.getStructureSize();
}
@Nullable
public AxisAlignedBB getStructureBounds() {
TileEntityStructure tileentitystructure = this.getStructureBlockEntity();
return tileentitystructure == null ? null : GameTestHarnessStructures.getStructureBounds(tileentitystructure);
}
@Nullable
private TileEntityStructure getStructureBlockEntity() {
return (TileEntityStructure) this.level.getBlockEntity(this.structureBlockPos);
}
public WorldServer getLevel() {
return this.level;
}
public boolean hasSucceeded() {
return this.done && this.error == null;
}
public boolean hasFailed() {
return this.error != null;
}
public boolean hasStarted() {
return this.started;
}
public boolean isDone() {
return this.done;
}
public long getRunTime() {
return this.timer.elapsed(TimeUnit.MILLISECONDS);
}
private void finish() {
if (!this.done) {
this.done = true;
this.timer.stop();
}
}
public void succeed() {
if (this.error == null) {
this.finish();
}
}
public void fail(Throwable throwable) {
this.error = throwable;
this.finish();
}
@Nullable
public Throwable getError() {
return this.error;
}
public String toString() {
return this.getTestName();
}
public void addListener(GameTestHarnessListener gametestharnesslistener) {
this.listeners.add(gametestharnesslistener);
}
public void spawnStructure(BlockPosition blockposition, int i) {
this.structureBlockEntity = GameTestHarnessStructures.spawnStructure(this.getStructureName(), blockposition, this.getRotation(), i, this.level, false);
this.structureBlockPos = this.structureBlockEntity.getBlockPos();
this.structureBlockEntity.setStructureName(this.getTestName());
GameTestHarnessStructures.addCommandBlockAndButtonToStartTest(this.structureBlockPos, new BlockPosition(1, 0, -1), this.getRotation(), this.level);
this.listeners.forEach((gametestharnesslistener) -> {
gametestharnesslistener.testStructureLoaded(this);
});
}
public void clearStructure() {
if (this.structureBlockEntity == null) {
throw new IllegalStateException("Expected structure to be initialized, but it was null");
} else {
StructureBoundingBox structureboundingbox = GameTestHarnessStructures.getStructureBoundingBox(this.structureBlockEntity);
GameTestHarnessStructures.clearSpaceForStructure(structureboundingbox, this.structureBlockPos.getY(), this.level);
}
}
long getTick() {
return this.tickCount;
}
GameTestHarnessSequence createSequence() {
GameTestHarnessSequence gametestharnesssequence = new GameTestHarnessSequence(this);
this.sequences.add(gametestharnesssequence);
return gametestharnesssequence;
}
public boolean isRequired() {
return this.testFunction.isRequired();
}
public boolean isOptional() {
return !this.testFunction.isRequired();
}
public String getStructureName() {
return this.testFunction.getStructureName();
}
public EnumBlockRotation getRotation() {
return this.rotation;
}
public GameTestHarnessTestFunction getTestFunction() {
return this.testFunction;
}
public int getTimeoutTicks() {
return this.timeoutTicks;
}
public boolean isFlaky() {
return this.testFunction.isFlaky();
}
public int maxAttempts() {
return this.testFunction.getMaxAttempts();
}
public int requiredSuccesses() {
return this.testFunction.getRequiredSuccesses();
}
}
| 32.340278 | 159 | 0.64344 |
1145fba4000701771ae412620d142357f6a56478 | 2,427 | package com.algorand.algosdk.v2.client.model;
import java.util.Objects;
import com.algorand.algosdk.util.Encoder;
import com.algorand.algosdk.v2.client.common.PathResponse;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* TransactionParams contains the parameters that help a client construct a new
* transaction.
*/
public class TransactionParametersResponse extends PathResponse {
/**
* ConsensusVersion indicates the consensus protocol version
* as of LastRound.
*/
@JsonProperty("consensus-version")
public String consensusVersion;
/**
* Fee is the suggested transaction fee
* Fee is in units of micro-Algos per byte.
* Fee may fall to zero but transactions must still have a fee of
* at least MinTxnFee for the current network protocol.
*/
@JsonProperty("fee")
public Long fee;
/**
* GenesisHash is the hash of the genesis block.
*/
@JsonProperty("genesis-hash")
public void genesisHash(String base64Encoded) {
this.genesisHash = Encoder.decodeFromBase64(base64Encoded);
}
@JsonProperty("genesis-hash")
public String genesisHash() {
return Encoder.encodeToBase64(this.genesisHash);
}
public byte[] genesisHash;
/**
* GenesisID is an ID listed in the genesis block.
*/
@JsonProperty("genesis-id")
public String genesisId;
/**
* LastRound indicates the last round seen
*/
@JsonProperty("last-round")
public Long lastRound;
/**
* The minimum transaction fee (not per byte) required for the
* txn to validate for the current network protocol.
*/
@JsonProperty("min-fee")
public Long minFee;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
TransactionParametersResponse other = (TransactionParametersResponse) o;
if (!Objects.deepEquals(this.consensusVersion, other.consensusVersion)) return false;
if (!Objects.deepEquals(this.fee, other.fee)) return false;
if (!Objects.deepEquals(this.genesisHash, other.genesisHash)) return false;
if (!Objects.deepEquals(this.genesisId, other.genesisId)) return false;
if (!Objects.deepEquals(this.lastRound, other.lastRound)) return false;
if (!Objects.deepEquals(this.minFee, other.minFee)) return false;
return true;
}
}
| 30.3375 | 93 | 0.6815 |
5c0ec7bf320e1f5790a545889bd78e6f99320fdb | 1,083 | package ex1;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;
public class Main {
public static void main(String[] args) {
Jdbi jdbi = Jdbi.create("jdbc:h2:mem:test");
try (Handle handle = jdbi.open()) {
handle.execute("""
CREATE TABLE legoset (
number VARCHAR PRIMARY KEY,
year INTEGER NOT NULL,
pieces INTEGER NOT NULL
)
"""
);
handle.execute("INSERT INTO legoset VALUES ('60073', 2015, 233)");
handle.execute("INSERT INTO legoset VALUES ('75211', 2018, 519)");
handle.execute("INSERT INTO legoset VALUES ('21034', 2017, 468)");
int numOfLegoSets = handle.createQuery("SELECT COUNT(*) FROM legoset").mapTo(Integer.class).one();
System.out.println(numOfLegoSets);
int totalPieces = handle.createQuery("SELECT SUM(pieces) FROM legoset").mapTo(Integer.class).one();
System.out.println(totalPieces);
}
}
} | 37.344828 | 111 | 0.55494 |
6ba079ad32628373fa331685014c0a7063b71c22 | 4,483 | package com.vaadin.flow.component.treegrid.it;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.IntStream;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.NativeButton;
import com.vaadin.flow.component.treegrid.TreeGrid;
import com.vaadin.flow.data.provider.hierarchy.TreeData;
import com.vaadin.flow.data.provider.hierarchy.TreeDataProvider;
import com.vaadin.flow.router.Route;
@Route("vaadin-grid/treegrid-expand-all")
public class TreeGridExpandAllPage extends Div {
private TreeGrid<String> treeGrid;
private TreeDataProvider<String> inMemoryDataProvider;
public TreeGridExpandAllPage() {
TreeGrid<String> grid = new TreeGrid<>();
grid.setId("treegrid");
grid.addHierarchyColumn(String::toString).setHeader("String")
.setId("string");
add(grid);
TreeData<String> data = new TreeData<>();
Map<String, String> parentPathMap = new HashMap<>();
TreeGridHugeTreePage.addRootItems("Granddad", 1, data, parentPathMap)
.forEach(granddad -> TreeGridHugeTreePage
.addItems("Dad", 1, granddad, data, parentPathMap)
.forEach(dad -> TreeGridHugeTreePage.addItems("Son", 3,
dad, data, parentPathMap)));
TreeDataProvider<String> dataprovider = new TreeDataProvider<>(data);
grid.setDataProvider(dataprovider);
grid.expandRecursively(data.getRootItems(), 3);
NativeButton collapse = new NativeButton("Collapse All",
event -> grid.collapseRecursively(data.getRootItems(), 3));
collapse.setId("collapse");
add(collapse);
NativeButton expand = new NativeButton("Expand All",
event -> grid.expandRecursively(data.getRootItems(), 3));
expand.setId("expand");
add(expand);
NativeButton addNew = new NativeButton("Add New son", event -> {
dataprovider.getTreeData().addItem("Dad 0/0", "New son");
dataprovider.refreshAll();
event.getSource().setEnabled(false);
});
addNew.setId("add-new");
add(addNew);
// second grid
initializeDataProvider();
treeGrid = new TreeGrid<>();
treeGrid.setDataProvider(inMemoryDataProvider);
treeGrid.setWidth("100%");
treeGrid.addHierarchyColumn(String::toString).setHeader("String").setAutoWidth(true);
treeGrid.addColumn((i) -> "Second Column").setHeader("Second Column").setAutoWidth(true);
treeGrid.setId("second-grid");
treeGrid.addCollapseListener(e -> treeGrid.recalculateColumnWidths());
treeGrid.addExpandListener(e -> treeGrid.recalculateColumnWidths());
add(treeGrid);
}
private void initializeDataProvider() {
TreeData<String> data = new TreeData<>();
final Map<String, String> parentPathMap = new HashMap<>();
addRootItems("Granddad", 3, data, parentPathMap).forEach(
granddad -> addItems("Dad is very long and large", 3, granddad, data, parentPathMap)
.forEach(dad -> addItems("Son", 300, dad, data,
parentPathMap)));
inMemoryDataProvider = new TreeDataProvider<>(data);
}
static List<String> addRootItems(String name, int numberOfItems,
TreeData<String> data, Map<String, String> parentPathMap) {
return addItems(name, numberOfItems, null, data, parentPathMap);
}
static List<String> addItems(String name, int numberOfItems,
String parent, TreeData<String> data,
Map<String, String> parentPathMap) {
List<String> items = new ArrayList<>();
IntStream.range(0, numberOfItems).forEach(index -> {
String parentPath = parentPathMap.get(parent);
String thisPath = Optional.ofNullable(parentPath)
.map(path -> path + "/" + index).orElse("" + index);
String item = addItem(name, thisPath);
parentPathMap.put(item, thisPath);
data.addItem(parent, item);
items.add(item);
});
return items;
}
private static String addItem(String name, String path) {
return (name + " " + path).trim();
}
}
| 39.672566 | 100 | 0.625474 |
5f52e104e6c6868758347c4544f58cab35dc63d9 | 3,255 | /*
* Copyright 2012 Jesper Terkelsen.
*
* 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 dk.deck.resolver.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Jesper Terkelsen
*/
public class ZipUtils {
private static Log log = LogFactory.getLog(ZipUtils.class);
public ZipUtils() {
}
public List<String> listArchive(File archive){
List<String> paths = new ArrayList<String>();
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
paths.add(entry.getName());
}
zipfile.close();
} catch (Exception e) {
log.error("Error while extracting file " + archive, e);
}
return paths;
}
public void unzipArchive(File archive, File outputDir) {
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, outputDir);
}
zipfile.close();
} catch (Exception e) {
log.error("Error while extracting file " + archive, e);
}
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {
if (entry.isDirectory()) {
createDir(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists()){
createDir(outputFile.getParentFile());
}
// log.debug("Extracting: " + entry);
BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
inputStream.close();
}
}
private void createDir(File dir) {
// log.debug("Creating dir "+dir.getName());
if(!dir.mkdirs()) throw new RuntimeException("Can not create dir "+dir);
}
} | 32.55 | 103 | 0.635945 |
529b62e4f3f72a52d0510e8870c46ae07cbbfa46 | 1,690 | /**
* Copyright (c) Istituto Nazionale di Fisica Nucleare, 2014-2021.
*
* 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.italiangrid.storm.webdav.oauth;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;
@Component
public class StormJwtAuthenticationConverter
implements Converter<Jwt, AbstractAuthenticationToken> {
private final StormJwtAuthoritiesConverter converter;
@Autowired
public StormJwtAuthenticationConverter(StormJwtAuthoritiesConverter converter) {
this.converter = converter;
}
@Override
public AbstractAuthenticationToken convert(Jwt source) {
Collection<GrantedAuthority> authorities = converter.convert(source);
return new JwtAuthenticationToken(source, authorities);
}
}
| 37.555556 | 97 | 0.801183 |
4af52167c94500cc523e5c74f9688b7c27360c87 | 358 | /**
*
*/
package com.cpt1.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.cpt1.entity.User;
/**
* TODO UserMapper2
* @author suns sontion@yeah.net
* @since 2017年3月16日上午11:42:34
*/
public interface UserMapper2 {
User getUserById(int id);
@Select("select * from user")
List<User> getUserList();
}
| 15.565217 | 44 | 0.687151 |
1578907de1041da246da461a59a489766b4478b7 | 341 | package com.mcgrady.xui.linkagerecyclerview.adapter.viewholder;
import android.support.annotation.NonNull;
import android.view.View;
/**
* Created by mcgrady on 2019/5/20.
*/
public class LinkageSecondaryViewHolder extends BaseViewHolder{
public LinkageSecondaryViewHolder(@NonNull View itemView) {
super(itemView);
}
}
| 22.733333 | 63 | 0.765396 |
7015b2cf865f22c3dafa2fc66b17980ee6ac5721 | 4,636 | /*
* 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 eagle.auditlog.userprofile.common;
import org.apache.eagle.security.userprofile.UserProfileUtils;
import org.apache.eagle.common.DateTimeUtil;
import junit.framework.Assert;
import org.joda.time.Period;
import org.joda.time.Seconds;
import org.junit.Test;
import java.text.ParseException;
public class TestUserProfileUtils {
@Test
public void testJodaTimePeriod() throws ParseException {
String periodText = "PT10m";
Period period = new Period(periodText);
int seconds = period.toStandardSeconds().getSeconds();
Assert.assertEquals(600, seconds);
Assert.assertEquals(60, period.toStandardSeconds().dividedBy(10).getSeconds());
}
@Test
public void testFormatSecondsByPeriod15M() throws ParseException {
Period period = new Period("PT15m");
Seconds seconds = period.toStandardSeconds();
Assert.assertEquals(15*60,seconds.getSeconds());
long time = DateTimeUtil.humanDateToSeconds("2015-07-01 13:56:12");
long expect = DateTimeUtil.humanDateToSeconds("2015-07-01 13:45:00");
long result = UserProfileUtils.formatSecondsByPeriod(time,seconds);
Assert.assertEquals(expect,result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect,result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect,result);
}
@Test
public void testFormatSecondsByPeriod1H() throws ParseException {
Period period = new Period("PT1h");
Seconds seconds = period.toStandardSeconds();
Assert.assertEquals(60*60,seconds.getSeconds());
long time = DateTimeUtil.humanDateToSeconds("2015-07-01 13:56:12");
long expect = DateTimeUtil.humanDateToSeconds("2015-07-01 13:00:00");
long result = UserProfileUtils.formatSecondsByPeriod(time,seconds);
Assert.assertEquals(expect,result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect,result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:30:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect,result);
}
/*@Test
public void testFormatSecondsByPeriod1Min() throws ParseException {
Period period = new Period("PT1M");
Seconds seconds = period.toStandardSeconds();
Assert.assertEquals(60,seconds.getSeconds());
long time = DateTimeUtil.humanDateToSeconds("2015-07-01 13:56:15");
long expect = DateTimeUtil.humanDateToSeconds("2015-07-01 13:55:16");
long result = UserProfileUtils.formatSecondsByPeriod(time,seconds);
Assert.assertEquals(expect,result);
//time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
//expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
//result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
//Assert.assertEquals(expect,result);
//time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:30:59");
//expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
//result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
//Assert.assertEquals(expect,result);
}*/
} | 43.735849 | 87 | 0.709232 |
274cfcf4de95d7c1b50714bc801c6361b2bd4ceb | 58,764 | package com.ibm.safr.we.internal.data.pgdao;
/*
* Copyright Contributors to the GenevaERS Project. SPDX-License-Identifier: Apache-2.0 (c) Copyright IBM Corporation 2008.
*
* 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.
*/
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import com.ibm.safr.we.constants.ComponentType;
import com.ibm.safr.we.constants.EnvRole;
import com.ibm.safr.we.constants.SortType;
import com.ibm.safr.we.data.ConnectionParameters;
import com.ibm.safr.we.data.DAOException;
import com.ibm.safr.we.data.DAOFactoryHolder;
import com.ibm.safr.we.data.DataUtilities;
import com.ibm.safr.we.data.UserSessionParameters;
import com.ibm.safr.we.data.dao.GroupDAO;
import com.ibm.safr.we.data.transfer.GroupComponentAssociationTransfer;
import com.ibm.safr.we.data.transfer.GroupEnvironmentAssociationTransfer;
import com.ibm.safr.we.data.transfer.GroupTransfer;
import com.ibm.safr.we.data.transfer.GroupUserAssociationTransfer;
import com.ibm.safr.we.exceptions.SAFRNotFoundException;
import com.ibm.safr.we.internal.data.PGSQLGenerator;
import com.ibm.safr.we.model.SAFRApplication;
import com.ibm.safr.we.model.query.EnvironmentQueryBean;
import com.ibm.safr.we.model.query.EnvironmentalQueryBean;
import com.ibm.safr.we.model.query.GroupQueryBean;
import com.ibm.safr.we.model.query.LogicalFileQueryBean;
import com.ibm.safr.we.model.query.LogicalRecordQueryBean;
import com.ibm.safr.we.model.query.PhysicalFileQueryBean;
import com.ibm.safr.we.model.query.UserExitRoutineQueryBean;
import com.ibm.safr.we.model.query.UserQueryBean;
import com.ibm.safr.we.model.query.ViewFolderQueryBean;
/**
* This class is used to implement the unimplemented methods of <b>GroupDAO</b>.
* This class contains the methods related to Groups which require database
* access.
*
*/
public class PGGroupDAO implements GroupDAO {
static transient Logger logger = Logger
.getLogger("com.ibm.safr.we.internal.data.dao.PGGroupDAO");
private static final String TABLE_NAME = "GROUP";
private static final String COL_ID = "GROUPID";
private static final String COL_DESC = "NAME";
private static final String COL_COMMENT = "COMMENTS";
private static final String COL_CREATETIME = "CREATEDTIMESTAMP";
private static final String COL_CREATEBY = "CREATEDUSERID";
private static final String COL_MODIFYTIME = "LASTMODTIMESTAMP";
private static final String COL_MODIFYBY = "LASTMODUSERID";
private Connection con;
private ConnectionParameters params;
private UserSessionParameters safrLogin;
private PGSQLGenerator generator = new PGSQLGenerator();
public PGGroupDAO(Connection con, ConnectionParameters params,
UserSessionParameters safrLogin) {
this.con = con;
this.params = params;
this.safrLogin = safrLogin;
}
public List<GroupQueryBean> queryAllGroups(SortType sortType)
throws DAOException {
List<GroupQueryBean> result = new ArrayList<GroupQueryBean>();
try {
String selectString = "";
String orderString = "";
if (sortType.equals(SortType.SORT_BY_ID)) {
orderString += COL_ID;
} else {
orderString += "UPPER( " + COL_DESC + ")";
}
if (SAFRApplication.getUserSession().isSystemAdministrator()) {
selectString = "Select " + COL_ID + ", " + COL_DESC + ", "
+ COL_CREATETIME + ", " + COL_CREATEBY + ", "
+ COL_MODIFYTIME + ", " + COL_MODIFYBY + " From "
+ params.getSchema() + "." + TABLE_NAME + " Order By "
+ orderString;
} else if (SAFRApplication.getUserSession().isEnvironmentAdministrator()) {
selectString = "Select DISTINCT A.GROUPID, A.NAME, A.CREATEDTIMESTAMP, A.CREATEDUSERID, "
+ "A.LASTMODTIMESTAMP, A.LASTMODUSERID From "
+ params.getSchema()
+ ".GROUP A, "
+ params.getSchema()
+ ".SECENVIRON B, "
+ params.getSchema()
+ ".SECUSER C Where A.GROUPID = B.GROUPID AND "
+ "B.GROUPID = C.GROUPID AND B.ENVROLE='ADMIN' AND C.USERID = '"
+ safrLogin.getUserId() + "'";
} else {
// CQ 8898. Nikita. 01/12/2010
// Return empty list for general user.
return result;
}
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(selectString);
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
while (rs.next()) {
int i = 1;
GroupQueryBean groupBean = new GroupQueryBean(rs.getInt(i++),
DataUtilities.trimString(rs.getString(i++)), rs
.getDate(i++), DataUtilities.trimString(rs
.getString(i++)), rs.getDate(i++),
DataUtilities.trimString(rs.getString(i++)));
result.add(groupBean);
}
pst.close();
rs.close();
return result;
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while querying all Groups.", e);
}
}
public GroupTransfer getGroup(Integer id) throws DAOException {
GroupTransfer result = null;
try {
List<String> idNames = new ArrayList<String>();
idNames.add(COL_ID);
String selectString = generator.getSelectStatement(params
.getSchema(), TABLE_NAME, idNames, null);
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(selectString);
pst.setInt(1, id);
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
if (rs.next()) {
result = generateTransfer(rs);
} else {
logger.info("No such Group in database with ID : " + id);
}
pst.close();
rs.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while retrieving the Group with id ["
+ id + "]", e);
}
return result;
}
public GroupTransfer getGroup(String name) throws DAOException {
GroupTransfer result = null;
try {
List<String> idNames = new ArrayList<String>();
idNames.add(COL_ID);
String selectString = "SELECT * " +
"FROM " +params.getSchema() +".GROUP " +
"WHERE NAME=?";
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(selectString);
pst.setString(1, name);
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
if (rs.next()) {
result = generateTransfer(rs);
} else {
logger.info("No such Group in database with name : " + name);
}
pst.close();
rs.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while retrieving the Group with name ["
+ name + "]", e);
}
return result;
}
/**
* This function is used to generate a transfer object for the Group.
*
* @param rs
* : The resultset of a database query run on GROUP table
* with which the values for the transfer objects are set.
* @return A transfer object for the Group with values set according to the
* resultset.
* @throws SQLException
*/
private GroupTransfer generateTransfer(ResultSet rs) throws SQLException {
GroupTransfer group = new GroupTransfer();
group.setId(rs.getInt(COL_ID));
group.setName(DataUtilities.trimString(rs.getString(COL_DESC)));
group.setComments(DataUtilities.trimString(rs.getString(COL_COMMENT)));
group.setCreateTime(rs.getDate(COL_CREATETIME));
group.setCreateBy(DataUtilities.trimString(rs.getString(COL_CREATEBY)));
group.setModifyTime(rs.getDate(COL_MODIFYTIME));
group.setModifyBy(DataUtilities.trimString(rs.getString(COL_MODIFYBY)));
return group;
}
public GroupTransfer persistGroup(GroupTransfer group) throws DAOException,
SAFRNotFoundException {
if (group.getId() == 0) {
return (createGroup(group));
} else {
return (updateGroup(group));
}
}
/**
* This function is used to create a Group in GROUP table
*
* @param group
* : The transfer object which contains the values which are to
* be set in the columns for the corresponding Group which is
* being created.
* @return The transfer object which contains the values which are received
* from the GROUP for the Group which is created.
* @throws DAOException
*/
private GroupTransfer createGroup(GroupTransfer group) throws DAOException {
try {
String[] columnNames = { COL_DESC, COL_COMMENT,
COL_CREATETIME, COL_CREATEBY, COL_MODIFYTIME, COL_MODIFYBY };
List<String> names = Arrays.asList(columnNames);
String statement = generator.getInsertStatement(params.getSchema(),
TABLE_NAME, COL_ID, names, true);
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(statement);
int i = 1;
pst.setString(i++, group.getName());
pst.setString(i++, group.getComments());
pst.setString(i++, safrLogin.getUserId());
pst.setString(i++, safrLogin.getUserId());
rs = pst.executeQuery();
rs.next();
int id = rs.getInt(1);
group.setPersistent(true);
group.setId(id);
group.setCreateBy(safrLogin.getUserId());
group.setCreateTime(rs.getDate(2));
group.setModifyBy(safrLogin.getUserId());
group.setModifyTime(rs.getDate(3));
rs.close();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
pst.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while creating a new Group.", e);
}
return group;
}
/**
* This function is used to update a Group in GROUP table.
*
* @param group
* : The transfer object which contains the values which are to
* be set in the columns for the corresponding Group which is
* being updated.
* @return The transfer object which contains the values which are received
* from the GROUP for the Group which is updated recently.
* @throws DAOException
* @throws SAFRNotFoundException
*/
private GroupTransfer updateGroup(GroupTransfer group) throws DAOException,
SAFRNotFoundException {
try {
String[] columnNames = { COL_DESC, COL_COMMENT, COL_MODIFYTIME, COL_MODIFYBY };
List<String> names = Arrays.asList(columnNames);
List<String> idNames = new ArrayList<String>();
idNames.add(COL_ID);
String statement = generator.getUpdateStatement(params.getSchema(), TABLE_NAME, names, idNames);
PreparedStatement pst = con.prepareStatement(statement);
while (true) {
try {
int i = 1;
pst.setString(i++, group.getName());
pst.setString(i++, group.getComments());
pst.setString(i++, safrLogin.getUserId());
pst.setInt(i++, group.getId());
ResultSet rs = pst.executeQuery();
rs.next();
group.setModifyTime(rs.getDate(1));
group.setModifyBy(safrLogin.getUserId());
rs.close();
pst.close();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while updating the Group.", e);
}
return group;
}
public GroupTransfer getDuplicateGroup(String groupName, Integer groupId)
throws DAOException {
GroupTransfer result = null;
try {
String statement = generator.getDuplicateComponent(params
.getSchema(), TABLE_NAME, COL_DESC, COL_ID);
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(statement);
int i = 1;
pst.setString(i++, groupName.toUpperCase());
pst.setInt(i++, groupId);
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
if (rs.next()) {
result = generateTransfer(rs);
logger.info("Existing Group with name '" + groupName + "' found.");
}
pst.close();
rs.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException("Database error occurred while retrieving a duplicate Group.",e);
}
return result;
}
public void removeGroup(Integer id) throws DAOException {
try {
List<String> idNames = new ArrayList<String>();
idNames.add(COL_ID);
String statement = generator.getDeleteStatement(params.getSchema(),
TABLE_NAME, idNames);
PreparedStatement pst = null;
while (true) {
try {
pst = con.prepareStatement(statement);
pst.setInt(1, id);
pst.execute();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
pst.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while deleting the Group.", e);
}
}
public List<GroupUserAssociationTransfer> getAssociatedUsers(Integer groupId)
throws DAOException {
List<GroupUserAssociationTransfer> result = new ArrayList<GroupUserAssociationTransfer>();
try {
String schema = params.getSchema();
String selectString = "Select A.USERID, B.FIRSTNAME, B.MIDDLEINIT, B.LASTNAME From "
+ schema
+ ".SECUSER A, "
+ schema
+ ".USER B"
+ " Where GROUPID = ? "
+ " AND A.USERID = B.USERID";
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(selectString);
pst.setInt(1, groupId);
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
String lastName;
String firstName;
String middleInitial;
String fullName = "";
while (rs.next()) {
fullName = "";
firstName = DataUtilities.trimString(rs.getString("FIRSTNAME"));
middleInitial = DataUtilities.trimString(rs
.getString("MIDDLEINIT"));
lastName = DataUtilities.trimString(rs.getString("LASTNAME"));
if (lastName != null && !lastName.equals("")) {
fullName = lastName + ",";
}
if (firstName != null) {
fullName += firstName + " ";
}
if (middleInitial != null) {
fullName += middleInitial;
}
GroupUserAssociationTransfer groupUserAssociationTransfer = new GroupUserAssociationTransfer();
groupUserAssociationTransfer.setUserId(DataUtilities
.trimString(rs.getString("USERID")));
groupUserAssociationTransfer
.setAssociatedComponentName(fullName);
result.add(groupUserAssociationTransfer);
}
pst.close();
rs.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException("Database error occurred while retrieving list of Users associated with the Group.",e);
}
return result;
}
public List<GroupUserAssociationTransfer> persistAssociatedUsers(
List<GroupUserAssociationTransfer> groupUserAssociationTransfer,
Integer groupId) throws DAOException {
groupUserAssociationTransfer = createAssociatedUsers(
groupUserAssociationTransfer, groupId);
return groupUserAssociationTransfer;
}
private List<GroupUserAssociationTransfer> createAssociatedUsers(
List<GroupUserAssociationTransfer> groupUserAssociationTransfer,
Integer groupId) throws DAOException {
try {
String[] columnNames = { COL_ID, "USERID", COL_CREATETIME,
COL_CREATEBY, COL_MODIFYTIME, COL_MODIFYBY };
List<String> names = Arrays.asList(columnNames);
String statement = generator.getInsertStatementNoIdentifier(params.getSchema(),
"SECUSER", names);
PreparedStatement pst = null;
while (true) {
try {
pst = con.prepareStatement(statement);
for (GroupUserAssociationTransfer associatedUsertoCreate : groupUserAssociationTransfer) {
int i = 1;
pst.setInt(i++, groupId);
pst.setString(i++, associatedUsertoCreate.getUserId());
pst.setString(i++, safrLogin.getUserId());
pst.setString(i++, safrLogin.getUserId());
pst.executeUpdate();
associatedUsertoCreate.setPersistent(true);
}
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
pst.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException("Database error occurred while creating User associations with the Group.",e);
}
return groupUserAssociationTransfer;
}
public void deleteAssociatedUser(Integer secGroupId, List<String> deletionIds)
throws DAOException {
try {
String statement = "Delete From " + params.getSchema()
+ ".SECUSER" + " Where GROUPID = ? "
+ " AND USERID IN (" + generator.getPlaceholders(deletionIds.size()) +")";
PreparedStatement pst = null;
while (true) {
try {
pst = con.prepareStatement(statement);
int ndx = 1;
pst.setInt(ndx++, secGroupId);
for(int i=0; i<deletionIds.size(); i++) {
pst.setString(ndx++, deletionIds.get(i));
}
pst.executeUpdate();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
pst.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException("Database error occurred while deleting User associations with the Group.",e);
}
}
public List<UserQueryBean> queryPossibleUserAssociations(List<String> notInParam)
throws DAOException {
List<UserQueryBean> result = new ArrayList<UserQueryBean>();
try {
String selectString = "Select USERID, FIRSTNAME, MIDDLEINIT, LASTNAME From "
+ params.getSchema()
+ ".USER ";
if(notInParam.size() > 0) {
selectString += " Where USERID NOT IN (" + generator.getPlaceholders(notInParam.size()) + ") ";
}
selectString += " Order By USERID";
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(selectString);
int ndx = 1;
for(int i=0; i<notInParam.size(); i++) {
pst.setString(ndx++, notInParam.get(i));
}
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
while (rs.next()) {
int i = 1;
UserQueryBean userQueryBean = new UserQueryBean(DataUtilities
.trimString(rs.getString(i++)), DataUtilities
.trimString(rs.getString(i++)), DataUtilities
.trimString(rs.getString(i++)), DataUtilities
.trimString(rs.getString(i++)), false, null, null,
null, null, null);
result.add(userQueryBean);
}
pst.close();
rs.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException("Database error occurred while retrieving all the possible Users which can be associated with the Group.",e);
}
return result;
}
public List<GroupEnvironmentAssociationTransfer> getAssociatedEnvironments(
Integer groupId) throws DAOException {
List<GroupEnvironmentAssociationTransfer> result = new ArrayList<GroupEnvironmentAssociationTransfer>();
try {
String schema = params.getSchema();
String selectString = "";
if (SAFRApplication.getUserSession().isSystemAdministrator()) {
selectString = "Select A.ENVIRONID, B.NAME, "
+ "A.ENVROLE, A.PFRIGHTS, A.LFRIGHTS, A.LRRIGHTS, "
+ "A.EXITRIGHTS, A.LPRIGHTS, A.VWRIGHTS, A.VFRIGHTS, A.MGRIGHTS "
+ " From " + schema
+ ".SECENVIRON A, " + schema + ".ENVIRON B"
+ " Where GROUPID = ? "
+ " AND A.ENVIRONID = B.ENVIRONID";
} else {
selectString = "Select A.ENVIRONID, B.NAME, "
+ "A.ENVROLE, A.PFRIGHTS, A.LFRIGHTS, A.LRRIGHTS, "
+ "A.EXITRIGHTS, A.LPRIGHTS, A.VWRIGHTS, A.VFRIGHTS, A.MGRIGHTS "
+ " From " + schema
+ ".SECENVIRON A, " + schema + ".ENVIRON B"
+ " Where GROUPID = ? "
+ " AND A.ENVIRONID = B.ENVIRONID AND A.ENVROLE='ADMIN'";
}
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(selectString);
pst.setInt(1, groupId);
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
while (rs.next()) {
GroupEnvironmentAssociationTransfer envGroupAssocTransfer = new GroupEnvironmentAssociationTransfer();
envGroupAssocTransfer.setAssociatingComponentId(groupId);
envGroupAssocTransfer.setEnvironmentId(rs.getInt("ENVIRONID"));
envGroupAssocTransfer.setAssociatedComponentName(
DataUtilities.trimString(rs.getString("NAME")));
envGroupAssocTransfer.setEnvRole(
EnvRole.getEnvRoleFromCode(DataUtilities.trimString(rs.getString("ENVROLE"))));
envGroupAssocTransfer.setPhysicalFileCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("PFRIGHTS")));
envGroupAssocTransfer.setLogicalFileCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("LFRIGHTS")));
envGroupAssocTransfer.setLogicalRecordCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("LRRIGHTS")));
envGroupAssocTransfer.setUserExitRoutineCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("EXITRIGHTS")));
envGroupAssocTransfer.setLookupPathCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("LPRIGHTS")));
envGroupAssocTransfer.setViewCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("VWRIGHTS")));
envGroupAssocTransfer.setViewFolderCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("VFRIGHTS")));
envGroupAssocTransfer.setMigrateInPermissions(
DataUtilities.intToBoolean(rs.getInt("MGRIGHTS")));
result.add(envGroupAssocTransfer);
}
pst.close();
rs.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while retrieving the Environments associated with the Group.",e);
}
return result;
}
public GroupEnvironmentAssociationTransfer getAssociatedEnvironment(
Integer groupId, Integer environmentId) throws DAOException {
GroupEnvironmentAssociationTransfer envGroupAssocTransfer = null;
try {
String schema = params.getSchema();
String selectString = "Select A.ENVIRONID, B.NAME, "
+ "A.ENVROLE, A.PFRIGHTS, A.LFRIGHTS, A.LRRIGHTS, "
+ "A.EXITRIGHTS, A.LPRIGHTS, A.VWRIGHTS, A.VFRIGHTS, A.MGRIGHTS"
+ " From " + schema
+ ".SECENVIRON A, " + schema + ".ENVIRON B"
+ " Where GROUPID = ? "
+ " AND A.ENVIRONID = B.ENVIRONID AND A.ENVIRONID = ? ";
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(selectString);
pst.setInt(1, groupId);
pst.setInt(2, environmentId);
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
while (rs.next()) {
envGroupAssocTransfer = new GroupEnvironmentAssociationTransfer();
envGroupAssocTransfer.setAssociatingComponentId(groupId);
envGroupAssocTransfer.setEnvironmentId(environmentId);
envGroupAssocTransfer.setAssociatedComponentName(
DataUtilities.trimString(rs.getString("NAME")));
envGroupAssocTransfer.setEnvRole(
EnvRole.getEnvRoleFromCode(DataUtilities.trimString(rs.getString("ENVROLE"))));
envGroupAssocTransfer.setPhysicalFileCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("PFRIGHTS")));
envGroupAssocTransfer.setLogicalFileCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("LFRIGHTS")));
envGroupAssocTransfer.setLogicalRecordCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("LRRIGHTS")));
envGroupAssocTransfer.setUserExitRoutineCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("EXITRIGHTS")));
envGroupAssocTransfer.setLookupPathCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("LPRIGHTS")));
envGroupAssocTransfer.setViewCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("VWRIGHTS")));
envGroupAssocTransfer.setViewFolderCreatePermissions(
DataUtilities.intToBoolean(rs.getInt("VFRIGHTS")));
envGroupAssocTransfer.setMigrateInPermissions(
DataUtilities.intToBoolean(rs.getInt("MGRIGHTS")));
}
pst.close();
rs.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while retrieving the Environments association with the Group.",e);
}
return envGroupAssocTransfer;
}
public List<EnvironmentQueryBean> queryPossibleEnvironmentAssociations(
List<Integer> associatedEnvIds) throws DAOException {
List<EnvironmentQueryBean> result = new ArrayList<EnvironmentQueryBean>();
String notInList = "";
try {
notInList = DataUtilities.integerListToString(associatedEnvIds);
String selectString = "Select ENVIRONID, NAME From "
+ params.getSchema() + ".ENVIRON Where "
+ "ENVIRONID NOT IN " + notInList + " Order By ENVIRONID";
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(selectString);
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
while (rs.next()) {
EnvironmentQueryBean envQueryBean = new EnvironmentQueryBean(rs
.getInt("ENVIRONID"), DataUtilities.trimString(rs
.getString("NAME")), true, null, null, null,
null);
result.add(envQueryBean);
}
pst.close();
rs.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException("Database error occurred while querying all the possible Environments which can be associated with the Group.",e);
}
return result;
}
private void createGroupEnvironmentAssociations(List<GroupEnvironmentAssociationTransfer> createList)
throws DAOException, SQLException {
String schema = params.getSchema();
PreparedStatement pst = null;
String createStatement = "INSERT INTO " + schema +".SECENVIRON" +
" (GROUPID,ENVIRONID,ENVROLE,PFRIGHTS,LFRIGHTS,LRRIGHTS,EXITRIGHTS,LPRIGHTS,VWRIGHTS,"
+ "VFRIGHTS,MGRIGHTS,CREATEDTIMESTAMP,CREATEDUSERID,LASTMODTIMESTAMP,LASTMODUSERID)" +
" VALUES (?,?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP,?,CURRENT_TIMESTAMP,?)";
if (createList == null) {
return;
}
while (true) {
try {
pst = con.prepareStatement(createStatement);
for (GroupEnvironmentAssociationTransfer trans : createList) {
int i = 1;
pst.setInt(i++, trans.getAssociatingComponentId());
pst.setInt(i++, trans.getEnvironmentId());
pst.setString(i++, trans.getEnvRole().getCode());
if (trans.hasPhysicalFileCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasLogicalFileCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasLogicalRecordCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasUserExitRoutineCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasLookupPathCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasViewCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasViewFolderCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasMigrateInPermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
pst.setString(i++,safrLogin.getUserId());
pst.setString(i++,safrLogin.getUserId());
pst.executeUpdate();
trans.setPersistent(true);
}
pst.close();
break;
}
catch (SQLException se) {
if (con.isClosed()) {
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
}
private void updateGroupEnvironmentAssociations(List<GroupEnvironmentAssociationTransfer> updateList)
throws DAOException, SQLException {
String schema = params.getSchema();
PreparedStatement pst = null;
String updateStatement = "UPDATE " + schema +".SECENVIRON SET " +
"ENVROLE=?,PFRIGHTS=?,LFRIGHTS=?,LRRIGHTS=?,EXITRIGHTS=?," +
"LPRIGHTS=?,VWRIGHTS=?,VFRIGHTS=?,MGRIGHTS=?," +
"LASTMODTIMESTAMP=CURRENT_TIMESTAMP,LASTMODUSERID=? " +
"WHERE GROUPID=? AND ENVIRONID=?";
if (updateList == null) {
return;
}
while (true) {
try {
pst = con.prepareStatement(updateStatement);
for (GroupEnvironmentAssociationTransfer trans : updateList) {
int i = 1;
pst.setString(i++, trans.getEnvRole().getCode());
if (trans.hasPhysicalFileCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasLogicalFileCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasLogicalRecordCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasUserExitRoutineCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasLookupPathCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasViewCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasViewFolderCreatePermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
if (trans.hasMigrateInPermissions()) {
pst.setInt(i++, 1);
} else {
pst.setInt(i++, 0);
}
pst.setString(i++,safrLogin.getUserId());
pst.setInt(i++, trans.getAssociatingComponentId());
pst.setInt(i++, trans.getEnvironmentId());
pst.executeUpdate();
trans.setPersistent(true);
}
pst.close();
break;
}
catch (SQLException se) {
if (con.isClosed()) {
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
}
private void deleteGroupEnvironmentAssociations(List<GroupEnvironmentAssociationTransfer> deleteList)
throws DAOException, SQLException {
String schema = params.getSchema();
String deleteStatementP1 = "DELETE FROM " + schema +".SECEXIT " +
"WHERE GROUPID=? AND ENVIRONID=?";
String deleteStatementP2 = "DELETE FROM " + schema +".SECPHYFILE " +
"WHERE GROUPID=? AND ENVIRONID=?";
String deleteStatementP3 = "DELETE FROM " + schema +".SECLOGFILE " +
"WHERE GROUPID=? AND ENVIRONID=?";
String deleteStatementP4 = "DELETE FROM " + schema +".SECLOGREC " +
"WHERE GROUPID=? AND ENVIRONID=?";
String deleteStatementP5 = "DELETE FROM " + schema +".SECLOOKUP " +
"WHERE GROUPID=? AND ENVIRONID=?";
String deleteStatementP6 = "DELETE FROM " + schema +".SECVIEW " +
"WHERE GROUPID=? AND ENVIRONID=?";
String deleteStatementP7 = "DELETE FROM " + schema +".SECVIEWFOLDER " +
"WHERE GROUPID=? AND ENVIRONID=?";
String deleteStatement = "DELETE FROM " + schema +".SECENVIRON " +
"WHERE GROUPID=? AND ENVIRONID=?";
if (deleteList == null) {
return;
}
while (true) {
try {
PreparedStatement pstP1 = con.prepareStatement(deleteStatementP1);
PreparedStatement pstP2 = con.prepareStatement(deleteStatementP2);
PreparedStatement pstP3 = con.prepareStatement(deleteStatementP3);
PreparedStatement pstP4 = con.prepareStatement(deleteStatementP4);
PreparedStatement pstP5 = con.prepareStatement(deleteStatementP5);
PreparedStatement pstP6 = con.prepareStatement(deleteStatementP6);
PreparedStatement pstP7 = con.prepareStatement(deleteStatementP7);
PreparedStatement pst = con.prepareStatement(deleteStatement);
for (GroupEnvironmentAssociationTransfer trans : deleteList) {
int i = 1;
pstP1.setInt(i++, trans.getAssociatingComponentId());
pstP1.setInt(i++, trans.getEnvironmentId());
pstP1.executeUpdate();
i = 1;
pstP2.setInt(i++, trans.getAssociatingComponentId());
pstP2.setInt(i++, trans.getEnvironmentId());
pstP2.executeUpdate();
i = 1;
pstP3.setInt(i++, trans.getAssociatingComponentId());
pstP3.setInt(i++, trans.getEnvironmentId());
pstP3.executeUpdate();
i = 1;
pstP4.setInt(i++, trans.getAssociatingComponentId());
pstP4.setInt(i++, trans.getEnvironmentId());
pstP4.executeUpdate();
i = 1;
pstP5.setInt(i++, trans.getAssociatingComponentId());
pstP5.setInt(i++, trans.getEnvironmentId());
pstP5.executeUpdate();
i = 1;
pstP6.setInt(i++, trans.getAssociatingComponentId());
pstP6.setInt(i++, trans.getEnvironmentId());
pstP6.executeUpdate();
i = 1;
pstP7.setInt(i++, trans.getAssociatingComponentId());
pstP7.setInt(i++, trans.getEnvironmentId());
pstP7.executeUpdate();
i = 1;
pst.setInt(i++, trans.getAssociatingComponentId());
pst.setInt(i++, trans.getEnvironmentId());
pst.executeUpdate();
trans.setPersistent(false);
}
pstP1.close();
pstP2.close();
pstP3.close();
pstP4.close();
pstP5.close();
pstP6.close();
pstP7.close();
pst.close();
break;
}
catch (SQLException se) {
if (con.isClosed()) {
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
}
public void persistGroupEnvironmentAssociations(
List<GroupEnvironmentAssociationTransfer> createList,
List<GroupEnvironmentAssociationTransfer> updateList,
List<GroupEnvironmentAssociationTransfer> deleteList)
throws DAOException {
try {
createGroupEnvironmentAssociations(createList);
updateGroupEnvironmentAssociations(updateList);
deleteGroupEnvironmentAssociations(deleteList);
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while creating, updating or deleting the Group to Environment associations.",e);
}
}
public List<GroupComponentAssociationTransfer> getComponentEditRights(
ComponentType compType, Integer environmentId, Integer groupId) throws DAOException
{
List<GroupComponentAssociationTransfer> componentEditRights = new ArrayList<GroupComponentAssociationTransfer>();
// return empty list if no component type is passed.
if (compType == null) {
return componentEditRights;
}
try {
String schema = params.getSchema();
String selectString = "";
if (compType == ComponentType.PhysicalFile) {
selectString = "Select A.PHYFILEID, B.NAME, A.RIGHTS "
+ "From "+ schema+ ".PHYFILE B INNER JOIN "
+ schema + ".SECPHYFILE A ON B.ENVIRONID = A.ENVIRONID"
+ " Where"+ " A.PHYFILEID = B.PHYFILEID AND A.ENVIRONID = ? AND B.ENVIRONID = ? "
+ " AND A.GROUPID = ? ";
} else if (compType == ComponentType.LogicalFile) {
selectString = "Select A.LOGFILEID, B.NAME, A.RIGHTS "
+ "From " + schema + ".LOGFILE B INNER JOIN "
+ schema+ ".SECLOGFILE A ON B.ENVIRONID = A.ENVIRONID"
+ " Where " + " A.LOGFILEID = B.LOGFILEID AND A.ENVIRONID = ? AND B.ENVIRONID = ? "
+ " AND A.GROUPID = ? ";
} else if (compType == ComponentType.LogicalRecord) {
selectString = "Select A.LOGRECID, B.NAME, A.RIGHTS " + "From "
+ schema + ".LOGREC B INNER JOIN " + schema
+ ".SECLOGREC A ON B.ENVIRONID = A.ENVIRONID"
+ " Where " + " A.LOGRECID = B.LOGRECID AND A.ENVIRONID = ? AND B.ENVIRONID = ? "
+ " AND A.GROUPID = ? ";
} else if (compType == ComponentType.UserExitRoutine) {
selectString = "Select A.EXITID, B.NAME, A.RIGHTS "
+ "From "+ schema+ ".EXIT B INNER JOIN "
+ schema+ ".SECEXIT A ON B.ENVIRONID = A.ENVIRONID"
+ " Where " + " A.EXITID = B.EXITID AND A.ENVIRONID = ? AND B.ENVIRONID = ? "
+ " AND A.GROUPID = ? ";
} else if (compType == ComponentType.LookupPath) {
selectString = "Select A.LOOKUPID, A.NAME, B.RIGHTS "
+ "From "+ schema+ ".LOOKUP A INNER JOIN "
+ schema + ".SECLOOKUP B "
+ "ON A.ENVIRONID = B.ENVIRONID"
+ " AND A.LOOKUPID = B.LOOKUPID"
+ " WHERE A.ENVIRONID = ? AND B.ENVIRONID = ? "
+ " AND B.GROUPID = ? ";
} else if (compType == ComponentType.View) {
selectString = "Select A.VIEWID, A.NAME, B.RIGHTS "
+ "From "+ schema+ ".VIEW A INNER JOIN "
+ schema + ".SECVIEW B "
+ "ON A.ENVIRONID = B.ENVIRONID"
+ " AND A.VIEWID = B.VIEWID"
+ " WHERE B.ENVIRONID = ? "
+ " AND B.GROUPID = ? ";
} else if (compType == ComponentType.ViewFolder) {
selectString = "Select A.VIEWFOLDERID, B.NAME, A.RIGHTS "
+ "From "+ schema+ ".VIEWFOLDER B INNER JOIN "
+ schema+ ".SECVIEWFOLDER A ON B.ENVIRONID = A.ENVIRONID"
+ " Where "+ " A.VIEWFOLDERID = B.VIEWFOLDERID AND A.ENVIRONID = ? "
+ " AND B.ENVIRONID = ? "
+ " AND A.GROUPID = ? ";
}
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(selectString);
pst.setInt(1, environmentId);
if (compType == ComponentType.View) {
pst.setInt(2, groupId);
}
else {
pst.setInt(2, environmentId);
pst.setInt(3, groupId);
}
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
while (rs.next()) {
GroupComponentAssociationTransfer grpCompTransfer = new GroupComponentAssociationTransfer();
int i = 1;
grpCompTransfer.setComponentId(rs.getInt(i++));
grpCompTransfer.setAssociatedComponentName(DataUtilities.trimString(rs.getString(i++)));
grpCompTransfer.setEnvironmentId(environmentId);
grpCompTransfer.setRights(SAFRApplication.getUserSession().getEditRightsNoUser(rs.getInt(i++), compType, environmentId));
componentEditRights.add(grpCompTransfer);
}
pst.close();
rs.close();
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while retrieving a list of a components along with their edit rights for a particular Environment-Group association.",e);
}
return componentEditRights;
}
public List<EnvironmentalQueryBean> queryPossibleComponentAssociations(
ComponentType compType, Integer environmentId,
List<Integer> associatedCompIds) throws DAOException {
List<EnvironmentalQueryBean> result = new ArrayList<EnvironmentalQueryBean>();
String notInList = "";
try {
String placeholders = generator.getPlaceholders(associatedCompIds.size());
String selectString = "";
PreparedStatement pst;
ResultSet rs;
while (true) {
try {
if (compType == ComponentType.PhysicalFile) {
selectString = "Select PHYFILEID, NAME From "
+ params.getSchema()
+ ".PHYFILE Where ENVIRONID = ? "
+ " AND PHYFILEID >0";
if(associatedCompIds.size() > 0) {
selectString += " AND PHYFILEID NOT IN (" + placeholders + " ) ";
}
selectString += " Order By PHYFILEID";
pst = con.prepareStatement(selectString);
int ndx = 1;
pst.setInt(ndx++, environmentId);
for(int i=0; i<associatedCompIds.size(); i++) {
pst.setInt(ndx++, associatedCompIds.get(i));
}
rs = pst.executeQuery();
while (rs.next()) {
EnvironmentalQueryBean queryBean = new PhysicalFileQueryBean(
environmentId, rs.getInt("PHYFILEID"),
DataUtilities.trimString(rs.getString("NAME")),
null, null, null, null, null, null,
null, null, null, null, null);
result.add(queryBean);
}
pst.close();
rs.close();
} else if (compType == ComponentType.LogicalFile) {
selectString = "Select LOGFILEID, NAME From "
+ params.getSchema()
+ ".LOGFILE Where ENVIRONID = ? "
+ " AND LOGFILEID >0 ";
if(associatedCompIds.size() > 0) {
selectString += " AND LOGFILEID NOT IN (" + placeholders + " ) ";
}
selectString += " Order By LOGFILEID";
pst = con.prepareStatement(selectString);
int ndx = 1;
pst.setInt(ndx++, environmentId);
for(int i=0; i<associatedCompIds.size(); i++) {
pst.setInt(ndx++, associatedCompIds.get(i));
}
rs = pst.executeQuery();
while (rs.next()) {
EnvironmentalQueryBean queryBean = new LogicalFileQueryBean(
environmentId, rs.getInt("LOGFILEID"),
DataUtilities.trimString(rs.getString("NAME")),
null, null, null, null, null);
result.add(queryBean);
}
pst.close();
rs.close();
} else if (compType == ComponentType.LogicalRecord) {
selectString = "Select LOGRECID, NAME From "
+ params.getSchema()
+ ".LOGRECID Where ENVIRONID = ? "
+ " AND LOGRECID >0 ";
if(associatedCompIds.size() > 0) {
selectString += " AND LOGRECID NOT IN (" + placeholders + " ) ";
}
selectString += " Order By LOGRECID";
pst = con.prepareStatement(selectString);
int ndx = 1;
rs = pst.executeQuery();
while (rs.next()) {
EnvironmentalQueryBean queryBean = new LogicalRecordQueryBean(
environmentId, rs.getInt("LOGRECID"),
DataUtilities.trimString(rs.getString("NAME")),
null, null, null, null, null, null, null, null, null, null, null);
result.add(queryBean);
}
pst.close();
rs.close();
} else if (compType == ComponentType.UserExitRoutine) {
selectString = "Select EXITID, NAME From "
+ params.getSchema()
+ ".EXITID Where ENVIRONID = ? "
+ " AND EXITID >0 ";
if(associatedCompIds.size() > 0) {
selectString += " AND EXITID NOT IN (" + placeholders + " ) ";
}
selectString += " Order By EXITID";
pst = con.prepareStatement(selectString);
int ndx = 1;
pst.setInt(ndx++, environmentId);
for(int i=0; i<associatedCompIds.size(); i++) {
pst.setInt(ndx++, associatedCompIds.get(i));
}
rs = pst.executeQuery();
while (rs.next()) {
EnvironmentalQueryBean queryBean = new UserExitRoutineQueryBean(
environmentId, rs.getInt("EXITID"),
DataUtilities.trimString(rs.getString("NAME")),
null, null, null, null, null, null, null, null);
result.add(queryBean);
}
pst.close();
rs.close();
} else if (compType == ComponentType.ViewFolder) {
if (associatedCompIds.size() == 0) {
selectString = "Select VIEWFOLDERID, NAME From "
+ params.getSchema()
+ ".VIEWFOLDER Where ENVIRONID = ? "
+ " Order By VIEWFOLDERID";
} else {
selectString = "Select VIEWFOLDERID, NAME From "
+ params.getSchema()
+ ".VIEWFOLDER Where ENVIRONID = ? "
+ " AND VIEWFOLDERID NOT IN (" + placeholders + " ) "
+ " Order By VIEWFOLDERID";
}
pst = con.prepareStatement(selectString);
int ndx = 1;
pst.setInt(ndx++, environmentId);
for(int i=0; i<associatedCompIds.size(); i++) {
pst.setInt(ndx++, associatedCompIds.get(i));
}
rs = pst.executeQuery();
while (rs.next()) {
EnvironmentalQueryBean queryBean = new ViewFolderQueryBean(
environmentId, rs.getInt("VIEWFOLDERID"),
DataUtilities.trimString(rs.getString("NAME")),
null, null, null, null, null);
result.add(queryBean);
}
pst.close();
rs.close();
}
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
} catch (SQLException e) {
throw DataUtilities.createDAOException("Database error occurred while querying all the possible components which can be associated with the Group.",e);
}
return result;
}
public List<GroupQueryBean> queryGroups(String userId, Integer environmentId)
throws DAOException {
List<GroupQueryBean> result = new ArrayList<GroupQueryBean>();
try {
String selectString = "SELECT A.GROUPID, A.NAME, "
+ "A.CREATEDTIMESTAMP, A.CREATEDUSERID, A.LASTMODTIMESTAMP, A.LASTMODUSERID "
+ "FROM " + params.getSchema() + ".GROUP A, "
+ params.getSchema() + ".SECUSER B, "
+ params.getSchema() + ".SECENVIRON C "
+ "WHERE A.GROUPID = B.GROUPID AND B.USERID = ? "
+ " AND A.GROUPID = C.GROUPID AND C.ENVIRONID = ? "
+ " ORDER BY UPPER(A.NAME)";
PreparedStatement pst = null;
ResultSet rs = null;
while (true) {
try {
pst = con.prepareStatement(selectString);
pst.setString(1, userId);
pst.setInt(2, environmentId);
rs = pst.executeQuery();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and retry
con = DAOFactoryHolder.getDAOFactory().reconnect();
} else {
throw se;
}
}
}
while (rs.next()) {
GroupQueryBean groupBean = new GroupQueryBean(rs
.getInt("GROUPID"), DataUtilities.trimString(rs
.getString("NAME")), rs
.getDate("CREATEDTIMESTAMP"), DataUtilities
.trimString(rs.getString("CREATEDUSERID")), rs
.getDate("LASTMODTIMESTAMP"), DataUtilities
.trimString(rs.getString("LASTMODUSERID")));
result.add(groupBean);
}
pst.close();
rs.close();
return result;
} catch (SQLException e) {
throw DataUtilities.createDAOException("Database error occurred while querying the Groups that the specified User belongs to, which are also associated with the specified Environment.",e);
}
}
public void persistComponentEditRights(ComponentType compType,
Integer groupId,
List<GroupComponentAssociationTransfer> createList,
List<GroupComponentAssociationTransfer> updateList,
List<GroupComponentAssociationTransfer> deleteList)
throws DAOException {
try {
String schema = params.getSchema();
String entityType = "";
String xml = "";
if (compType == ComponentType.PhysicalFile) {
entityType = "PF";
} else if (compType == ComponentType.LogicalFile) {
entityType = "LF";
} else if (compType == ComponentType.LogicalRecord) {
entityType = "LR";
} else if (compType == ComponentType.UserExitRoutine) {
entityType = "EXIT";
} else if (compType == ComponentType.LookupPath) {
entityType = "LP";
} else if (compType == ComponentType.View) {
entityType = "VIEW";
} else if (compType == ComponentType.ViewFolder) {
entityType = "VF";
}
xml += "<Root>\n"
+ getXmlForComponentRights(createList, "IN")
+ getXmlForComponentRights(updateList, "UP")
+ getXmlForComponentRights(deleteList, "DE")
+ "</Root>";
if (!xml.equals("")) {
String statement = generator.getSelectFromFunction(schema,
"inssecgrprights", 4);
// CallableStatement proc = null;
PreparedStatement proc = null;
while (true) {
try {
proc = con.prepareStatement(statement);
// proc = con.prepareCall(statement);
int i = 1;
proc.setString(i++, entityType);
proc.setInt(i++, groupId);
proc.setString(i++, safrLogin.getUserId());
proc.setString(i++, xml);
// proc.setString("P_ENTTYPE", entityType);
// proc.setInt("P_SECGROUP", groupId);
// proc.setString("P_USERID", safrLogin.getUserId());
// proc.setString("P_DOC", xml);
// proc.execute();
proc.executeQuery();
proc.close();
break;
} catch (SQLException se) {
if (con.isClosed()) {
// lost database connection, so reconnect and
// retry
con = DAOFactoryHolder.getDAOFactory()
.reconnect();
} else {
throw se;
}
}
}
proc.close();
}
} catch (SQLException e) {
throw DataUtilities.createDAOException(
"Database error occurred while storing the edit rights on the components.",e);
}
}
/**
* This method is for creating the xml which is the input
* parameter for the Stored Procedure GP_INSSECGRPRGHT which is used to
* store edit rights of a Group over the different metadata components of an
* Environment.
*
* @param list
* : The list of GroupEnvironmentAssociationTransfer objects.
* @param action
* : The integer which is responsible for the action which is to
* be performed through the SP. It can be one of create, update
* and delete.
* @return xml which in one of input
* parameter for the Stored Procedure GP_INSSECGRPRGHT for a
* particular type of action.
*/
private String getXmlForComponentRights(
List<GroupComponentAssociationTransfer> list, String action) {
StringBuffer xml = new StringBuffer();
if (list != null && !list.isEmpty()) {
for (GroupComponentAssociationTransfer grpCompAssocTran : list) {
xml.append(" <Operation>");
xml.append(" <OPTYPE>" + action + "</OPTYPE>");
xml.append(" <ENVID>" + grpCompAssocTran.getEnvironmentId() + "</ENVID>");
xml.append(" <ENTID>" + grpCompAssocTran.getComponentId() + "</ENTID>");
xml.append(" <RIGHTS>" + grpCompAssocTran.getRights().getCode() + "</RIGHTS>");
xml.append(" </Operation>");
}
}
return xml.toString();
}
}
| 37.524904 | 191 | 0.580764 |
490f87b9ca584c19b9ce560196c03014a4dc6b01 | 76 | /**
*
*/
/**
* @author invtidke
*
*/
package org.dyfaces.debug; | 9.5 | 26 | 0.473684 |
24133af5a6b53da87fc7e9d91e99a7be66c01474 | 595 | package com.webfleet.oauth.controller;
//@Controller
public class ErrorController //implements org.springframework.boot.web.servlet.error.ErrorController
{
// @RequestMapping(KnownUrls.ERROR)
// public String error(HttpServletRequest request)
// {
// Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
// Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
//
//
// return "error";
// }
//
// @Override
// public String getErrorPath()
// {
// return "/error";
// }
}
| 25.869565 | 100 | 0.668908 |
554c84e0db15b30a5706c1fa54387e10534d89ac | 1,563 | package net.grian.spatium.transform;
import net.grian.spatium.geo3.Triangle3;
import net.grian.spatium.geo3.Vector3;
@FunctionalInterface
public interface Transformation {
/**
* Applies the transformation to a point.
*
* @param point the point
*/
public void transform(Vector3 point);
/**
* Applies the transformation to a triangle.
*
* @param triangle the triangle
*/
public default void transform(Triangle3 triangle) {
triangle.transform(this);
}
/**
* Returns a new transformation which is a composition of the given transformation and this one. The new
* transformation will first apply this transformation and then the current given one.
*
* @param transform the transformation to apply before this one
* @return a new composed transformation
*/
public default Transformation andThen(Transformation transform) {
return (point) -> {this.transform(point); transform.transform(point);};
}
/**
* Returns a new transformation which is a composition of the current and the given transformation. The new
* transformation will first apply the given transformation and then the current one.
*
* @param transform the transformation to apply before this one
* @return a new composed transformation
*/
public default Transformation compose(Transformation transform) {
return (point) -> {transform.transform(point); this.transform(point);};
}
}
| 32.5625 | 112 | 0.668586 |
0a2efc3517df20b87b675562313dbc088a2078c5 | 20,970 |
package controlador;
import java.sql.*;
import javax.swing.table.DefaultTableModel;
import conexion_bd.*;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Juan Nicolas Morales
*/
public class Ventana extends javax.swing.JFrame {
/**
* Creates new form Ventana
*/
public Ventana() {
initComponents();
this.setLocationRelativeTo(null);
DefaultTableModel tabla = new DefaultTableModel();
tabla.addColumn("ID");
tabla.addColumn("Nombre");
tabla.addColumn("Apellido");
tabla.addColumn("Edad");
tabla.addColumn("Curso");
tabla.addColumn("Nota");
tabla_Alumnos.setModel(tabla);
String [] datos = new String[6];
try {
Conexion cn2 = new Conexion();
Connection cn = cn2.conectar();
Statement leer = cn.createStatement();
ResultSet resultado = leer.executeQuery("SELECT * FROM DATOS");
while (resultado.next()) {
datos [0] = resultado.getString(1);
datos [1] = resultado.getString(2);
datos [2] = resultado.getString(3);
datos [3] = resultado.getString(4);
datos [4] = resultado.getString(5);
datos [5] = resultado.getString(6);
tabla.addRow (datos);
}
tabla_Alumnos.setModel(tabla);
} catch (Exception e){
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
tabla_Alumnos = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
aviso_Registro = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
txt_Nombre = new javax.swing.JTextField();
txt_Edad = new javax.swing.JTextField();
txt_Curso = new javax.swing.JTextField();
txt_Apellido = new javax.swing.JTextField();
txt_Nota = new javax.swing.JTextField();
registrar = new javax.swing.JButton();
mostrar_Registro = new javax.swing.JButton();
jComboBox1 = new javax.swing.JComboBox<>();
export_pdf = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenu3 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu4 = new javax.swing.JMenu();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jMenu5 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Registro de Alumnos");
setResizable(false);
tabla_Alumnos.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane1.setViewportView(tabla_Alumnos);
jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 24)); // NOI18N
jLabel1.setText("Registro de Alumnos");
jLabel3.setText("Nombre:");
jLabel4.setText("Apellido:");
jLabel5.setText("Edad:");
jLabel6.setText("Nota:");
jLabel7.setText("Curso:");
registrar.setText("Registrar");
registrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
registrarActionPerformed(evt);
}
});
mostrar_Registro.setText("Consultar");
mostrar_Registro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mostrar_RegistroActionPerformed(evt);
}
});
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Todo", "Menor a mayor", "Mayor a menor", " " }));
jComboBox1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jComboBox1ActionPerformed(evt);
}
});
export_pdf.setText("Exportar pdf");
export_pdf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
export_pdfActionPerformed(evt);
}
});
jLabel2.setText("Filtrar:");
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
jMenu3.setText("jMenu3");
jMenuItem1.setText("jMenuItem1");
jMenu3.add(jMenuItem1);
jMenu4.setText("jMenu4");
jMenu3.add(jMenu4);
jMenu3.add(jSeparator1);
jMenu5.setText("jMenu5");
jMenu3.add(jMenu5);
jMenuBar1.add(jMenu3);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 113, Short.MAX_VALUE)
.addComponent(registrar))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_Apellido, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txt_Edad, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txt_Curso)
.addComponent(txt_Nombre)
.addComponent(txt_Nota))))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(export_pdf)
.addGap(37, 37, 37)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(mostrar_Registro))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGap(23, 23, 23))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(aviso_Registro, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(160, 160, 160)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(108, 108, 108))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(aviso_Registro, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txt_Nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txt_Apellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(3, 3, 3)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt_Edad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt_Curso)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt_Nota)
.addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(registrar)
.addComponent(mostrar_Registro)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(export_pdf)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void registrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registrarActionPerformed
try {
Conexion cn = new Conexion();
Connection cn1 = cn.conectar();
PreparedStatement pts = cn1.prepareStatement("insert into datos values(?,?,?,?,?,?)");
pts.setString(1, "0");
pts.setString(2, txt_Nombre.getText().trim());
pts.setString(3, txt_Apellido.getText().trim());
pts.setString(4, txt_Edad.getText().trim());
pts.setString(5, txt_Curso.getText().trim());
pts.setString(6, txt_Nota.getText().trim());
pts.executeUpdate();
txt_Nombre.setText("");
txt_Apellido.setText("");
txt_Edad.setText("");
txt_Curso.setText("");
txt_Nota.setText("");
aviso_Registro.setText("Registro Exitoso...");
} catch (Exception e) {
}
}//GEN-LAST:event_registrarActionPerformed
private void mostrar_RegistroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mostrar_RegistroActionPerformed
DefaultTableModel tabla = new DefaultTableModel();
tabla.addColumn("ID");
tabla.addColumn("Nombre");
tabla.addColumn("Apellido");
tabla.addColumn("Edad");
tabla.addColumn("Curso");
tabla.addColumn("Nota");
tabla_Alumnos.setModel(tabla);
String [] datos = new String[6];
try {
Conexion cn1 = new Conexion();
Connection cn = cn1.conectar();
Statement leer = cn.createStatement();
ResultSet resultado = leer.executeQuery("SELECT * FROM DATOS");
while (resultado.next()) {
datos [0] = resultado.getString(1);
datos [1] = resultado.getString(2);
datos [2] = resultado.getString(3);
datos [3] = resultado.getString(4);
datos [4] = resultado.getString(5);
datos [5] = resultado.getString(6);
tabla.addRow (datos);
}
tabla_Alumnos.setModel(tabla);
} catch (Exception e){
}
}//GEN-LAST:event_mostrar_RegistroActionPerformed
private void export_pdfActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_export_pdfActionPerformed
Document documento = new Document();
try {
String ruta = System.getProperty("user.home");
PdfWriter.getInstance(documento, new FileOutputStream(ruta +"/Desktop/Reporte_Alumnos.pdf"));
documento.open();
PdfPTable tabla = new PdfPTable(6);
tabla.addCell("ID");
tabla.addCell("Nombre:");
tabla.addCell("Apellido:");
tabla.addCell("Edad:");
tabla.addCell("Curso:");
tabla.addCell("Nota:");
try {
Conexion cn2 = new Conexion();
Connection leer = cn2.conectar();
PreparedStatement pst = leer.prepareStatement("select * from datos");
ResultSet rs = pst.executeQuery();
if (rs.next()) {
do {
tabla.addCell(rs.getString(1));
tabla.addCell(rs.getString(2));
tabla.addCell(rs.getString(3));
tabla.addCell(rs.getString(4));
tabla.addCell(rs.getString(5));
tabla.addCell(rs.getString(6));
}while (rs.next()); {
documento.add(tabla);
}
}
} catch (DocumentException | SQLException e) {
}
documento.close();
JOptionPane.showMessageDialog(null,"Se Exporto Correctamente...");
} catch (DocumentException | FileNotFoundException e) {
}
}//GEN-LAST:event_export_pdfActionPerformed
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Ventana.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Ventana().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel aviso_Registro;
private javax.swing.JButton export_pdf;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenu jMenu5;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JPopupMenu.Separator jSeparator1;
private javax.swing.JButton mostrar_Registro;
private javax.swing.JButton registrar;
private javax.swing.JTable tabla_Alumnos;
private javax.swing.JTextField txt_Apellido;
private javax.swing.JTextField txt_Curso;
private javax.swing.JTextField txt_Edad;
private javax.swing.JTextField txt_Nombre;
private javax.swing.JTextField txt_Nota;
// End of variables declaration//GEN-END:variables
}
| 47.123596 | 175 | 0.59547 |
4b5a152f7aae321b470b453293baf4376076472c | 2,823 | /*
# Copyright © 2021 Argela Technologies
#
# 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 tr.com.argela.nfv.onap.serviceManager.onap.rest.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.List;
/**
*
* @author Nebi Volkan UNLENEN(unlenen@gmail.com)
*/
public class VNF {
String id;
String name;
String type;
String lineOfBusiness;
String platform;
String reqId;
String reqUrl;
VF vf;
Tenant tenant;
@JsonIgnore
ServiceInstance serviceInstance;
List<VFModule> vfModules;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLineOfBusiness() {
return lineOfBusiness;
}
public void setLineOfBusiness(String lineOfBusiness) {
this.lineOfBusiness = lineOfBusiness;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public String getReqId() {
return reqId;
}
public void setReqId(String reqId) {
this.reqId = reqId;
}
public String getReqUrl() {
return reqUrl;
}
public void setReqUrl(String reqUrl) {
this.reqUrl = reqUrl;
}
public VF getVf() {
return vf;
}
public void setVf(VF vf) {
this.vf = vf;
}
public Tenant getTenant() {
return tenant;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
public ServiceInstance getServiceInstance() {
return serviceInstance;
}
public void setServiceInstance(ServiceInstance serviceInstance) {
this.serviceInstance = serviceInstance;
}
public List<VFModule> getVfModules() {
return vfModules;
}
public void setVfModules(List<VFModule> vfModules) {
this.vfModules = vfModules;
}
@Override
public String toString() {
return "VNF{" + "id=" + id + ", name=" + name + '}';
}
}
| 20.605839 | 74 | 0.630889 |
0bb132abddc1940d861798dc6b13ce289b2fa3a6 | 489 | package com.keimons.deepjson.test.verification;
import com.keimons.deepjson.test.AssertUtil;
import org.junit.jupiter.api.Test;
/**
* 栈深验证
*
* @author houyn[monkey@keimons.com]
* @version 1.0
* @since 1.7
**/
public class ThreadStackSizeTest {
@Test
public void test() {
try {
test();
} catch (Error error) {
AssertUtil.assertEquals("异常捕获失败", StackOverflowError.class, error.getClass());
AssertUtil.assertTrue("栈深错误", error.getStackTrace().length == 1024);
}
}
} | 20.375 | 81 | 0.695297 |
2a6095fd4891ed825927d8e6ed47dc89f2516f60 | 1,705 | package org.openxava.web.editors;
import static org.openxava.jpa.XPersistence.*;
import java.util.*;
import javax.persistence.*;
/**
* An implementation of {@link IFilePersistor} <p>
*
* @author Jeromy Altuna
*/
public class JPAFilePersistor implements IFilePersistor {
/**
* @see org.openxava.web.editors.IFilePersistor#save(AttachedFile)
*/
@Override
public void save(AttachedFile file) {
getManager().persist(file);
commit();
}
/**
* @see org.openxava.web.editors.IFilePersistor#remove(String)
*/
@Override
public void remove(String id) {
AttachedFile file = getManager().find(AttachedFile.class, id);
if (file == null) return;
getManager().remove(file);
commit();
}
/**
* @see org.openxava.web.editors.IFilePersistor#removeLibrary(String)
*/
@Override
public void removeLibrary(String libraryId) {
Query query = getManager().createQuery("delete from AttachedFile f where "
+ "f.libraryId = :libraryId");
query.setParameter("libraryId", libraryId);
query.executeUpdate();
commit();
}
/**
* @see org.openxava.web.editors.IFilePersistor#findLibrary(String)
*/
@Override
public Collection<AttachedFile> findLibrary(String libraryId) {
TypedQuery<AttachedFile> query = getManager().createQuery(
"from AttachedFile f " +
"where f.libraryId = :libraryId",
AttachedFile.class);
query.setParameter("libraryId", libraryId);
return query.getResultList();
}
/**
* @see org.openxava.web.editors.IFilePersistor#find(String)
*/
@Override
public AttachedFile find(String id) {
AttachedFile file = getManager().find(AttachedFile.class, id);
commit();
return file;
}
}
| 24.014085 | 76 | 0.687977 |
3c9cc285f1155fa89f793d07a6c5ac3ee1261b2b | 371 | package es.ftoribio.dam;
import es.ftoribio.dam.models.Biblioteca;
import es.ftoribio.dam.utils.Menu;
public class Main {
public static void main(String[] args){
Biblioteca biblioteca = Biblioteca.getInstance();
int option;
do {
option= Menu.optionMenu();
biblioteca.menu(option);
}while(option!=5);
}
}
| 21.823529 | 57 | 0.625337 |
7da4ef798ef7b2c961f82e4d2bdc2e411a1d7ee5 | 672 | package org.cyclops.integrateddynamics.capability.networkelementprovider;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.cyclops.integrateddynamics.api.network.INetworkElement;
import org.cyclops.integrateddynamics.api.network.INetworkElementProvider;
import java.util.Collection;
import java.util.Collections;
/**
* An dummy network element provider implementation.
* @author rubensworks
*/
public class NetworkElementProviderEmpty implements INetworkElementProvider {
@Override
public Collection<INetworkElement> createNetworkElements(World world, BlockPos blockPos) {
return Collections.emptyList();
}
}
| 32 | 94 | 0.813988 |
e3e90735a8c3c04ac0cfafb501e0ddb8a3adc046 | 1,851 | /*******************************************************************************
* Copyright 2014 Rafael Garcia Moreno.
*
* 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.bladecoder.engine.actions;
import com.bladecoder.engine.model.SpriteActor;
import com.bladecoder.engine.model.VerbRunner;
import com.bladecoder.engine.model.World;
import com.bladecoder.engine.spine.SpineRenderer;
import com.bladecoder.engine.util.EngineLogger;
@ActionDescription("ONLY FOR SPINE ACTORS: Sets a Skin.")
public class SpineSkinAction implements Action {
@ActionPropertyDescription("The target actor")
@ActionProperty(required = true)
private SceneActorRef actor;
@ActionProperty(required = false)
@ActionPropertyDescription("The Skin. Empty to clear the skin.")
private String skin;
private World w;
@Override
public void init(World w) {
this.w = w;
}
@Override
public boolean run(VerbRunner cb) {
SpriteActor a = (SpriteActor) actor.getActor(w);
if(a instanceof SpriteActor && a.getRenderer() instanceof SpineRenderer) {
SpineRenderer r = (SpineRenderer) a.getRenderer();
r.setSkin(skin);
} else {
EngineLogger.error("SpineSecondaryAnimation: The actor renderer has to be of Spine type.");
}
return false;
}
}
| 31.913793 | 94 | 0.686116 |
53f1ca32422208b6efc16cf369f9e76bc3e45f77 | 175 | package test;
import java.util.List;
public class UnusedImport111113 {
public static void main() {
System.out.println(List[].class.getName());
}
}
| 14.583333 | 51 | 0.628571 |
d91425a3beab0f4d83c22ead3f343ab6b70a1e85 | 495 | package com.giraone.samples.pmspoc1.boundary.dto;
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
import org.mapstruct.factory.Mappers;
import com.giraone.samples.pmspoc1.entity.CostCenter;
@Mapper
public interface CostCenterMapper
{
CostCenterMapper INSTANCE = Mappers.getMapper(CostCenterMapper.class);
void updateDtoFromEntity(CostCenter entity, @MappingTarget CostCenterDTO dto);
void updateEntityFromDto(CostCenterDTO dto, @MappingTarget CostCenter entity);
} | 30.9375 | 82 | 0.826263 |
ebfdfb6d58e3226b898418f0a94c00f95fd1e9e1 | 5,121 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.miwok;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class PhrasesFragment extends Fragment implements AdapterView.OnItemClickListener, MediaPlayer.OnCompletionListener {
private static final String TAG = "PhrasesFragment";
private MediaPlayer mMediaPlayer;
final ArrayList<Word> words = new ArrayList<Word>();
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.word_list, container, false);
//Create a list of words
words.add(new Word("Where are you going?\n" +
"\n", "minto wuksus", R.raw.phrase_where_are_you_going));
words.add(new Word("What is your name?\n" +
"\n", "tinnә oyaase'nә", R.raw.phrase_what_is_your_name));
words.add(new Word("My name is...\n" +
"\n", "oyaaset...", R.raw.phrase_my_name_is));
words.add(new Word("How are you feeling?\n" +
"\n", "michәksәs?", R.raw.phrase_how_are_you_feeling));
words.add(new Word("I’m feeling good.\n" +
"\n", "kuchi achit", R.raw.phrase_im_feeling_good));
words.add(new Word("Are you coming?\n" +
"\n", "әәnәs'aa?", R.raw.phrase_are_you_coming));
words.add(new Word("Yes, I’m coming.\n" +
"\n", "hәә’ әәnәm", R.raw.phrase_yes_im_coming));
words.add(new Word("I’m coming.\n" +
"\n", "әәnәm", R.raw.phrase_im_coming));
words.add(new Word("Let’s go.\n" +
"\n", "yoowutis", R.raw.phrase_lets_go));
words.add(new Word("Come here.\n" +
"\n", "әnni'nem", R.raw.phrase_come_here));
// Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
// adapter knows how to create layouts for each item in the list.
WordAdapter adapter = new WordAdapter(getActivity(), words, R.color.category_phrases);
// Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
// There should be a {@link ListView} with the view ID called list, which is declared in the
// word_list.xml file.
ListView listView = view.findViewById(R.id.list);
// Make the {@link ListView} use the {@link ArrayAdapter} we created above, so that the
// {@link ListView} will display list items for each {@link Word} in the list.
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
return view;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
releaseMediaPlayer();
Word current = words.get(position);
Log.d(TAG, "onItemClick: " + current);
mMediaPlayer = MediaPlayer.create(getActivity(), current.getAudioResourceId());
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(this);
}
@Override
public void onStop() {
super.onStop();
// When the activity is stopped, release the media player resources because we won't be playing any more sounds
releaseMediaPlayer();
}
/**
* Clean up the media player by releasing its resources.
*/
private void releaseMediaPlayer() {
// If the media player is not null, then it may be currently playing a sound.
if (mMediaPlayer != null) {
// Regardless of the current state of the media player, release its resources
// because we no longer need it.
mMediaPlayer.release();
// Set the media player back to null. For our code, we've decided that
// setting the media player to null is an easy way to tell that the media player
// is not configured to play an audio file at the moment.
mMediaPlayer = null;
}
}
@Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
} | 40.322835 | 132 | 0.658465 |
79d6889ab452fde2da98edc803fac3c002a7ddae | 1,541 | package Samples;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.Servo;
/**
* Created by Black Tigers on 29/12/2017.
*/
@TeleOp(name="servoTest", group="")
@Disabled
public class testservo extends OpMode {
Servo servo;
double position=0.4;
@Override
public void init() {
servo=hardwareMap.get(Servo.class,"glyphsArm");
servo.setPosition(0.2);
}
@Override
public void loop() {
boolean up = gamepad1.y;
boolean down = gamepad1.a;
if(up){
servo.setPosition(0.7);
}
else if(down)
{
servo.setPosition(0.2);
}
else if(gamepad1.left_bumper){
servo.setPosition(0.9);
}
// if(up) {
// if (position < 0.8) {
//// position = 0.8;
// position += 0.1;
// }
// telemetry.addData("incresment", position);
//// servo.setPosition(position);
// }
// else if(down) {
//
//
// if (position > 0.2) {
//// position = 0.2;
// position -= 0.1;
// }
// telemetry.addData("incresment", position);
//// servo.setPosition(position);
// }
// servo.setPosition(position);
telemetry.addData("position", servo.getPosition());
telemetry.update();
}
}
| 24.078125 | 59 | 0.532771 |
cfe12349587d2cfc5686a826c4640849429f4526 | 208 | package edu.uml.studentname.stocktrader;
/**
* Client code for the StockService application.
*/
public class StockTraderApp {
public static void main(String[] args) {
// write your code here
}
}
| 17.333333 | 48 | 0.701923 |
c3d749d7ad96b0f42475dba61ed3a3574c795646 | 1,935 | package de.fxworld.basel.ui;
import java.util.List;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.ui.Grid;
import de.fxworld.basel.api.IBaselUserService;
import de.fxworld.basel.api.IGroup;
import de.fxworld.basel.api.IUser;
import de.fxworld.basel.data.IUserRepository;
@SpringView(name = UserListView.VIEW_NAME)
public class UserListView extends EntityView<IUser> {
private static final long serialVersionUID = 1633058377572911134L;
private static final Logger log = LoggerFactory.getLogger(UserListView.class);
public static final String VIEW_NAME = "users";
protected IBaselUserService service;
protected IUserRepository repo;
public UserListView(@Autowired IBaselUserService service, @Autowired IUserRepository repo) {
super(IUser.class, new UserForm(service));
this.service = service;
this.repo = repo;
setSaveHandler(u -> service.saveUser(u));
}
@Override
protected void addColumns(Grid<IUser> grid) {
grid.addColumn(IUser::getName).setId("name").setCaption("name");
grid.addColumn(IUser::getFirstName).setId("firstName").setCaption("first name");
grid.addColumn(IUser::getLastName).setId("lastName").setCaption("last name");
grid.addColumn(IUser::getEmail).setId("email").setCaption("e-mail");
grid.addColumn(IUser::getGroups).setId("groups").setCaption("groups");
grid.addColumn(IUser::getRoles).setId("roles").setCaption("roles");
}
@Override
protected List<IUser> getEntities() {
List<IUser> result = service.getUsers();
return result;
}
@Override
protected IUser createNewEntity() {
return service.createUser(null);
}
@Override
protected void deleteEntity(IUser entity) {
service.deleteUser(entity);
}
}
| 28.043478 | 94 | 0.73385 |
15f79847c99a3cb9bad492ff92d0dde10982bac2 | 1,790 | /*
* Copyright 2019 WeBank
* 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.webank.wedatasphere.dss.framework.project.entity.request;
import com.webank.wedatasphere.dss.framework.project.entity.vo.LabelRouteVo;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
@XmlRootElement
public class OrchestratorDeleteRequest {
@NotNull(message = "id不能为空")
private Long id;
@NotNull(message = "workspaceId不能为空")
private Long workspaceId;
@NotNull(message = "工程id不能为空")
private Long projectId;
/**
* dssLabels是通过前端进行传入的,主要是用来进行当前的环境信息
*/
private LabelRouteVo labels;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getWorkspaceId() {
return workspaceId;
}
public void setWorkspaceId(Long workspaceId) {
this.workspaceId = workspaceId;
}
public Long getProjectId() {
return projectId;
}
public void setProjectId(Long projectId) {
this.projectId = projectId;
}
public LabelRouteVo getLabels() {
return labels;
}
public void setLabels(LabelRouteVo labels) {
this.labels = labels;
}
}
| 23.866667 | 76 | 0.69162 |
1fdc9b94a3846dcfb36ca31c2d50d3d282c90ae8 | 2,987 | /*
* Copyright 2017 David Karnok
*
* 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 hu.akarnokd.reactive4javaflow.impl.operators;
import hu.akarnokd.reactive4javaflow.*;
import hu.akarnokd.reactive4javaflow.functionals.AutoDisposable;
import hu.akarnokd.reactive4javaflow.processors.*;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
import static org.junit.Assert.*;
public class FolyamBlockingStreamTest {
@Test
public void normal() {
List<Integer> list = Folyam.range(1, 5)
.blockingStream()
.limit(3)
.collect(Collectors.toList());
assertEquals(Arrays.asList(1, 2, 3), list);
}
@Test
public void normal2() {
List<Integer> list = Folyam.range(1, 5)
.blockingStream(1)
.limit(3)
.collect(Collectors.toList());
assertEquals(Arrays.asList(1, 2, 3), list);
}
@Test(timeout = 1000)
public void asyncSupplied() throws Exception {
DirectProcessor<Integer> dp = new DirectProcessor<>();
CountDownLatch cdl = new CountDownLatch(1);
AutoDisposable d = SchedulerServices.single().schedule(() -> {
while (!dp.hasSubscribers()) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
cdl.countDown();
return;
}
}
for (int i = 1; i < 6; i++) {
if (!dp.tryOnNext(i)) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
cdl.countDown();
return;
}
}
}
while (dp.hasSubscribers()) {
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
cdl.countDown();
return;
}
}
cdl.countDown();
});
try (d) {
try (Stream<Integer> st = dp.blockingStream()
.limit(3)) {
List<Integer> list = st
.collect(Collectors.toList());
assertEquals(Arrays.asList(1, 2, 3), list);
}
assertTrue(cdl.await(5, TimeUnit.SECONDS));
}
}
}
| 29.574257 | 75 | 0.531637 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.