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
70bace1da099bd6bbaeab521f56ba4fe31bda40a
1,172
import io.github.bonigarcia.wdm.WebDriverManager; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import static org.junit.Assert.*; public class AcademyTest { @Test // Il test ha lo scopo di verificare la corretta partenza dell'applicazione WordPress, verificando se è presente nella title bar la stringa WordPress public void wordPressTest() throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./resources/mac/chromedriver"); ChromeOptions ChromeOptions = new ChromeOptions(); //Opzioni inserite per lanciare il Browser Chrome in modalità senza interfaccia grafica (in quanto il server Jenkins dove viene lanciato non ha l'interfaccia grafica ChromeOptions.addArguments("--headless", "window-size=1024,768", "--no-sandbox"); WebDriver driver = new ChromeDriver(ChromeOptions); driver.get("http://54.74.203.183:8080/"); Thread.sleep(3000); System.out.println (driver.getTitle()); assertTrue(driver.getTitle().contains("WordPress")); driver.quit(); } }
43.407407
167
0.761092
c1c8e0bd08d97ba260e29fec25cc429b6b3b7f42
5,935
package org.apache.fineract.client.services; import org.apache.fineract.client.ApiClient; import org.apache.fineract.client.models.DateParam; import org.apache.fineract.client.models.FormDataContentDisposition; import org.apache.fineract.client.models.JournalEntryCommand; import org.apache.fineract.client.models.JournalEntryData; import org.apache.fineract.client.models.PostJournalEntriesResponse; import org.apache.fineract.client.models.PostJournalEntriesTransactionIdRequest; import org.apache.fineract.client.models.PostJournalEntriesTransactionIdResponse; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for JournalEntriesApi */ public class JournalEntriesApiTest { private JournalEntriesApi api; @Before public void setup() { api = new ApiClient().createService(JournalEntriesApi.class); } /** * Create \&quot;Balanced\&quot; Journal Entries * * Note: A Balanced (simple) Journal entry would have atleast one \&quot;Debit\&quot; and one \&quot;Credit\&quot; entry whose amounts are equal Compound Journal entries may have \&quot;n\&quot; debits and \&quot;m\&quot; credits where both \&quot;m\&quot; and \&quot;n\&quot; are greater than 0 and the net sum or all debits and credits are equal Mandatory Fields officeId, transactionDate credits- glAccountId, amount, comments debits- glAccountId, amount, comments Optional Fields paymentTypeId, accountNumber, checkNumber, routingCode, receiptNumber, bankNumber */ @Test public void createGLJournalEntryTest() { JournalEntryCommand body = null; String command = null; // PostJournalEntriesResponse response = api.createGLJournalEntry(body, command); // TODO: test validations } /** * Update Running balances for Journal Entries * * This API calculates the running balances for office. If office ID not provided this API calculates running balances for all offices. Mandatory Fields officeId */ @Test public void createReversalJournalEntryTest() { String transactionId = null; PostJournalEntriesTransactionIdRequest body = null; String command = null; // PostJournalEntriesTransactionIdResponse response = api.createReversalJournalEntry(transactionId, body, command); // TODO: test validations } /** * * * */ @Test public void getJournalEntriesTemplateTest() { Long officeId = null; String dateFormat = null; // Void response = api.getJournalEntriesTemplate(officeId, dateFormat); // TODO: test validations } /** * * * */ @Test public void postJournalEntriesTemplateTest() { FormDataContentDisposition file = null; String locale = null; String dateFormat = null; // String response = api.postJournalEntriesTemplate(file, locale, dateFormat); // TODO: test validations } /** * Retrieve a single Entry * * Example Requests: journalentries/1 journalentries/1?fields&#x3D;officeName,glAccountId,entryType,amount journalentries/1?runningBalance&#x3D;true journalentries/1?transactionDetails&#x3D;true */ @Test public void retreiveJournalEntryByIdTest() { Long journalEntryId = null; Boolean runningBalance = null; Boolean transactionDetails = null; // JournalEntryData response = api.retreiveJournalEntryById(journalEntryId, runningBalance, transactionDetails); // TODO: test validations } /** * List Journal Entries * * The list capability of journal entries can support pagination and sorting. Example Requests: journalentries journalentries?transactionId&#x3D;PB37X8Y21EQUY4S journalentries?officeId&#x3D;1&amp;manualEntriesOnly&#x3D;true&amp;fromDate&#x3D;1 July 2013&amp;toDate&#x3D;15 July 2013&amp;dateFormat&#x3D;dd MMMM yyyy&amp;locale&#x3D;en journalentries?fields&#x3D;officeName,glAccountName,transactionDate journalentries?offset&#x3D;10&amp;limit&#x3D;50 journalentries?orderBy&#x3D;transactionId&amp;sortOrder&#x3D;DESC journalentries?runningBalance&#x3D;true journalentries?transactionDetails&#x3D;true journalentries?loanId&#x3D;12 journalentries?savingsId&#x3D;24 */ @Test public void retrieveAll1Test() { Long officeId = null; Long glAccountId = null; Boolean manualEntriesOnly = null; DateParam fromDate = null; DateParam toDate = null; String transactionId = null; Integer entityType = null; Integer offset = null; Integer limit = null; String orderBy = null; String sortOrder = null; String locale = null; String dateFormat = null; Long loanId = null; Long savingsId = null; Boolean runningBalance = null; Boolean transactionDetails = null; // List<JournalEntryData> response = api.retrieveAll1(officeId, glAccountId, manualEntriesOnly, fromDate, toDate, transactionId, entityType, offset, limit, orderBy, sortOrder, locale, dateFormat, loanId, savingsId, runningBalance, transactionDetails); // TODO: test validations } /** * * * */ @Test public void retrieveJournalEntriesTest() { Integer offset = null; Integer limit = null; Long entryId = null; // String response = api.retrieveJournalEntries(offset, limit, entryId); // TODO: test validations } /** * * * */ @Test public void retrieveOpeningBalanceTest() { Long officeId = null; String currencyCode = null; // String response = api.retrieveOpeningBalance(officeId, currencyCode); // TODO: test validations } }
36.411043
678
0.690143
debc711052cc3e2ed47783148983cffc62826760
2,067
package us.dot.its.jpo.ode.plugin.j2735; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class J2735LaneAttributesTest { @Test public void testDirectionalUseGetterSetter() { J2735LaneAttributes laneAttributes = new J2735LaneAttributes(); J2735BitString directionalUse = new J2735BitString(); char[] chars = "01".toCharArray(); for (char i = 0; i < chars.length; i++) { if (i >= J2735LaneDirection.values().length) { break; } String bitName = J2735LaneDirection.values()[i].name(); Boolean bitStatus = (chars[i] == '1'); directionalUse.put(bitName, bitStatus); } laneAttributes.setDirectionalUse(directionalUse); assertEquals(laneAttributes.getDirectionalUse(), directionalUse); } @Test public void testShareWithGetterSetter() { J2735LaneAttributes laneAttributes = new J2735LaneAttributes(); J2735BitString shareWith = new J2735BitString(); char[] chars = "1000000000".toCharArray(); for (char i = 0; i < chars.length; i++) { if (i >= J2735LaneSharing.values().length) { break; } String bitName = J2735LaneSharing.values()[i].name(); Boolean bitStatus = (chars[i] == '1'); shareWith.put(bitName, bitStatus); } laneAttributes.setShareWith(shareWith); assertEquals(laneAttributes.getShareWith(), shareWith); } @Test public void testLaneTypeGetterSetter() { J2735LaneAttributes laneAttributes = new J2735LaneAttributes(); J2735LaneTypeAttributes laneTypeAttributes = new J2735LaneTypeAttributes(); J2735BitString vehicle = new J2735BitString(); char[] chars = "00000100".toCharArray(); for (char i = 0; i < chars.length; i++) { if (i >= J2735LaneAttributesVehicle.values().length) { break; } String bitName = J2735LaneAttributesVehicle.values()[i].name(); Boolean bitStatus = (chars[i] == '1'); vehicle.put(bitName, bitStatus); } laneTypeAttributes.setVehicle(vehicle); laneAttributes.setLaneType(laneTypeAttributes); assertEquals(laneAttributes.getLaneType().getVehicle(), vehicle); } }
29.112676
77
0.721819
61562fa7d115a85bceb0ee9b089791462e938c21
3,432
package de.bitnoise.sonferenz.web.pages.conference; import org.apache.wicket.extensions.markup.html.repeater.data.table.DefaultDataTable; import org.apache.wicket.extensions.markup.html.repeater.data.table.ISortableDataProvider; import org.apache.wicket.extensions.markup.html.repeater.util.SortParam; import org.apache.wicket.injection.web.InjectorHolder; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.spring.injection.annot.SpringBean; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; import de.bitnoise.sonferenz.facade.UiFacade; import de.bitnoise.sonferenz.model.ConferenceModel; import de.bitnoise.sonferenz.web.component.SortableServiceDataProvider; import de.bitnoise.sonferenz.web.component.TableBuilder; import de.bitnoise.sonferenz.web.pages.conference.action.AddConference; import de.bitnoise.sonferenz.web.pages.conference.action.EditConference; import de.bitnoise.sonferenz.web.pages.conference.table.ConferenceListItem; import de.bitnoise.sonferenz.web.toolbar.AddToolbarWithButton; public class ListConferencesPanel extends Panel { @SpringBean private UiFacade facade; public ListConferencesPanel(String id) { super(id); InjectorHolder.getInjector().inject(this); } @Override protected void onInitialize() { super.onInitialize(); TableBuilder<ConferenceListItem> builder = new TableBuilder<ConferenceListItem>("conference") { { addColumn(new Column() { { setTitle("Aktiv"); setModelProperty("aktiv"); } }); addColumn(new Column() { { setTitle("Status"); setModelProperty("state"); sortable(); } }); addColumn(new Column() { { setTitle("Name"); setModelProperty("shortName"); sortable(); action(new EditConference()); } }); } }; ISortableDataProvider<ConferenceListItem,SortParam<String>> provider = new SortableServiceDataProvider<ConferenceModel, ConferenceListItem>() { @Override protected ConferenceListItem transferType(ConferenceModel dbObject) { ConferenceListItem item = new ConferenceListItem(); item.shortName = dbObject.getShortName(); item.state = dbObject.getState(); item.aktiv = dbObject.getActive(); item.conference = dbObject; return item; } @Override protected Page<ConferenceModel> getAllItems(PageRequest request) { return facade.getConferences(request); } @Override public long size() { return facade.getAllConferencesCount(); } @Override protected Sort createDefaultSorting() { return new Sort(new Order(Direction.ASC, "shortName")); } }; DefaultDataTable<ConferenceListItem,SortParam<String>> table = new DefaultDataTable<ConferenceListItem,SortParam<String>>( "conferenceTable", builder.getColumns(), provider, 20); AddToolbarWithButton toolbar = new AddToolbarWithButton( "+ create Conference", table, new AddConference()); table.addBottomToolbar(toolbar); add(table); } }
32.377358
126
0.697261
9ee45399414575e001758e94a1fbb6cbb031e3cf
2,668
package omtteam.openmodularlighting.items; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import omtteam.omlib.compatibility.minecraft.CompatItem; import omtteam.openmodularlighting.OpenModularLighting; import omtteam.openmodularlighting.handler.ConfigHandler; import omtteam.openmodularlighting.init.ModItems; import omtteam.openmodularlighting.reference.OMLNames; import omtteam.openmodularlighting.reference.Reference; import javax.annotation.Nonnull; import javax.annotation.ParametersAreNonnullByDefault; import java.util.List; import static omtteam.omlib.util.GeneralUtil.safeLocalize; @SuppressWarnings("deprecation") public class UpgradeMetaItem extends CompatItem { public UpgradeMetaItem() { super(); this.setHasSubtypes(true); this.setCreativeTab(OpenModularLighting.creativeTab); this.setRegistryName(Reference.MOD_ID, OMLNames.Items.upgradeMetaItem); this.setUnlocalizedName(OMLNames.Items.upgradeMetaItem); } public final static String[] subNames = { OMLNames.Items.efficiencyUpgrade, }; @Override @ParametersAreNonnullByDefault public void clGetSubItems(Item itemIn, CreativeTabs tab, List<ItemStack> subItems) { for (int i = 0; i < 1; i++) { subItems.add(new ItemStack(ModItems.upgradeMetaItem, 1, i)); } } @Override @Nonnull @ParametersAreNonnullByDefault public String getUnlocalizedName(ItemStack itemStack) { return "item." + subNames[itemStack.getItemDamage()]; } @Override public int getMetadata(int damage) { return damage; } @SideOnly(Side.CLIENT) @Override @ParametersAreNonnullByDefault public void addInformation(ItemStack stack, EntityPlayer player, List<String> tooltip, boolean isAdvanced) { switch (stack.getMetadata()) { case 0: tooltip.add(""); tooltip.add(TextFormatting.BLUE + safeLocalize("turret.upgrade.label")); tooltip.add(""); tooltip.add("- " + ConfigHandler.getEfficiencyUpgradeBoostPercentage() * 100 + "% " + safeLocalize( "turret.upgrade.eff")); tooltip.add(safeLocalize("turret.upgrade.stacks")); tooltip.add(""); tooltip.add(TextFormatting.DARK_GRAY + safeLocalize("turret.upgrade.eff.flavour")); } } }
35.573333
115
0.707646
4fa8131ffc953d962ad828b0dd1c4be0b0cd7248
753
package com.hcl.appscan.jenkins.plugin.scanners; /** * This class is not intended for normal use. It's sole purpose is for compatibility to convert * older build steps to use the Describable Scanner implementations. */ public class ScannerFactory implements ScannerConstants { /** * Creates a Scanner given a type and target. * @param type * @param target * @return */ public static Scanner getScanner(String type, String target) { Scanner ret = null; switch(type) { case DYNAMIC_ANALYZER: ret = new DynamicAnalyzer(target); break; case MOBILE_ANALYZER: ret = new MobileAnalyzer(target); break; case STATIC_ANALYZER: ret = new StaticAnalyzer(target); break; default: break; } return ret; } }
21.514286
96
0.705179
163de288eaabe4c623908c57ff32706ac9ff0b37
842
import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; /** * Created by Алена on 02.05.2017. */ public class TranscriptWriter extends FileWriter { private HashMap<String, String> MyHashMap; public TranscriptWriter(String fileName) throws IOException { super(fileName); MyHashMap = new HashMap<String, String>(); } public void add(String source, String data) { MyHashMap.put(source, data); } @Override public void write(String s) throws IOException { String c = ""; for(int i = 0; i < s.length(); i++) { if((c = MyHashMap.get(String.valueOf(s.charAt(i)))) != null) super.write(c); else super.write(s.charAt(i)); super.flush(); } } }
24.057143
72
0.593824
f834878c5a94e4ae80dc6b945a3da003c72ffbc7
2,433
/* * 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.cassandra.auth; import com.google.common.base.Objects; /** * Returned from IAuthenticator#authenticate(), represents an authenticated user everywhere internally. */ public class AuthenticatedUser { public static final String ANONYMOUS_USERNAME = "anonymous"; public static final AuthenticatedUser ANONYMOUS_USER = new AuthenticatedUser(ANONYMOUS_USERNAME); private final String name; public AuthenticatedUser(String name) { this.name = name; } public String getName() { return name; } /** * Checks the user's superuser status. * Only a superuser is allowed to perform CREATE USER and DROP USER queries. * Im most cased, though not necessarily, a superuser will have Permission.ALL on every resource * (depends on IAuthorizer implementation). */ public boolean isSuper() { return !isAnonymous() && Auth.isSuperuser(name); } /** * If IAuthenticator doesn't require authentication, this method may return true. */ public boolean isAnonymous() { return this == ANONYMOUS_USER; } @Override public String toString() { return String.format("#<User %s>", name); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof AuthenticatedUser)) return false; AuthenticatedUser u = (AuthenticatedUser) o; return Objects.equal(this.name, u.name); } @Override public int hashCode() { return Objects.hashCode(name); } }
27.965517
103
0.677764
1dbd3e56c5e4a75da2616fcf8c03e5de4c34f075
1,990
package de.melsicon.kafka.sensors.serialization.avromapper; import com.google.errorprone.annotations.Immutable; import de.melsicon.kafka.sensors.avro.SensorState; import de.melsicon.kafka.sensors.avro.SensorStateWithDuration; import de.melsicon.kafka.sensors.serde.SensorStateMapper; import de.melsicon.kafka.sensors.serialization.mapping.MapStructConfig; import org.checkerframework.checker.nullness.qual.PolyNull; import org.mapstruct.Mapper; import org.mapstruct.MappingTarget; @Immutable @Mapper(config = MapStructConfig.class, uses = DurationMapper.class) /* package */ abstract class SpecificDirectMapper implements SensorStateMapper<SensorState, SensorStateWithDuration> { private static SensorState createSensorState() { return new SensorState(); } private static SensorStateWithDuration createSensorStateWithDuration() { return new SensorStateWithDuration(); } @Override public abstract de.melsicon.kafka.sensors.model.@PolyNull SensorState map( @PolyNull SensorState sensorState); @Override public @PolyNull SensorState unmap(de.melsicon.kafka.sensors.model.@PolyNull SensorState from) { if (from == null) { return null; } var to = createSensorState(); unmapto(from, to); return to; } @Override public abstract de.melsicon.kafka.sensors.model.@PolyNull SensorStateWithDuration map2( @PolyNull SensorStateWithDuration sensorState); @Override public @PolyNull SensorStateWithDuration unmap2( de.melsicon.kafka.sensors.model.@PolyNull SensorStateWithDuration from) { if (from == null) { return null; } var to = createSensorStateWithDuration(); unmapto2(from, to); return to; } /* package */ abstract void unmapto( de.melsicon.kafka.sensors.model.SensorState from, @MappingTarget SensorState to); /* package */ abstract void unmapto2( de.melsicon.kafka.sensors.model.SensorStateWithDuration from, @MappingTarget SensorStateWithDuration to); }
33.166667
98
0.762814
965cf5934d5c821768b029550f1c8b4dd14cedbe
1,131
package gr.uom.java.ast.decomposition.cfg.mapping; public abstract class IdBasedGap extends NodeMapping { protected double id1; protected double id2; private boolean advancedMatch; //if an id is equal to zero it means that this id does not exist public IdBasedGap(double id1, double id2, boolean advancedMatch) { this.id1 = id1; this.id2 = id2; this.advancedMatch = advancedMatch; } public double getId1() { return id1; } public double getId2() { return id2; } public boolean isAdvancedMatch() { return advancedMatch; } public int compareTo(IdBasedGap other) { if(this.id1 != 0 && other.id1 != 0) return Double.compare(this.id1, other.id1); if(this.id2 != 0 && other.id2 != 0) return Double.compare(this.id2, other.id2); if(this.id1 != 0 && other.id2 != 0) { double id1 = this.id1; double id2 = other.id2; if(id1 == id2) return -1; else return Double.compare(id1, id2); } if(other.id1 != 0 && this.id2 != 0) { double id2 = other.id1; double id1 = this.id2; if(id1 == id2) return -1; else return Double.compare(id1, id2); } return 0; } }
22.176471
67
0.656941
ba6425d08d0d2c1a2d3410013dedfd75fd0a35b0
16,979
/* * Password Management Servlets (PWM) * http://www.pwm-project.org * * Copyright (c) 2006-2009 Novell, Inc. * Copyright (c) 2009-2021 The PWM 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 password.pwm.http.servlet.configeditor.data; import password.pwm.PwmConstants; import password.pwm.PwmDomain; import password.pwm.PwmEnvironment; import password.pwm.bean.DomainID; import password.pwm.config.AppConfig; import password.pwm.config.PwmSetting; import password.pwm.config.PwmSettingCategory; import password.pwm.config.PwmSettingFlag; import password.pwm.config.PwmSettingScope; import password.pwm.config.PwmSettingSyntax; import password.pwm.config.stored.ConfigSearchMachine; import password.pwm.config.stored.StoredConfigKey; import password.pwm.config.stored.StoredConfiguration; import password.pwm.config.stored.StoredConfigurationUtil; import password.pwm.config.value.StoredValue; import password.pwm.http.servlet.configeditor.DomainManageMode; import password.pwm.i18n.Config; import password.pwm.i18n.PwmLocaleBundle; import password.pwm.util.i18n.LocaleHelper; import password.pwm.util.java.JsonUtil; import password.pwm.util.java.StringUtil; import password.pwm.util.java.TimeDuration; import password.pwm.util.logging.PwmLogger; import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; /** * Utility class for generating {@link NavTreeItem}s suitable for display in the * config editor UI. */ public class NavTreeDataMaker { private static final PwmLogger LOGGER = PwmLogger.forClass( NavTreeDataMaker.class ); private static final String ROOT_NODE_ID = "ROOT"; private static final String DISPLAY_TEXT_ID = "DISPLAY_TEXT"; private static final String DISPLAY_TEXT_NAME = "Display Text"; public static List<NavTreeItem> makeNavTreeItems( final PwmDomain pwmDomain, final StoredConfiguration storedConfiguration, final NavTreeSettings navTreeSettings ) { final Instant startTime = Instant.now(); final ArrayList<NavTreeItem> navigationData = new ArrayList<>(); // root node navigationData.add( makeRootNode() ); // add setting nodes navigationData.addAll( makeSettingNavItems( pwmDomain, storedConfiguration, navTreeSettings ) ); // add display text nodes navigationData.addAll( makeDisplayTextNavItems( pwmDomain, storedConfiguration, navTreeSettings ) ); NavTreeDataMaker.moveNavItemToTopOfList( PwmSettingCategory.NOTES.toString(), navigationData ); NavTreeDataMaker.moveNavItemToTopOfList( PwmSettingCategory.TEMPLATES.toString(), navigationData ); LOGGER.trace( () -> "generated " + navigationData.size() + " navTreeItems for display menu with settings" + JsonUtil.serialize( navTreeSettings ), () -> TimeDuration.fromCurrent( startTime ) ); return Collections.unmodifiableList( navigationData ); } private static NavTreeItem makeRootNode() { return NavTreeItem.builder() .id( ROOT_NODE_ID ) .name( ROOT_NODE_ID ) .build(); } private static List<NavTreeItem> makeDisplayTextNavItems( final PwmDomain pwmDomain, final StoredConfiguration storedConfiguration, final NavTreeSettings navTreeSettings ) { final DomainID domainID = navTreeSettings.getDomainManageMode() == DomainManageMode.domain ? pwmDomain.getDomainID() : DomainID.systemId(); return makeDisplayTextNavItemsForDomain( domainID, storedConfiguration, navTreeSettings ); } private static List<NavTreeItem> makeDisplayTextNavItemsForDomain( final DomainID domainID, final StoredConfiguration storedConfiguration, final NavTreeSettings navTreeSettings ) { final ArrayList<NavTreeItem> navigationData = new ArrayList<>(); final int level = navTreeSettings.getLevel(); final boolean modifiedSettingsOnly = navTreeSettings.isModifiedSettingsOnly(); boolean includeDisplayText = false; if ( level >= 1 ) { for ( final PwmLocaleBundle localeBundle : PwmLocaleBundle.values() ) { if ( !localeBundle.isAdminOnly() ) { final List<String> modifiedKeys = modifiedSettingsOnly ? new ArrayList<>( NavTreeDataMaker.determineModifiedDisplayKeysSettings( domainID, localeBundle, storedConfiguration ) ) : Collections.emptyList(); if ( !modifiedSettingsOnly || !modifiedKeys.isEmpty() ) { final List<String> outputKeys = modifiedSettingsOnly ? modifiedKeys : new ArrayList<>( localeBundle.getDisplayKeys() ); Collections.sort( outputKeys ); final NavTreeItem categoryInfo = NavTreeItem.builder() .id( localeBundle.toString() ) .name( localeBundle.getTheClass().getSimpleName() ) .parent( DISPLAY_TEXT_ID ) .type ( NavTreeItem.NavItemType.displayText ) .keys( outputKeys ) .build(); navigationData.add( categoryInfo ); includeDisplayText = true; } } } } if ( includeDisplayText ) { final NavTreeItem categoryInfo = NavTreeItem.builder() .id( DISPLAY_TEXT_ID ) .name( DISPLAY_TEXT_NAME ) .type( NavTreeItem.NavItemType.navigation ) .parent( ROOT_NODE_ID ) .build(); navigationData.add( categoryInfo ); } return Collections.unmodifiableList( navigationData ); } private static List<String> determineModifiedDisplayKeysSettings( final DomainID domainID, final PwmLocaleBundle bundle, final StoredConfiguration storedConfiguration ) { final List<Locale> knownLocales = Collections.unmodifiableList( new AppConfig( storedConfiguration ).getKnownLocales() ); final List<String> modifiedKeys = new ArrayList<>(); for ( final String key : bundle.getDisplayKeys() ) { final Map<String, String> storedBundle = storedConfiguration.readLocaleBundleMap( bundle, key, domainID ); if ( !storedBundle.isEmpty() ) { for ( final Locale locale : knownLocales ) { final ResourceBundle defaultBundle = ResourceBundle.getBundle( bundle.getTheClass().getName(), locale ); final String localeKeyString = PwmConstants.DEFAULT_LOCALE.toString().equals( locale.toString() ) ? "" : locale.toString(); if ( storedBundle.containsKey( localeKeyString ) ) { final String value = storedBundle.get( localeKeyString ); if ( value != null && !value.equals( defaultBundle.getString( key ) ) ) { modifiedKeys.add( key ); } } } } } return Collections.unmodifiableList( modifiedKeys ); } /** * Produces a collection of {@code NavTreeItem}. */ private static List<NavTreeItem> makeSettingNavItems( final PwmDomain pwmDomain, final StoredConfiguration storedConfiguration, final NavTreeSettings navTreeSettings ) { final Locale locale = navTreeSettings.getLocale(); final List<NavTreeItem> navigationData = new ArrayList<>(); for ( final PwmSettingCategory loopCategory : PwmSettingCategory.sortedValues() ) { if ( !loopCategory.hasProfiles() ) { // regular category, so output a standard nav tree item if ( categoryMatcher( pwmDomain, loopCategory, null, storedConfiguration, navTreeSettings ) ) { navigationData.add( navTreeItemForCategory( loopCategory, locale, null ) ); } } else { final List<String> profiles = StoredConfigurationUtil.profilesForCategory( pwmDomain.getDomainID(), loopCategory, storedConfiguration ); if ( loopCategory.isTopLevelProfile() ) { // edit profile option navigationData.add( navTreeItemForCategory( loopCategory, locale, null ) ); { final String editItemName = LocaleHelper.getLocalizedMessage( locale, Config.Label_ProfileListEditMenuItem, null ); final PwmSetting profileSetting = loopCategory.getProfileSetting().orElseThrow( IllegalStateException::new ); final NavTreeItem profileEditorInfo = NavTreeItem.builder() .id( loopCategory.getKey() + "-EDITOR" ) .name( editItemName ) .type( NavTreeItem.NavItemType.profileDefinition ) .profileSetting( profileSetting.getKey() ) .parent( loopCategory.getKey() ) .build(); navigationData.add( profileEditorInfo ); } for ( final String profileId : profiles ) { final NavTreeItem.NavItemType type = !loopCategory.hasChildren() ? NavTreeItem.NavItemType.category : NavTreeItem.NavItemType.navigation; final NavTreeItem profileInfo = navTreeItemForCategory( loopCategory, locale, profileId ).toBuilder() .name( profileId.isEmpty() ? "Default" : profileId ) .id( "profile-" + loopCategory.getKey() + "-" + profileId ) .parent( loopCategory.getKey() ) .type( type ) .build(); navigationData.add( profileInfo ); } } else { for ( final String profileId : profiles ) { if ( categoryMatcher( pwmDomain, loopCategory, profileId, storedConfiguration, navTreeSettings ) ) { navigationData.add( navTreeItemForCategory( loopCategory, locale, profileId ) ); } } } } } return navigationData; } private static NavTreeItem navTreeItemForCategory( final PwmSettingCategory category, final Locale locale, final String profileId ) { final String parent = category.getParent() != null ? ( profileId != null ? "profile-" + category.getParent().getKey() + "-" + profileId : category.getParent().getKey() ) : ROOT_NODE_ID; final NavTreeItem.NavItemType type = !category.hasChildren() && !category.isTopLevelProfile() ? NavTreeItem.NavItemType.category : NavTreeItem.NavItemType.navigation; return NavTreeItem.builder() .id( category.getKey() + ( profileId != null ? "-" + profileId : "" ) ) .name( category.getLabel( locale ) ) .category( category.getKey() ) .parent( parent ) .type( type ) .profile( profileId ) .menuLocation( category.toMenuLocationDebug( profileId, locale ) ) .build(); } private static boolean categoryMatcher( final PwmDomain pwmDomain, final PwmSettingCategory category, final String profile, final StoredConfiguration storedConfiguration, final NavTreeSettings navTreeSettings ) { if ( category == PwmSettingCategory.HTTPS_SERVER ) { if ( !pwmDomain.getPwmApplication().getPwmEnvironment().getFlags().contains( PwmEnvironment.ApplicationFlag.ManageHttps ) ) { return false; } } for ( final PwmSettingCategory childCategory : category.getChildren() ) { if ( categoryMatcher( pwmDomain, childCategory, profile, storedConfiguration, navTreeSettings ) ) { return true; } } for ( final PwmSetting setting : category.getSettings() ) { if ( settingMatcher( pwmDomain.getDomainID(), storedConfiguration, setting, profile, navTreeSettings ) ) { return true; } } return false; } static boolean settingMatcher( final DomainID domainID, final StoredConfiguration storedConfiguration, final PwmSetting setting, final String profileID, final NavTreeSettings navTreeSettings ) { final StoredConfigKey storedConfigKey = StoredConfigKey.forSetting( setting, profileID, domainID ); if ( setting.getSyntax() == PwmSettingSyntax.PROFILE && !setting.isHidden() && setting.getCategory().getParent().isHidden() ) { return true; } final boolean valueIsDefault = StoredConfigurationUtil.isDefaultValue( storedConfiguration, storedConfigKey ); if ( setting.isHidden() && !valueIsDefault ) { return false; } final PwmSettingCategory settingCategory = setting.getCategory(); if ( navTreeSettings.getDomainManageMode() == DomainManageMode.system && settingCategory.getScope() != PwmSettingScope.SYSTEM ) { return false; } else if ( navTreeSettings.getDomainManageMode() == DomainManageMode.domain && settingCategory.getScope() != PwmSettingScope.DOMAIN ) { return false; } if ( navTreeSettings.isModifiedSettingsOnly() && valueIsDefault ) { return false; } final int level = navTreeSettings.getLevel(); if ( setting.getLevel() > level ) { return false; } if ( setting.getFlags().contains( PwmSettingFlag.MultiDomain ) && ( !( new AppConfig( storedConfiguration ).isMultiDomain() ) ) ) { return false; } if ( StringUtil.isEmpty( navTreeSettings.getFilterText() ) ) { return true; } else { final StoredValue storedValue = storedConfiguration.readStoredValue( storedConfigKey ).orElseThrow(); for ( final String term : StringUtil.whitespaceSplit( navTreeSettings.getFilterText() ) ) { if ( ConfigSearchMachine.matchSetting( storedConfiguration, setting, storedValue, term, PwmConstants.DEFAULT_LOCALE ) ) { return true; } } } return false; } private static void moveNavItemToTopOfList( final String categoryID, final List<NavTreeItem> navigationData ) { { // put templates on top NavTreeItem templateEntry = null; for ( final NavTreeItem entry : navigationData ) { if ( categoryID.equals( entry.getId() ) ) { templateEntry = entry; } } if ( templateEntry != null ) { navigationData.remove( templateEntry ); navigationData.add( 0, templateEntry ); } } } }
39.394432
152
0.582543
eb8961461223278e803676332b9236ba8ea866e1
3,777
package us.ihmc.simulationconstructionset.torqueSpeedCurve; import static us.ihmc.robotics.Assert.assertEquals; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class TypicalTorqueSpeedCurveTest { @BeforeEach public void setUp() throws Exception { } @AfterEach public void tearDown() throws Exception { } @Test // timeout=300000 public void testOne() { TypicalTorqueSpeedCurve torqueSpeedCurve = new TypicalTorqueSpeedCurve(); double maxTorque = 100.0; double maxSpeed = 12.0; double maxSpeedAtMaxTorque = 2.0; torqueSpeedCurve.setMaxTorque(maxTorque); torqueSpeedCurve.setMaxSpeed(maxSpeed); torqueSpeedCurve.setMaxSpeedAtMaxTorque(maxSpeedAtMaxTorque); // Test that you should get 0.0 torque at any speed: assertEquals(0.0, torqueSpeedCurve.limitTorque(0.0, 0.0), 1e-7); assertEquals(0.0, torqueSpeedCurve.limitTorque(0.0, 10.0 * maxSpeed), 1e-7); assertEquals(0.0, torqueSpeedCurve.limitTorque(0.0, -10.0 * maxSpeed), 1e-7); // Test at zero speed: assertEquals(maxTorque, torqueSpeedCurve.limitTorque(2.0 * maxTorque, 0.0), 1e-7); assertEquals(-maxTorque, torqueSpeedCurve.limitTorque(-2.0 * maxTorque, 0.0), 1e-7); assertEquals(0.5 * maxTorque, torqueSpeedCurve.limitTorque(0.5 * maxTorque, 0.0), 1e-7); assertEquals(0.5 * maxTorque, torqueSpeedCurve.limitTorque(0.5 * maxTorque, 0.0), 1e-7); // Test at greater than maxSpeed: assertEquals(0.0, torqueSpeedCurve.limitTorque(0.5 * maxTorque, maxSpeed), 1e-7); assertEquals(0.0, torqueSpeedCurve.limitTorque(0.5 * maxTorque, 1.5 * maxSpeed), 1e-7); assertEquals(0.0, torqueSpeedCurve.limitTorque(-0.5 * maxTorque, -maxSpeed), 1e-7); assertEquals(0.0, torqueSpeedCurve.limitTorque(-0.5 * maxTorque, -1.5 * maxSpeed), 1e-7); // Test at opposite signs: assertEquals(0.5 * maxTorque, torqueSpeedCurve.limitTorque(0.5 * maxTorque, -maxSpeed), 1e-7); assertEquals(0.5 * maxTorque, torqueSpeedCurve.limitTorque(0.5 * maxTorque, -10.0 * maxSpeed), 1e-7); assertEquals(-0.5 * maxTorque, torqueSpeedCurve.limitTorque(-0.5 * maxTorque, maxSpeed), 1e-7); assertEquals(-0.5 * maxTorque, torqueSpeedCurve.limitTorque(-0.5 * maxTorque, 10.0 * maxSpeed), 1e-7); // Test below maxSpeedAtMaxTorque assertEquals(maxTorque, torqueSpeedCurve.limitTorque(2.0 * maxTorque, 0.5 * maxSpeedAtMaxTorque), 1e-7); assertEquals(maxTorque, torqueSpeedCurve.limitTorque(maxTorque, 0.5 * maxSpeedAtMaxTorque), 1e-7); assertEquals(0.5 * maxTorque, torqueSpeedCurve.limitTorque(0.5 * maxTorque, 0.5 * maxSpeedAtMaxTorque), 1e-7); assertEquals(-maxTorque, torqueSpeedCurve.limitTorque(-2.0 * maxTorque, -0.5 * maxSpeedAtMaxTorque), 1e-7); assertEquals(-maxTorque, torqueSpeedCurve.limitTorque(-maxTorque, -0.5 * maxSpeedAtMaxTorque), 1e-7); assertEquals(-0.5 * maxTorque, torqueSpeedCurve.limitTorque(-0.5 * maxTorque, -0.5 * maxSpeedAtMaxTorque), 1e-7); // Test on Curve: assertEquals(maxTorque, torqueSpeedCurve.limitTorque(2.0 * maxTorque, maxSpeedAtMaxTorque), 1e-7); assertEquals(0.0, torqueSpeedCurve.limitTorque(2.0 * maxTorque, maxSpeed), 1e-7); assertEquals(0.5 * maxTorque, torqueSpeedCurve.limitTorque(2.0 * maxTorque, (maxSpeed + maxSpeedAtMaxTorque) / 2.0), 1e-7); assertEquals(-maxTorque, torqueSpeedCurve.limitTorque(-2.0 * maxTorque, -maxSpeedAtMaxTorque), 1e-7); assertEquals(-0.0, torqueSpeedCurve.limitTorque(-2.0 * maxTorque, -maxSpeed), 1e-7); assertEquals(-0.5 * maxTorque, torqueSpeedCurve.limitTorque(-2.0 * maxTorque, -(maxSpeed + maxSpeedAtMaxTorque) / 2.0), 1e-7); } }
49.697368
132
0.710617
7e04662c7255e1ba3c2b7c4a33307af818418537
9,620
/* */ package org.realtors.rets.server; import java.io.File; import java.io.FileInputStream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import junit.framework.TestCase; public class IOUtilsTest extends TestCase { /* * SystemUtils.IS_OS_UNIX doesn't detect the * BSD variants as Unix. */ public static final boolean IS_BSD; static { IS_BSD = StringUtils.contains(System.getProperty("os.name"), "BSD"); } public static final String SEP = File.separator; public static final String ROOT_PREFIX; static { if (SystemUtils.IS_OS_UNIX || IS_BSD) ROOT_PREFIX = "/"; else if (SystemUtils.IS_OS_WINDOWS) ROOT_PREFIX = "C:\\"; else ROOT_PREFIX = ""; } public void testFileRootPrefix() { File file = new File(ROOT_PREFIX + "foo"); assertTrue(file.isAbsolute()); } public void testFillByteBuffer() throws IOException { URL resource = getClass().getResource("large-file.txt"); File file = IOUtils.urlToFile(resource); int fileSize = (int) file.length(); // Make sure file is larger than the number of bytes read per read() assertTrue(fileSize > SputteringInputStream.SPUTTERING_SIZE); // Using this special input stream filter, we ensure that the read() // loop is tested. SputteringInputStream stream = new SputteringInputStream(new FileInputStream(file)); // Make buffer 1 byte larger than file to test premature EOF byte[] buffer = new byte[fileSize + 1]; int bytesRead = IOUtils.fillByteBuffer(stream, buffer); assertEquals(fileSize, bytesRead); // There should be more than 2 calls to read(), to make sure the read() // loop is working. Why two? The best case requires 2 reads, one to // read all the data, the second to return -1. assertTrue(stream.getReadCount() > 2); // Check contents byte[] expected = new byte[fileSize + 1]; for (int i = 0; i < fileSize; i++) { expected[i] = (byte) ((i % 10) + '0'); } assertTrue(Arrays.equals(buffer, expected)); } /** * A stream that only reads 10 bytes at a time. */ private static class SputteringInputStream extends FilterInputStream { public SputteringInputStream(InputStream stream) { super(stream); mReadCount = 0; } public int read(byte[] bytes, int off, int len) throws IOException { mReadCount++; if (len > SPUTTERING_SIZE) { len = SPUTTERING_SIZE; } return super.read(bytes, off, len); } public int getReadCount() { return mReadCount; } public static final int SPUTTERING_SIZE = 10; private int mReadCount; } public void testReadString() throws IOException { URL file = getClass().getResource("foo.txt"); String string = IOUtils.readString(file); assertEquals("a\nb\nc\n", string); } public void testReadBytes() throws IOException { URL file = getClass().getResource("foo.txt"); byte[] expected = new byte[]{'a', '\n', 'b', '\n', 'c', '\n'}; byte[] actual = IOUtils.readBytes(file); assertTrue(Arrays.equals(expected, actual)); } public void testReadLines() throws IOException { URL file = getClass().getResource("foo.txt"); List lines = IOUtils.readLines(file); List expected = new ArrayList(); expected.add("a"); expected.add("b"); expected.add("c"); assertEquals(expected, lines); } public void testWriteString() throws IOException { String file = IOUtils.urlToFilename(getClass().getResource("foo.txt")); file = StringUtils.replace(file, "foo.txt", "bar.txt"); String expected = "a\nb\nc\n" + System.currentTimeMillis() + "\n"; IOUtils.writeString(expected, file); assertEquals(expected, IOUtils.readString(file)); } public void testWriteBytes() throws IOException { String file = IOUtils.urlToFilename(getClass().getResource("foo.txt")); file = StringUtils.replace(file, "foo.txt", "bar.txt"); byte[] expected = new byte[10]; Random random = new Random(); random.nextBytes(expected); IOUtils.writeBytes(expected, file); assertTrue(Arrays.equals(expected, IOUtils.readBytes(file))); } public void testListRecursive() throws IOException { String file = IOUtils.urlToFilename(getClass().getResource("foo.txt")); file = StringUtils.replace(file, "foo.txt", "dirTest"); List files = IOUtils.listFilesRecursive(new File(file)); Collections.sort(files); List expected = new ArrayList(); expected.add(new File(file, "a")); expected.add(new File(file, "a/bar.html")); expected.add(new File(file, "b")); expected.add(new File(file, "b/baz.txt")); expected.add(new File(file, "foo.xml")); assertEquals(expected, files); } public void testListRecursiveFilenameFilter() throws IOException { String file = IOUtils.urlToFilename(getClass().getResource("foo.txt")); file = StringUtils.replace(file, "foo.txt", "dirTest"); List files = IOUtils.listFilesRecursive( new File(file), new IOUtils.ExtensionFilter(".html")); Collections.sort(files); List expected = new ArrayList(); expected.add(new File(file, "a/bar.html")); assertEquals(expected, files); } public void testListRecursiveFileFilter() throws IOException { String file = IOUtils.urlToFilename(getClass().getResource("foo.txt")); file = StringUtils.replace(file, "foo.txt", "dirTest"); List files = IOUtils.listFilesRecursive( new File(file), new IOUtils.NotDirectoryFilter()); Collections.sort(files); List expected = new ArrayList(); expected.add(new File(file, "a/bar.html")); expected.add(new File(file, "b/baz.txt")); expected.add(new File(file, "foo.xml")); assertEquals(expected, files); } public void testRelativizeFiles() { File base = new File(ROOT_PREFIX + "root" + SEP + "directory" + SEP); File subDir = new File(ROOT_PREFIX + "root" + SEP + "directory" + SEP + "sub" + SEP + "directory"); File other = new File(ROOT_PREFIX + "some" + SEP + "other" +SEP + "directory"); File relative = IOUtils.relativize(base, subDir); File expected = new File("sub" + SEP + "directory"); assertEquals(expected, relative); relative = IOUtils.relativize(base, other); expected = new File(ROOT_PREFIX + "some" + SEP + "other" + SEP + "directory"); assertEquals(expected, relative); } public void testRelativizeStrings() { String base = "/root/directory/"; String subDir = "/root/directory/sub/directory"; String other = "/some/other/directory"; String relative = IOUtils.relativize(base, subDir); String expected = "sub/directory"; assertEquals(expected, relative); relative = IOUtils.relativize(base, other); String root; if (SystemUtils.IS_OS_UNIX || IS_BSD) { root = "/"; } else if (SystemUtils.IS_OS_WINDOWS) { String [] userDir = StringUtils.split( System.getProperty("user.dir"), ":"); if (userDir != null && userDir[0] != null) { root = "/" + userDir[0] + ":/"; } else { root = "/C:/"; } } else { root = ""; } expected = root + "some/other/directory"; assertEquals(expected, relative); } public void testResolveStrings() { String base = SystemUtils.JAVA_IO_TMPDIR; String subDir = new File("sub" + SEP + "directory").getPath(); String other = new File(ROOT_PREFIX + "some" + SEP +"other" + SEP + "directory").getPath(); String resolved = IOUtils.resolve(base, subDir); String expected = new File(base, "sub" + SEP + "directory").getPath();; assertEquals(expected, resolved); resolved = IOUtils.resolve(base, other); expected = other; assertEquals(expected, resolved); } public void testResolveFiles() { File base = new File(SystemUtils.JAVA_IO_TMPDIR); File subDir = new File("sub" + SEP + "directory"); File other = new File(ROOT_PREFIX + "some" + SEP + "other" + SEP + "directory"); File resolved = IOUtils.resolve(base, subDir); File expected = new File(base, "sub/directory"); assertEquals(expected, resolved); resolved = IOUtils.resolve(base, other); expected = other; assertEquals(expected, resolved); } }
33.172414
79
0.586279
804d53929b111c29c28bf04bcd785843fac31cc8
1,393
package com.themaster.services.impl; import com.themaster.dto.MainLocalitiesDTO; import com.themaster.dto.MainMetBusDTO; import com.themaster.services.SendRequest; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; @Log4j2 @Component public class SendRequestImpl implements SendRequest{ @Value("${met.localitiesUrl}") private String localitiesUrl; @Override public MainMetBusDTO getMetBusRequest(String url){ RestTemplate restTemplate = new RestTemplate(); MainMetBusDTO dto; //I know is a bad practice to catch runtime exceptions and then throw the same exception //but I need to do this to log the error with the CompletableFuture try{ dto = restTemplate.getForObject(url,MainMetBusDTO.class); }catch(RestClientException ex){ log.error("An error occurred while sending the request", ex); throw ex; } return dto; } @Override public MainLocalitiesDTO getLocalities(){ RestTemplate restTemplate = new RestTemplate(); return restTemplate.getForObject(localitiesUrl, MainLocalitiesDTO.class); } }
33.166667
97
0.709261
a56e6fee82c5ab4c7f603ddae8427a96a8799eb7
728
package ramos.jefferson.boot.dto; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; import org.springframework.beans.factory.annotation.Autowired; public class SportDTO implements Serializable { @JsonProperty("id") private long id; @JsonProperty("name") private String name; @Autowired public SportDTO() { } public SportDTO(long id, String name) { this.id = id; this.name = name; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
17.756098
62
0.615385
89b086a540a77556bf45ce41a6dec207dc90aef9
318
package com.pengo.prototype.demo3; import java.io.Serializable; /** * @author pengo * @description: * @date: 2021/2/22 */ public class Student implements Serializable { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
13.25
44
0.663522
4c18acd6df106e6de394bc9f746e4f6861576c17
4,588
package org.apache.lucene.search.spans; /* * 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. */ import java.io.IOException; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.analysis.MockTokenFilter; import org.apache.lucene.analysis.MockTokenizer; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.search.*; import org.apache.lucene.search.similarities.DefaultSimilarity; /******************************************************************************* * Some expanded tests to make sure my patch doesn't break other SpanTermQuery * functionality. * */ public class TestSpansAdvanced2 extends TestSpansAdvanced { IndexSearcher searcher2; IndexReader reader2; /** * Initializes the tests by adding documents to the index. */ @Override public void setUp() throws Exception { super.setUp(); // create test index final RandomIndexWriter writer = new RandomIndexWriter(random(), mDirectory, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random(), MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET)) .setOpenMode(OpenMode.APPEND).setMergePolicy(newLogMergePolicy()) .setSimilarity(new DefaultSimilarity())); addDocument(writer, "A", "Should we, could we, would we?"); addDocument(writer, "B", "It should. Should it?"); addDocument(writer, "C", "It shouldn't."); addDocument(writer, "D", "Should we, should we, should we."); reader2 = writer.getReader(); writer.close(); // re-open the searcher since we added more docs searcher2 = newSearcher(reader2); searcher2.setSimilarity(new DefaultSimilarity()); } @Override public void tearDown() throws Exception { reader2.close(); super.tearDown(); } /** * Verifies that the index has the correct number of documents. */ public void testVerifyIndex() throws Exception { final IndexReader reader = DirectoryReader.open(mDirectory); assertEquals(8, reader.numDocs()); reader.close(); } /** * Tests a single span query that matches multiple documents. */ public void testSingleSpanQuery() throws IOException { final Query spanQuery = new SpanTermQuery(new Term(FIELD_TEXT, "should")); final String[] expectedIds = new String[] {"B", "D", "1", "2", "3", "4", "A"}; final float[] expectedScores = new float[] {0.625f, 0.45927936f, 0.35355338f, 0.35355338f, 0.35355338f, 0.35355338f, 0.26516503f,}; assertHits(searcher2, spanQuery, "single span query", expectedIds, expectedScores); } /** * Tests a single span query that matches multiple documents. */ public void testMultipleDifferentSpanQueries() throws IOException { final Query spanQuery1 = new SpanTermQuery(new Term(FIELD_TEXT, "should")); final Query spanQuery2 = new SpanTermQuery(new Term(FIELD_TEXT, "we")); final BooleanQuery query = new BooleanQuery(); query.add(spanQuery1, BooleanClause.Occur.MUST); query.add(spanQuery2, BooleanClause.Occur.MUST); final String[] expectedIds = new String[] {"D", "A"}; // these values were pre LUCENE-413 // final float[] expectedScores = new float[] { 0.93163157f, 0.20698164f }; final float[] expectedScores = new float[] {1.0191123f, 0.93163157f}; assertHits(searcher2, query, "multiple different span queries", expectedIds, expectedScores); } /** * Tests two span queries. */ @Override public void testBooleanQueryWithSpanQueries() throws IOException { doTestBooleanQueryWithSpanQueries(searcher2, 0.73500174f); } }
37.300813
80
0.701613
e5304699650912ba8806992113ccd422abcc6e96
1,913
package com.etc.entity; public class Sales { private Integer salId; private String title; private Double discount; private int busId; private String content; private int state; private String pubDate; public String getPubDate() { return pubDate; } public void setPubDate(String pubDate) { this.pubDate = pubDate; } public Sales() { // TODO Auto-generated constructor stub } public Sales(Integer salId, String title, Double discount, String content, int state, String pubDate) { super(); this.salId = salId; this.title = title; this.discount = discount; this.content = content; this.state = state; this.pubDate = pubDate; } public Sales(String title, Double discount, int busId, String content, String pubDate) { super(); this.title = title; this.discount = discount; this.busId = busId; this.content = content; this.pubDate = pubDate; } public String getTitle() { return title; } @Override public String toString() { return "Sales [salId=" + salId + ", title=" + title + ", discount=" + discount + ", busId=" + busId + ", content=" + content + ", state=" + state + ", pubDate=" + pubDate + "]"; } public Integer getSalId() { return salId; } public void setSalId(Integer salId) { this.salId = salId; } public void setTitle(String title) { this.title = title; } public Double getDiscount() { return discount; } public void setDiscount(Double discount) { this.discount = discount; } public int getBusId() { return busId; } public void setBusId(int busId) { this.busId = busId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getState() { return state; } public void setState(int state) { this.state = state; } }
19.323232
105
0.63931
d517069b62c97b69f926d8bfb88df02e0b1313e0
11,020
package com.github.autoftp.config; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItems; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import java.io.File; import java.util.ArrayList; import java.util.List; import jftp.client.ClientFactory.ClientType; import jftp.exception.FileConfigurationException; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.joda.time.DateTime; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.InjectMocks; import org.mockito.Mock; public class SettingsProviderTest { private static final String CONFIG_FILE = "build/autoftp.conf"; private static final String INTERVAL = "interval"; private static final String HOST_FILE_DIR = "host.file-dir"; private static final String HOST_PORT = "host.port"; private static final String HOST_TYPE = "host.type"; private static final String HOST_PASSWORD = "host.password"; private static final String HOST_USER = "host.user"; private static final String HOST_NAME = "host.name"; private static final String LAST_RUN = "last-run"; private static final String APP_DOWNLOAD_DIR = "download-dir"; private static final String FILE_FILTER_LIST = "filters.expression"; private static final String MOVE_ENABLED = "move.enabled"; private static final String MOVE_DIRECTORY = "move.directory"; private static final String PUSHBULLET_API_KEY = "pushbullet.api.key"; private static final String PUSHBULLET_NOTIFICATIONS_ENABLED = "pushbullet.notify.enabled"; private static final String THIS_IS_A_DOWNLOAD_DIR = "this/is/a/download/dir"; @InjectMocks private SettingsProvider settingsProvider = new SettingsProvider("build/autoftp.conf"); @Mock private PropertiesConfiguration propertiesConfiguration; @Rule public ExpectedException expectedException = ExpectedException.none(); @Before public void setUp() { initMocks(this); when(propertiesConfiguration.getList(FILE_FILTER_LIST)).thenReturn(initFilterList()); } @Test public void setDownloadDirectoryShouldCallPropertiesConfigurationToSetDownloadDirectory() throws ConfigurationException { settingsProvider.setDownloadDirectory(THIS_IS_A_DOWNLOAD_DIR); verify(propertiesConfiguration).setProperty(APP_DOWNLOAD_DIR, THIS_IS_A_DOWNLOAD_DIR); verify(propertiesConfiguration).save(); } @Test public void ifConfigUnableToSaveThenShouldThrowConfigCorruptedException() throws ConfigurationException { doThrow(new ConfigurationException()).when(propertiesConfiguration).save(); expectedException.expect(FileConfigurationException.class); expectedException.expectMessage(is(equalTo("Unable to save new configuration property."))); settingsProvider.setDownloadDirectory(THIS_IS_A_DOWNLOAD_DIR); } @Test public void setPushbulletNotificationEnabledShouldCallPropertiesConfigurationToSetMoveEnabled() throws ConfigurationException { settingsProvider.setPushbulletNotificationEnabled(true); verify(propertiesConfiguration).setProperty(PUSHBULLET_NOTIFICATIONS_ENABLED, true); verify(propertiesConfiguration).save(); } @Test public void isPushbulletNotificationEnabledShouldReturnValueFromProperties() { when(propertiesConfiguration.getBoolean(PUSHBULLET_NOTIFICATIONS_ENABLED)).thenReturn(true); assertThat(settingsProvider.isPushbulletNotificationEnabled(), is(equalTo(true))); } @Test public void setMoveEnabledShouldCallPropertiesConfigurationToSetMoveEnabled() throws ConfigurationException { settingsProvider.setMoveEnabled(true); verify(propertiesConfiguration).setProperty(MOVE_ENABLED, true); verify(propertiesConfiguration).save(); } @Test public void isMoveEnabledShouldReturnValueFromProperties() { when(propertiesConfiguration.getBoolean(MOVE_ENABLED)).thenReturn(true); assertThat(settingsProvider.isMoveEnabled(), is(equalTo(true))); } @Test public void setMoveDirectoryShouldCallPropertiesConfigurationToSetMoveEnabled() throws ConfigurationException { settingsProvider.setMoveDirectory("dir"); verify(propertiesConfiguration).setProperty(MOVE_DIRECTORY, "dir"); verify(propertiesConfiguration).save(); } @Test public void getMoveDirectoryShouldReturnValueFromProperties() { when(propertiesConfiguration.getString(MOVE_DIRECTORY)).thenReturn("movedir"); assertThat(settingsProvider.getMoveDirectory(), is(equalTo("movedir"))); } @Test public void setPushbulletApiKeyShouldCallPropertiesConfigurationToSetMoveEnabled() throws ConfigurationException { settingsProvider.setPushbulletApiKey("apikey"); verify(propertiesConfiguration).setProperty(PUSHBULLET_API_KEY, "apikey"); verify(propertiesConfiguration).save(); } @Test public void getPushbulletApiKeyShouldReturnValueFromProperties() { when(propertiesConfiguration.getString(PUSHBULLET_API_KEY)).thenReturn("apikey"); assertThat(settingsProvider.getPushbulletApiKey(), is(equalTo("apikey"))); } @Test public void getDownloadDirectoryShouldCalLPropertiesConfigurationToGetDownloadDirectory() { settingsProvider.getDownloadDirectory(); verify(propertiesConfiguration).getString(APP_DOWNLOAD_DIR); } @Test public void getDownloadDirectoryShouldReturnValueFromPropertiesConfiguration() { when(propertiesConfiguration.getString(APP_DOWNLOAD_DIR)).thenReturn(THIS_IS_A_DOWNLOAD_DIR); assertThat(settingsProvider.getDownloadDirectory(), is(equalTo(THIS_IS_A_DOWNLOAD_DIR))); } @Test public void getFilterExpressionsShouldCallPropertiesConfigurationToReturnListOfStrings() { settingsProvider.getFilterExpressions(); verify(propertiesConfiguration).getList(FILE_FILTER_LIST); } @Test public void objectListReturnedFromGetListMethodInPropertiesConfigurationShouldBeConvertedToStringList() { List<String> filters = settingsProvider.getFilterExpressions(); assertThat(filters, hasItems("Filter 1", "Filter 2", "Filter 3")); } @Test public void listSizeReturnedFromGetFilterExpressionsShouldMatchListSizeReturnedFromPropertiesConfiguration() { assertThat(settingsProvider.getFilterExpressions().size(), is(equalTo(3))); } @Test public void setFilterExpressionsShouldTakeInListOfStringsAndCallPropertiesConfigurationsetProperty() { List<String> filters = new ArrayList<String>(); filters.add("New String"); settingsProvider.setFilterExpressions(filters); verify(propertiesConfiguration).setProperty(FILE_FILTER_LIST, filters); } @Test public void setConnectionIntervalShouldCallPropertiesConfiguration() throws ConfigurationException { settingsProvider.setConnectionInterval(5); verify(propertiesConfiguration).setProperty(INTERVAL, 5); verify(propertiesConfiguration).save(); } @Test public void getConnectionIntervalShouldCallPropertiesConfigurationAndReturnValue() { when(propertiesConfiguration.getInt(INTERVAL)).thenReturn(3); assertThat(settingsProvider.getConnectionInterval(), is(equalTo(3))); } @Test public void setFilterExpressionsShouldSaveConfig() throws ConfigurationException { List<String> filters = new ArrayList<String>(); filters.add("New String"); settingsProvider.setFilterExpressions(filters); verify(propertiesConfiguration).save(); } @Test public void setLastRunDateShouldAddNewPropertyToPropertiesConfiguration() throws ConfigurationException { DateTime dateTime = new DateTime(123456789); settingsProvider.setLastRunDate(dateTime); verify(propertiesConfiguration).setProperty(LAST_RUN, 123456789l); verify(propertiesConfiguration).save(); } @Test public void getLastRunDateShouldGetLastRunMillisAndConvertToDateTimeThenReturn() { DateTime dateTime = new DateTime(123456789); when(propertiesConfiguration.getLong(eq(LAST_RUN), anyLong())).thenReturn(123456789l); assertThat(settingsProvider.getLastRunDate(), is(equalTo(dateTime))); } @Test public void getHostConfigShouldCompileMultipleObjectValuesFromConfigIntoHostConfigObject() { when(propertiesConfiguration.getString(HOST_NAME)).thenReturn("hostname"); when(propertiesConfiguration.getString(HOST_USER)).thenReturn("a user"); when(propertiesConfiguration.getString(HOST_PASSWORD)).thenReturn("a password"); when(propertiesConfiguration.getInt(HOST_PORT)).thenReturn(80); when(propertiesConfiguration.getString(HOST_TYPE)).thenReturn("SFTP"); when(propertiesConfiguration.getString(HOST_FILE_DIR)).thenReturn("remote/directory"); HostConfig hostConfig = settingsProvider.getHost(); verify(propertiesConfiguration).getString(HOST_NAME); verify(propertiesConfiguration).getString(HOST_USER); verify(propertiesConfiguration).getString(HOST_PASSWORD); verify(propertiesConfiguration).getString(HOST_TYPE); verify(propertiesConfiguration).getInt(HOST_PORT); verify(propertiesConfiguration).getString(HOST_FILE_DIR); assertThat(hostConfig.getHostname(), is(equalTo("hostname"))); assertThat(hostConfig.getPassword(), is(equalTo("a password"))); assertThat(hostConfig.getUsername(), is(equalTo("a user"))); assertThat(hostConfig.getPort(), is(equalTo(80))); assertThat(hostConfig.getClientType(), is(equalTo(ClientType.SFTP))); assertThat(hostConfig.getFileDirectory(), is(equalTo("remote/directory"))); } @Test public void setHostConfigShouldTakeHostConfigObjectAndWriteToPropertiesForEveryField() throws ConfigurationException { HostConfig config = new HostConfig(); config.setClientType(ClientType.SFTP); config.setHostname("hostname"); config.setPassword("password"); config.setPort(80); config.setUsername("username"); config.setFileDirectory("remote/directory"); settingsProvider.setHost(config); verify(propertiesConfiguration).setProperty(HOST_NAME, "hostname"); verify(propertiesConfiguration).setProperty(HOST_PASSWORD, "password"); verify(propertiesConfiguration).setProperty(HOST_PORT, 80); verify(propertiesConfiguration).setProperty(HOST_TYPE, "SFTP"); verify(propertiesConfiguration).setProperty(HOST_USER, "username"); verify(propertiesConfiguration).setProperty(HOST_FILE_DIR, "remote/directory"); verify(propertiesConfiguration).save(); } @Test public void ifConfigFileDoesNotExistThenConstructorShouldCreateIt() { File file = new File(CONFIG_FILE); file.delete(); new SettingsProvider("build/autoftp.conf"); assertThat(new File(CONFIG_FILE).exists(), is(equalTo(true))); } private List<Object> initFilterList() { List<Object> list = new ArrayList<Object>(); list.add("Filter 1"); list.add("Filter 2"); list.add("Filter 3"); return list; } }
33.495441
128
0.802632
a458cc363a46e6f9777f2d899c7da5c33fcadf9e
2,571
/* * Copyright (C) 2013 Cumulocity GmbH * * 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 c8y.lx.driver; import com.cumulocity.rest.representation.inventory.ManagedObjectRepresentation; import com.cumulocity.rest.representation.measurement.MeasurementRepresentation; import com.cumulocity.sdk.client.Platform; import com.cumulocity.sdk.client.SDKException; import com.cumulocity.sdk.client.measurement.MeasurementApi; import org.joda.time.DateTime; public abstract class MeasurementPollingDriver extends PollingDriver { private MeasurementApi measurements; private MeasurementRepresentation measurementRep = new MeasurementRepresentation(); public MeasurementPollingDriver(String measurementType, String pollingProp, long defaultPollingInterval) { super(measurementType, pollingProp, defaultPollingInterval); measurementRep.setType(measurementType); } @Override public void initialize(Platform platform) throws Exception { super.initialize(platform); this.measurements = platform.getMeasurementApi(); } public void setSource(ManagedObjectRepresentation mo) { measurementRep.setSource(mo); } protected void sendMeasurement(Object measurement) { try { measurementRep.set(measurement); measurementRep.setDateTime(new DateTime()); measurements.create(measurementRep); } catch (SDKException e) { logger.warn("Cannot send measurement", e); } } }
42.85
105
0.744846
817e127717776c5b5bd914ab280383a2652b10eb
5,247
package solar.rpg.shoptopia.data; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Item; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; import solar.rpg.shoptopia.Main; import solar.rpg.shoptopia.player.ShopListener; /** * Showcase model. Contains location, icon, and purchasing information. * Is able to spawn itself and interact with the listeners. * * @author lavuh * @version 1.1 * @since 1.0 */ public class Showcase { private final Boolean RESTRICTED; private final int OWNER_ID; /* Reference to JavaPlugin. */ private Main PLUGIN; /* Unchanging showcase information. */ private PurchaseData BUY_DATA; private PurchaseData SELL_DATA; private Location SHOWCASE_LOCATION; private ItemStack ICON; /* Item drop displayed on showcase. */ private Item SHOWCASE_DROP; /** * Showcase constructor. * * @param x X-location of showcase half-slab. * @param y Y-location of showcase half-slab. * @param z Z-location of showcase half-slab. * @param ICON The item that the showcase will display. * @param BUY_DATA The showcase's buyable item, if any. * @param SELL_DATA The showcase's sellable item, if any. * @param RESTRICTED Whether or not this is a restricted shop. * @param OWNER_ID Owning island's ID. -1 if admin shop. */ public Showcase(Main PLUGIN, int x, int y, int z, ItemStack ICON, PurchaseData BUY_DATA, PurchaseData SELL_DATA, Boolean RESTRICTED, int OWNER_ID, World creationWorld) { this.PLUGIN = PLUGIN; this.ICON = ICON; this.BUY_DATA = BUY_DATA; this.SELL_DATA = SELL_DATA; this.RESTRICTED = RESTRICTED; this.OWNER_ID = OWNER_ID; SHOWCASE_LOCATION = new Location(creationWorld, x, y, z); create(); } /** * Utility method. * Checks if two locations share the same Z and X axis. * * @param l1 The first location. * @param l2 The second location. * @return True if both locations share the same Z and X value. */ public static boolean matchXZ(Location l1, Location l2) { return l1.getBlockX() == l2.getBlockX() && l1.getBlockZ() == l2.getBlockZ(); } /** * Registers the showcase's clickspace with the listener. * Respawns the item drop for the showcase afterwards. * * @see ShopListener */ private void create() { getShopListener().getClickspace().put(getPosition(), this); getShopListener().getClickspace().put(getPosition().clone().subtract(0, 1, 0), this); respawn(); } /** * @return True if this showcase is restricted to donators. */ public boolean isDonatorOnly() { return RESTRICTED; } public void respawn() { World world = SHOWCASE_LOCATION.getWorld(); if (SHOWCASE_DROP != null) { if (SHOWCASE_DROP.isValid() && !SHOWCASE_DROP.isDead()) return; if (!SHOWCASE_LOCATION.getChunk().isLoaded()) return; getShopListener().getExempt().remove(SHOWCASE_DROP); SHOWCASE_DROP.remove(); } SHOWCASE_DROP = world.dropItem(SHOWCASE_LOCATION.clone().add(0.5, 0.505, 0.5), ICON); SHOWCASE_DROP.setVelocity(new Vector(0, -1, 0)); SHOWCASE_DROP.setPickupDelay(9999 * 9999); getShopListener().getExempt().add(SHOWCASE_DROP); } /** * Destroys the item drop associated with this showcase. * Removes information about itself to speed up GC. */ public void destroy() { getShopListener().getExempt().remove(SHOWCASE_DROP); SHOWCASE_DROP.remove(); SHOWCASE_DROP = null; PLUGIN = null; ICON = null; BUY_DATA = null; SELL_DATA = null; SHOWCASE_LOCATION = null; } /** * Showcases can belong to either the admin shop or an island. * There are different (but similar) listener classes for both. * * @return Appropriate shop listener for th is showcase. */ private ShopListener getShopListener() { return isAdminShop() ? PLUGIN.getAdminShopListener() : PLUGIN.getPlayerShopListener(); } /** * @return The showcase's item drop on display. */ public Item getShowcaseDrop() { return SHOWCASE_DROP; } /** * @return True if an admin shop, false if player shop */ public boolean isAdminShop() { return OWNER_ID == -1; } /** * @return The showcase's location. */ public Location getPosition() { return SHOWCASE_LOCATION; } /** * @return True if you can buy from this showcase. */ public boolean canBuy() { return BUY_DATA != null; } /** * @return Data related to buying from this showcase. */ public PurchaseData getBuyData() { return BUY_DATA; } /** * @return True if you can sell to this showcase. */ public boolean canSell() { return SELL_DATA != null; } /** * @return Data related to selling to this showcase. */ public PurchaseData getSellData() { return SELL_DATA; } }
29.8125
173
0.62531
d69911ce9b46e086197341d6cdc6009d437fa216
6,600
/* * Copyright 2014-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.dbflute.intro.app.web.client; import java.util.LinkedHashMap; import java.util.Objects; import java.util.Optional; import javax.annotation.Resource; import org.apache.commons.lang3.StringUtils; import org.dbflute.intro.app.logic.client.ClientPhysicalLogic; import org.dbflute.intro.app.logic.client.ClientReadLogic; import org.dbflute.intro.app.logic.dfprop.TestConnectionLogic; import org.dbflute.intro.app.logic.dfprop.database.DatabaseInfoLogic; import org.dbflute.intro.app.model.client.ClientModel; import org.dbflute.intro.app.model.client.ExtlibFile; import org.dbflute.intro.app.model.client.ProjectInfra; import org.dbflute.intro.app.model.client.basic.BasicInfoMap; import org.dbflute.intro.app.model.client.database.DatabaseInfoMap; import org.dbflute.intro.app.model.client.database.DbConnectionBox; import org.dbflute.intro.app.model.client.database.various.AdditionalSchemaMap; import org.dbflute.intro.app.web.client.ClientCreateBody.ClientPart; import org.dbflute.intro.dbflute.allcommon.CDef.TargetDatabase; import org.dbflute.intro.mylasta.action.IntroMessages; import org.dbflute.optional.OptionalThing; /** * @author jflute (split from large action) (at roppongi japanese) */ public class ClientUpdateAssist { // =================================================================================== // Attribute // ========= @Resource private ClientReadLogic clientReadLogic; @Resource private ClientPhysicalLogic clientPhysicalLogic; @Resource private TestConnectionLogic testConnectionLogic; @Resource private DatabaseInfoLogic databaseInfoLogic; // =================================================================================== // Validation // ========== public void moreValidateCreate(IntroMessages messages, ClientCreateBody clientCreateBody) { String clientName = clientCreateBody.client.projectName; ClientPart client = clientCreateBody.client; if (clientReadLogic.getProjectList().contains(clientName)) { messages.addErrorsWelcomeClientAlreadyExists("projectName", clientName); } TargetDatabase databaseCd = client.databaseCode; if (databaseCd != null && !databaseInfoLogic.isEmbeddedJar(databaseCd) && Objects.isNull(client.jdbcDriver)) { messages.addErrorsDatabaseNeedsJar("database", databaseCd.alias()); } Optional.ofNullable(client.jdbcDriver) .map(driverPart -> driverPart.fileName) .filter(s -> StringUtils.isNotEmpty(s) && !s.endsWith(".jar")) .ifPresent(fileName -> messages.addErrorsDatabaseNeedsJar("jdbcDriver", fileName)); } // =================================================================================== // Mapping // ======= public ClientModel mappingToClientModel(ClientPart clientBody) { return newClientModel(clientBody); } private ClientModel newClientModel(ClientPart clientBody) { ProjectInfra projectInfra = prepareProjectInfra(clientBody); BasicInfoMap basicInfoMap = prepareBasicInfoMap(clientBody); DatabaseInfoMap databaseInfoMap = prepareDatabaseInfoMap(clientBody); ClientModel clientModel = new ClientModel(projectInfra, basicInfoMap, databaseInfoMap); return clientModel; } private ProjectInfra prepareProjectInfra(ClientPart clientBody) { String projectName = clientBody.projectName; if (Objects.isNull(clientBody.jdbcDriver)) { return new ProjectInfra(projectName, clientBody.dbfluteVersion); } ExtlibFile extlibFile = clientPhysicalLogic.createExtlibFile(projectName, clientBody.jdbcDriver.fileName, clientBody.jdbcDriver.data); return new ProjectInfra(projectName, clientBody.dbfluteVersion, extlibFile); } private BasicInfoMap prepareBasicInfoMap(ClientPart clientBody) { return new BasicInfoMap(clientBody.databaseCode, clientBody.languageCode, clientBody.containerCode, clientBody.packageBase); } private DatabaseInfoMap prepareDatabaseInfoMap(ClientPart clientBody) { return OptionalThing.ofNullable(clientBody.mainSchemaSettings, () -> {}).map(databaseBody -> { DbConnectionBox connectionBox = new DbConnectionBox(databaseBody.url, databaseBody.schema, databaseBody.user, databaseBody.password); AdditionalSchemaMap additionalSchemaMap = new AdditionalSchemaMap(new LinkedHashMap<>()); // #pending see the class code return new DatabaseInfoMap(clientBody.jdbcDriverFqcn, connectionBox, additionalSchemaMap); }).orElseThrow(() -> { return new IllegalStateException("Not found the database body: " + clientBody); }); } // =================================================================================== // Assist Logic // ============ public void testConnectionIfPossible(ClientModel clientModel) { String dbfluteVersion = clientModel.getProjectInfra().getDbfluteVersion(); OptionalThing<String> jdbcDriverJarPath = clientModel.getProjectInfra().getJdbcDriverExtlibFile().map(ExtlibFile::getCanonicalPath); DatabaseInfoMap databaseInfoMap = clientModel.getDatabaseInfoMap(); testConnectionLogic.testConnection(dbfluteVersion, jdbcDriverJarPath, databaseInfoMap); } }
51.968504
140
0.634242
a5592ff9f9738769b45bc8b375e7139e945459ba
9,899
/* * (C) Copyright IBM Corp. 2021 * * SPDX-License-Identifier: Apache-2.0 */ package io.github.linuxforhealth.rules.conditions.predicate; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import io.github.linuxforhealth.rules.api.RuleFact; import io.github.linuxforhealth.rules.condition.Condition; import io.github.linuxforhealth.rules.condition.SimpleBiCondition; import io.github.linuxforhealth.rules.condition.SimpleCondition; import io.github.linuxforhealth.rules.condition.variable.SimpleVariable; import io.github.linuxforhealth.rules.fact.ContextValues; import io.github.linuxforhealth.rules.fact.StringValueType; import io.github.linuxforhealth.rules.fact.ValueType; class PredicateForStringTypeTest { @Test public void test_contain_operator_evaluated() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ANY_ACCESSION_NUMBER"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.CONTAINS, "ANY_ACCESSION"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } private ContextValues generateFact(String key, ValueType value) { ContextValues attrs = new ContextValues(); attrs.addValue(key, value); return attrs; } @Test public void test_contain_than_operator_with_invalid_input() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ANY_ACCESSION_NUMBER"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.CONTAINS, 4); Assertions.assertThatIllegalStateException() .isThrownBy(() -> tDicomRuleCondition.evaluate(fact.getData())); } @Test public void test_contain_operator_with_empty_input() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ANY_ACCESSION_NUMBER"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.CONTAINS, ""); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } @Test public void test_equals_operator() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ANY_ACCESSION"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.EQUALS, "ANY_ACCESSION"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } @Test public void test_equals_operator_false() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ANY_ACCESSION_N"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.EQUALS, "ANY_ACCESSION"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isFalse(); } @Test public void test_start_with_operator() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ANY_ACCESSION_N"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.STARTS_WITH, "ANY_ACCESSION"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } @Test public void test_not_start_with_operator_false() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ANY_ACCESSION_N"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.NOT_STARTS_WITH, "ANY_ACCESSION"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isFalse(); } @Test public void test_not_start_with_operator_true() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("TANY_ACCESSION"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.NOT_STARTS_WITH, "ANY_ACCESSION"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } @Test public void test_ends_with_operator() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ANY_ACCESSION"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.ENDS_WITH, "ION"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } @Test public void test_not_ends_with_operator_false_case() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ANY_ACCESSION"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.NOT_ENDS_WITH, "ION"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isFalse(); } @Test public void test_not_ends_with_operator_true_case() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ANY_ACCESSION"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.NOT_ENDS_WITH, "IOG"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } @Test public void test_not_contains_operator_false_case() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ACCESSION_AANY"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.NOT_CONTAINS, "ACCESSION"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isFalse(); } @Test public void test_not_contains_operator_true_case() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("ACCESSION"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.NOT_CONTAINS, "NUM"); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } @Test public void test_in_equal_operator_true_case() { List<String> tModalityList = new ArrayList<String>(); tModalityList.add("CT"); tModalityList.add("US"); tModalityList.add("SR"); RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("CT"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.IN_EQUALS, tModalityList); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } @Test public void test_in_equal_operator_false_case() { List<String> tModalityList = new ArrayList<String>(); tModalityList.add("CT"); tModalityList.add("US"); tModalityList.add("SR"); RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("TCT"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.IN_EQUALS, tModalityList); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isFalse(); } @Test public void test_in_contain_operator_false_case() { List<String> tModalityList = new ArrayList<String>(); tModalityList.add("CT"); tModalityList.add("US"); tModalityList.add("SR"); RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("C"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.IN_CONTAINS, tModalityList); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isFalse(); } @Test public void test_in_contain_operator_true_case() { List<String> tModalityList = new ArrayList<String>(); tModalityList.add("CT"); tModalityList.add("US"); tModalityList.add("SR"); RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("CTR"))); Condition tDicomRuleCondition = new SimpleBiCondition(new SimpleVariable("(0020,1206)"), RuleBiPredicate.IN_CONTAINS, tModalityList); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } @Test public void test_string_is_null_true() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType(null))); Condition tDicomRuleCondition = new SimpleCondition(new SimpleVariable("(0020,1206)"), RulePredicate.IS_NULL); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isTrue(); } @Test public void test_string_is_null() { RuleFact fact = new RuleFact(generateFact("(0020,1206)", new StringValueType("CTR"))); Condition tDicomRuleCondition = new SimpleCondition(new SimpleVariable("(0020,1206)"), RulePredicate.IS_NULL); boolean tConditionEvaluated = tDicomRuleCondition.evaluate(fact.getData()); assertThat(tConditionEvaluated).isFalse(); } }
32.887043
100
0.740176
7e554959c434b8b17c0c18425b6b54f1bf3af50c
1,800
package org.sustudent.cherry.services.user.service; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Service; import org.sustudent.cherry.common.core.exception.CommonException; import org.sustudent.cherry.common.core.model.Page; import org.sustudent.cherry.common.core.service.BaseService; import org.sustudent.cherry.services.user.entity.SysRole; import org.sustudent.cherry.services.user.entity.SysUser; import org.sustudent.cherry.services.user.mapper.SysRoleMapper; /** * @author yiyi.su * @version 1.0.0 * @ClassName SysRoleService.java * @Description SysUserService * @createTime 2019/10/20/ 19:02:00 */ @Service public class SysRoleService extends BaseService<SysRoleMapper, SysRole> { public void findPage(Page<SysRole> page, SysRole sysRole) { mapper.findPage(page, sysRole); } public boolean checkField(SysRole role) { return mapper.checkField(role); } private boolean checkName(Long id, String name) { SysRole role = new SysRole(); role.setId(id); role.setName(name); return checkField(role); } private boolean checkAttribute(Long id, String attribute) { SysRole role = new SysRole(); role.setId(id); role.setAttribute(attribute); return checkField(role); } public SysRole save(SysRole role) { String name = role.getName(); String attribute = role.getAttribute(); if (StringUtils.isAnyBlank(name, attribute)) { throw new CommonException("名称和属性不能为空。"); } if (!checkName(role.getId(), name)) { throw new CommonException("名称已存在。"); } if (!checkAttribute(role.getId(), attribute)) { throw new CommonException("名称已存在。"); } saveOrUpdate(role); return role; } }
28.125
73
0.724444
881e5e1c84a25025b69c9a0ed03a247390b96198
244
package de.tmosebach.slowen.buchhaltung.model; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface DepotRepository extends CrudRepository<Depot, Long> { }
24.4
70
0.844262
72a4b24ef9c0fda49d04cdfba6acbb7974c87654
5,050
/* * Created on Jun 28, 2010 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * Copyright @2010-2013 the original author or authors. */ package org.fest.assertions; import org.fest.util.IntrospectionError; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Assertions for arrays or collections. * * @param <S> used to simulate "self types." For more information please read &quot;<a href="http://goo.gl/fjgOM" * target="_blank">Emulating 'self types' using Java Generics to simplify fluent API implementation</a>.&quot; * @param <A> the type the "actual" value. * @author Yvonne Wang * @since 1.3 */ public abstract class ObjectGroupAssert<S, A> extends ItemGroupAssert<S, A> { /** * Creates a new {@link ObjectGroupAssert}. * * @param selfType the "self type." * @param actual the target to verify. */ protected ObjectGroupAssert(@NotNull Class<S> selfType, @Nullable A actual) { super(selfType, actual); } /** * Verifies that the actual group of objects contains the given objects. * * @param objects the objects to look for. * @return this assertion object. * @throws AssertionError if the actual group of objects is {@code null}. * @throws NullPointerException if the given array is {@code null}. * @throws AssertionError if the actual group of objects does not contain the given objects. */ public final @NotNull S contains(@NotNull Object... objects) { assertContains(objects); return myself(); } /** * Verifies that the actual group of objects contains the given objects <strong>only</strong>, in any order. * * @param objects the objects to look for. * @return this assertion object. * @throws AssertionError if the actual group of objects is {@code null}. * @throws NullPointerException if the given group of objects is {@code null}. * @throws AssertionError if the actual group of objects does not contain the given objects, or if the actual group of * objects contains elements other than the ones specified. */ public final @NotNull S containsOnly(@NotNull Object... objects) { assertContainsOnly(objects); return myself(); } /** * Verifies that the actual group of objects does not contain the given objects. * * @param objects the objects that the group of objects should exclude. * @return this assertion object. * @throws AssertionError if the actual group of objects is {@code null}. * @throws NullPointerException if the given array is {@code null}. * @throws AssertionError if the actual group of objects contains any of the given objects. */ public final @NotNull S excludes(@NotNull Object... objects) { assertExcludes(objects); return myself(); } /** * Verifies that the actual group of objects does not have duplicates. * * @return this assertion object. * @throws AssertionError if the actual group of objects is {@code null}. * @throws AssertionError if the actual group of objects has duplicates. */ public final @NotNull S doesNotHaveDuplicates() { assertDoesNotHaveDuplicates(); return myself(); } /** * Creates a new group of objects whose target collection contains the values of the given property name from the * elements of the actual group of objects. Property access works with both simple properties like {@code Person.age} * and nested properties {@code Person.father.age}. * <p/> * For example, let's say we have a collection of {@code Person} objects and you want to verify their age: * <pre> * assertThat(persons).onProperty(&quot;age&quot;).containsOnly(25, 16, 44, 37); // simple property * assertThat(persons).onProperty("father.age").containsOnly(55, 46, 74, 62); // nested property * </pre> * * @param propertyName the name of the property to extract values from the actual collection to build a new group of * objects. * @return a new group of objects containing the values of the given property name from the elements of the actual * group of objects. * @throws NullPointerException if the given property name is {@code null}. * @throws AssertionError if the actual group of objects is {@code null}. * @throws IntrospectionError if an element in the given collection does not have a matching property. * @since 1.3 */ protected abstract @NotNull S onProperty(@NotNull String propertyName); }
42.436975
126
0.700594
d1438b3b2f9c36d5ab556c5457bfba28f015139e
28,756
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ec.edu.ups.vista; import ec.edu.ups.controlador.ControladorContrayente; import ec.edu.ups.controlador.ControladorMatrimonio; import ec.edu.ups.modelo.Autoridad; import ec.edu.ups.modelo.Contrayente; import ec.edu.ups.modelo.Matrimonio; import java.time.LocalDate; import javax.swing.JOptionPane; import javax.swing.JTextField; /** * * @author ariel */ public class VentanaMatrimonios extends javax.swing.JFrame { /** * Creates new form VentanaMatrimonios */ private Autoridad autoridad; private ControladorContrayente controladorPersona; private ControladorMatrimonio controladorMatrimonio; public VentanaMatrimonios(ControladorContrayente controladorContrayente, Autoridad autoridad, ControladorMatrimonio controladorMatrimonio) { initComponents(); this.controladorPersona = controladorPersona; this.autoridad = autoridad; } public JTextField getjTextFieldJuez() { return jTextFieldJuez; } public JTextField getjTextFieldFecha() { return jTextFieldFecha; } public void limpiar() { jTextFieldCedulaContrayente1.setText(""); jTextFieldCedulaContrayente2.setText(""); jTextFieldCedulaTestigo1.setText(""); jTextFieldCedulaTestigo2.setText(""); jTextFieldContrayente1.setText(""); jTextFieldContrayente2.setText(""); jTextFieldFecha.setText(LocalDate.now().toString()); jTextFieldLugar.setText(""); jTextFieldTestigo1.setText(""); jTextFieldTestigo2.setText(""); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabelTitulo = new javax.swing.JLabel(); jLabelContrayentes = new javax.swing.JLabel(); jLabelTestigos = new javax.swing.JLabel(); jTextFieldCedulaContrayente1 = new javax.swing.JTextField(); jTextFieldContrayente1 = new javax.swing.JTextField(); jTextFieldTestigo1 = new javax.swing.JTextField(); jTextFieldCedulaTestigo1 = new javax.swing.JTextField(); jLabelFecha = new javax.swing.JLabel(); jLabelJuez = new javax.swing.JLabel(); jTextFieldJuez = new javax.swing.JTextField(); jLabelFecha1 = new javax.swing.JLabel(); jTextFieldFecha = new javax.swing.JTextField(); jTextFieldLugar = new javax.swing.JTextField(); jButtonCancelar = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabelContrayentes1 = new javax.swing.JLabel(); jLabelContrayentes2 = new javax.swing.JLabel(); jTextFieldContrayente2 = new javax.swing.JTextField(); jLabelContrayentes3 = new javax.swing.JLabel(); jTextFieldCedulaContrayente2 = new javax.swing.JTextField(); jLabelContrayentes4 = new javax.swing.JLabel(); jLabelTestigos1 = new javax.swing.JLabel(); jTextFieldTestigo2 = new javax.swing.JTextField(); jLabelContrayentes5 = new javax.swing.JLabel(); jTextFieldCedulaTestigo2 = new javax.swing.JTextField(); jButton5 = new javax.swing.JButton(); jButtonGuardar = new javax.swing.JButton(); setResizable(false); jPanel1.setBackground(new java.awt.Color(102, 153, 255)); jLabelTitulo.setFont(new java.awt.Font("Arial", 0, 36)); // NOI18N jLabelTitulo.setForeground(new java.awt.Color(255, 255, 255)); jLabelTitulo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ec/edu/ups/imagen/pareja-de-boda.png"))); // NOI18N jLabelTitulo.setText("Nuevo Matrimonio"); jLabelContrayentes.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelContrayentes.setText("Cedula:"); jLabelTestigos.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelTestigos.setText("Primer Testigo:"); jTextFieldCedulaContrayente1.setEditable(false); jTextFieldContrayente1.setEditable(false); jTextFieldTestigo1.setEditable(false); jTextFieldCedulaTestigo1.setEditable(false); jLabelFecha.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelFecha.setText("Fecha: "); jLabelJuez.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelJuez.setText("Juez: "); jTextFieldJuez.setEditable(false); jLabelFecha1.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelFecha1.setText("Lugar de Celebracion:"); jTextFieldFecha.setEditable(false); jButtonCancelar.setText("Cancelar"); jButtonCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonCancelarActionPerformed(evt); } }); jButton1.setText("Seleccionar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Seleccionar"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("Seleccionar"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("Seleccionar"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N jLabelContrayentes1.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelContrayentes1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ec/edu/ups/imagen/novio.png"))); // NOI18N jLabelContrayentes1.setText("Primer Contrayente:"); jLabelContrayentes2.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelContrayentes2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ec/edu/ups/imagen/novia.png"))); // NOI18N jLabelContrayentes2.setText("Segundo Contrayente:"); jTextFieldContrayente2.setEditable(false); jLabelContrayentes3.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelContrayentes3.setText("Cedula:"); jTextFieldCedulaContrayente2.setEditable(false); jLabelContrayentes4.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelContrayentes4.setText("Cedula:"); jLabelTestigos1.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelTestigos1.setText("Primer Testigo:"); jTextFieldTestigo2.setEditable(false); jLabelContrayentes5.setFont(new java.awt.Font("Yu Gothic", 0, 18)); // NOI18N jLabelContrayentes5.setText("Cedula:"); jTextFieldCedulaTestigo2.setEditable(false); jButton5.setText("Limpiar"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jButtonGuardar.setText("Guardar"); jButtonGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonGuardarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(150, 150, 150) .addComponent(jLabelTitulo) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelContrayentes) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextFieldCedulaContrayente1, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabelContrayentes1) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTextFieldContrayente1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(46, 46, 46) .addComponent(jButton1))) .addGap(45, 45, 45) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelContrayentes3) .addGap(61, 61, 61) .addComponent(jTextFieldCedulaContrayente2)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTextFieldContrayente2, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(33, 33, 33) .addComponent(jButton2)) .addComponent(jLabelContrayentes2))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelTestigos) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelContrayentes4) .addGap(35, 35, 35) .addComponent(jTextFieldCedulaTestigo1, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTextFieldTestigo1, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(25, 25, 25) .addComponent(jButton3))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelTestigos1) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jTextFieldTestigo2, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(36, 36, 36) .addComponent(jButton4)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelContrayentes5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jTextFieldCedulaTestigo2, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelFecha) .addComponent(jLabelJuez)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextFieldJuez, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jTextFieldFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(16, 16, 16) .addComponent(jButton5) .addGap(18, 18, 18) .addComponent(jButtonCancelar) .addGap(35, 35, 35) .addComponent(jButtonGuardar)))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelFecha1) .addGap(18, 18, 18) .addComponent(jTextFieldLugar, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(37, 37, 37)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jLabelTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelContrayentes1) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(1, 1, 1) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldContrayente1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelContrayentes) .addComponent(jTextFieldCedulaContrayente1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1)))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelContrayentes2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldContrayente2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelContrayentes3) .addComponent(jTextFieldCedulaContrayente2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelTestigos) .addGap(1, 1, 1) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldTestigo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextFieldCedulaTestigo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabelContrayentes4))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabelTestigos1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton4) .addComponent(jTextFieldTestigo2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelContrayentes5) .addComponent(jTextFieldCedulaTestigo2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(62, 62, 62) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelFecha1) .addComponent(jTextFieldLugar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelJuez) .addComponent(jTextFieldJuez, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelFecha) .addComponent(jTextFieldFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonCancelar) .addComponent(jButton5) .addComponent(jButtonGuardar)) .addContainerGap(31, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: VentanaContrayentes ventanaPersonasRegistradas = new VentanaContrayentes(controladorPersona, jTextFieldContrayente1, jTextFieldCedulaContrayente1); ventanaPersonasRegistradas.setVisible(true); ventanaPersonasRegistradas.cargarDatosPersonas(); }//GEN-LAST:event_jButton1ActionPerformed private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed // TODO add your handling code here: this.setVisible(false); limpiar(); }//GEN-LAST:event_jButtonCancelarActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed // TODO add your handling code here: limpiar(); }//GEN-LAST:event_jButton5ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: VentanaContrayentes ventanaPersonasRegistradas = new VentanaContrayentes(controladorPersona, jTextFieldContrayente2, jTextFieldCedulaContrayente2); ventanaPersonasRegistradas.setVisible(true); ventanaPersonasRegistradas.cargarDatosPersonas(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: VentanaContrayentes ventanaPersonasRegistradas = new VentanaContrayentes(controladorPersona, jTextFieldTestigo1, jTextFieldCedulaTestigo1); ventanaPersonasRegistradas.setVisible(true); ventanaPersonasRegistradas.cargarDatosPersonas(); }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: VentanaContrayentes ventanaPersonasRegistradas = new VentanaContrayentes(controladorPersona, jTextFieldTestigo2, jTextFieldCedulaTestigo2); ventanaPersonasRegistradas.setVisible(true); ventanaPersonasRegistradas.cargarDatosPersonas(); }//GEN-LAST:event_jButton4ActionPerformed private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed // TODO add your handling code here: if (jTextFieldCedulaContrayente1.getText().trim().equals("") || jTextFieldCedulaContrayente2.getText().trim().equals("") || jTextFieldCedulaTestigo1.getText().trim().equals("") || jTextFieldTestigo2.getText().trim().equals("") || jTextFieldLugar.getText().trim().equals("") ) { JOptionPane.showMessageDialog(this, "Porfavor rellene todos los campos"); } else { Contrayente c1 = new Contrayente(jTextFieldCedulaContrayente1.getText()); c1.setEstadoCivil("casado"); c1 = controladorPersona.buscar(c1); System.out.println(c1.toString()); Contrayente c2 = new Contrayente(jTextFieldCedulaContrayente2.getText()); c2 = controladorPersona.buscar(c2); c2.setEstadoCivil("casado"); System.out.println(c2.toString()); Contrayente t1 = new Contrayente(jTextFieldCedulaTestigo1.getText()); c1 = controladorPersona.buscar(c1); System.out.println(t1.toString()); Contrayente t2 = new Contrayente(jTextFieldCedulaTestigo2.getText()); t2 = controladorPersona.buscar(t2); System.out.println(t2.toString()); Matrimonio matrimonio = new Matrimonio(controladorMatrimonio.generarId(), LocalDate.now(), jTextFieldLugar.getText(), c1, c2, t1, t2,autoridad); if (controladorMatrimonio.crear(matrimonio)) { JOptionPane.showMessageDialog(this, "Matrimonio guardado con exito"); controladorPersona.actualizar(c1); controladorPersona.actualizar(c2); limpiar(); } else { JOptionPane.showMessageDialog(this, "No se guardaron los datos porfavor vuelva a intentarlo"); } } }//GEN-LAST:event_jButtonGuardarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButtonCancelar; private javax.swing.JButton jButtonGuardar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabelContrayentes; private javax.swing.JLabel jLabelContrayentes1; private javax.swing.JLabel jLabelContrayentes2; private javax.swing.JLabel jLabelContrayentes3; private javax.swing.JLabel jLabelContrayentes4; private javax.swing.JLabel jLabelContrayentes5; private javax.swing.JLabel jLabelFecha; private javax.swing.JLabel jLabelFecha1; private javax.swing.JLabel jLabelJuez; private javax.swing.JLabel jLabelTestigos; private javax.swing.JLabel jLabelTestigos1; private javax.swing.JLabel jLabelTitulo; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTextFieldCedulaContrayente1; private javax.swing.JTextField jTextFieldCedulaContrayente2; private javax.swing.JTextField jTextFieldCedulaTestigo1; private javax.swing.JTextField jTextFieldCedulaTestigo2; private javax.swing.JTextField jTextFieldContrayente1; private javax.swing.JTextField jTextFieldContrayente2; private javax.swing.JTextField jTextFieldFecha; private javax.swing.JTextField jTextFieldJuez; private javax.swing.JTextField jTextFieldLugar; private javax.swing.JTextField jTextFieldTestigo1; private javax.swing.JTextField jTextFieldTestigo2; // End of variables declaration//GEN-END:variables }
57.627255
199
0.658089
7e726634fc363d6fa6eb7c301d798fdf4fc05027
817
package de.dfki.asr.compass.business; import de.dfki.asr.compass.business.exception.EntityNotFoundException; import de.dfki.asr.compass.business.services.CRUDService; import de.dfki.asr.compass.model.components.Annotation; import javax.ejb.Stateless; import javax.inject.Inject; import org.jboss.logging.Logger; @Stateless public class AnnotationManager { @Inject private CRUDService crudService; @Inject private Logger log; public void updateAnnotation(long annotationId, String title, String text) { try { Annotation updatee = crudService.findById(Annotation.class, annotationId); updatee.setText(text); updatee.setTitle(title); crudService.save(updatee.getOwner().getOwner()); } catch (EntityNotFoundException ex) { log.errorv(ex, "Trying to update a nonexistent annotation"); } } }
28.172414
77
0.780906
831781477ce65a6da098d4543991bb37272818f0
1,129
// Copyright 2020 Jacob Glueck // // 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 tako; import java.nio.ByteBuffer; public class Helpers { public static ByteBuffer bytes(int... bytes) { ByteBuffer result = ByteBuffer.allocate(bytes.length); for (int b: bytes) { result.put((byte) b); } result.position(0); return result; } public static boolean bufEquals(ByteBuffer a, ByteBuffer b) { var adup = a.duplicate(); var bdup = b.duplicate(); adup.position(0); bdup.position(0); return adup.equals(bdup); } }
30.513514
75
0.668733
d88676567ed43b7f2a1e4a3f6a7200e17b80df82
535
package com.yeepay.yop.sdk.utils.json.joda; import com.fasterxml.jackson.databind.module.SimpleModule; import org.joda.time.DateTime; /** * title: DateTime模块<br> * description: <br> * Copyright: Copyright (c) 2020<br> * Company: 易宝支付(YeePay)<br> */ public class DatetimeModule extends SimpleModule { private static final long serialVersionUID = -1L; public DatetimeModule() { addSerializer(DateTime.class, new DateTimeSerializer()); addDeserializer(DateTime.class, new DateTimeDeserializer()); } }
25.47619
68
0.723364
315fc1c183d06f3877bccc29345c415ed4a76006
605
package org.ajexp.excel; import org.ajexp.AjxLocale; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.util.Collection; /** * Created by SSh on 19.10.2017. */ public class XSSFExporter extends AbstractExcelExporter { public XSSFExporter(Collection<?> data, Class clazz) { super(data, clazz); } public XSSFExporter(Collection<?> data, Class clazz, AjxLocale locale) { super(data, clazz, locale); } protected Workbook createWorkbook() { return new XSSFWorkbook(); } }
23.269231
77
0.669421
1ae265c1a73965cd514d3947e6dcf80603cb0e4f
4,346
package com.github.a5809909.gps_finder.Fragment; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import com.github.a5809909.gps_finder.R; import com.github.a5809909.gps_finder.Sql.DatabaseHelper; public class DatabaseFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemSelectedListener, OnItemLongClickListener { private static final String TAG = DatabaseFragment.class.getSimpleName(); SwipeRefreshLayout mSwipeRefreshLayout; ListView listView; Cursor mCursor; SimpleCursorAdapter mSimpleCursorAdapter; DatabaseHelper databaseHelper; String[] from = new String[]{databaseHelper.COLUMN_DAY_AND_TIME, databaseHelper.COLUMN_LAT, databaseHelper.COLUMN_LNG, databaseHelper.COLUMN_ACCURACY, databaseHelper.COLUMN_ADDRESS}; int[] to = new int[]{R.id.text_view_date_and_time, R.id.text_view_latitude, R.id.text_view_longitude, R.id.text_view_accurancy, R.id.text_view_address}; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_database, container, false); listView = view.findViewById(R.id.listView1); registerForContextMenu(listView); mSwipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout); mSwipeRefreshLayout.setOnRefreshListener(this); Log.i(TAG, "onCreateView: "); onRefresh(); listView.setOnItemLongClickListener(this); listView.setOnItemSelectedListener(this); return view; } // @Override // public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { // super.onCreateContextMenu(menu, v, menuInfo); // // MenuInflater inflater = getMenuInflater(); // inflater.inflate(R.menu.context_menu, menu); // } // // @Override // public boolean onContextItemSelected(MenuItem item) { // AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); // switch (item.getItemId()) { // case R.id.edit: // editItem(info.position); // метод, выполняющий действие при редактировании пункта меню // return true; // case R.id.delete: // deleteItem(info.position); //метод, выполняющий действие при удалении пункта меню // return true; // default: // return super.onContextItemSelected(item); // } // } @Override public void onRefresh() { databaseHelper = new DatabaseHelper(getActivity()); mCursor = databaseHelper.getLastItem(); mSimpleCursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.item_list_view, mCursor, from, to, 0); listView.setAdapter(mSimpleCursorAdapter); mSwipeRefreshLayout.setRefreshing(false); databaseHelper.close(); Log.i(TAG, "onRefresh: "); } @Override public void onResume() { super.onResume(); Log.i(TAG, "onResume: "); } @Override public boolean onItemLongClick(AdapterView<?> pAdapterView, View pView, int pI, long pL) { Cursor m = ((Cursor) mSimpleCursorAdapter.getItem(pI)); String mmm = m.getString(0); Log.i(TAG, "onItemLongClick: " + mmm + ", PI:" + pI + ", PL:" + pL); databaseHelper = new DatabaseHelper(getActivity()); databaseHelper.deleteIditem(mmm); databaseHelper.close(); onRefresh(); return false; } @Override public void onItemSelected(AdapterView<?> pAdapterView, View pView, int pI, long pL) { // Log.i(TAG, "onItemSelected: " + ((LocationModel) mSimpleCursorAdapter.getItem(pI)).getDateAndTime()); } @Override public void onNothingSelected(AdapterView<?> pAdapterView) { } }
37.465517
157
0.699264
15fc47e58777f62be066f30ed893c88edd85323c
13,065
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package software.amazon.awssdk.http.nio.netty.internal; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static software.amazon.awssdk.http.nio.netty.internal.Http1TunnelConnectionPool.TUNNEL_ESTABLISHED_KEY; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelId; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.pool.ChannelPool; import io.netty.channel.pool.ChannelPoolHandler; import io.netty.handler.ssl.ApplicationProtocolNegotiator; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslHandler; import io.netty.util.Attribute; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.Promise; import java.io.IOException; import java.net.URI; import java.util.List; import java.util.concurrent.CountDownLatch; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSessionContext; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import software.amazon.awssdk.http.SdkHttpConfigurationOption; /** * Unit tests for {@link Http1TunnelConnectionPool}. */ @RunWith(MockitoJUnitRunner.class) public class Http1TunnelConnectionPoolTest { private static final NioEventLoopGroup GROUP = new NioEventLoopGroup(1); private static final URI HTTP_PROXY_ADDRESS = URI.create("http://localhost:1234"); private static final URI HTTPS_PROXY_ADDRESS = URI.create("https://localhost:5678"); private static final URI REMOTE_ADDRESS = URI.create("https://s3.amazonaws.com:5678"); private static final String PROXY_USER = "myuser"; private static final String PROXY_PASSWORD = "mypassword"; @Mock private ChannelPool delegatePool; @Mock private ChannelPoolHandler mockHandler; @Mock public Channel mockChannel; @Mock public ChannelPipeline mockPipeline; @Mock public Attribute mockAttr; @Mock public ChannelHandlerContext mockCtx; @Mock public ChannelId mockId; public NettyConfiguration configuration; @Before public void methodSetup() { Future<Channel> channelFuture = GROUP.next().newSucceededFuture(mockChannel); when(delegatePool.acquire(any(Promise.class))).thenReturn(channelFuture); when(mockCtx.channel()).thenReturn(mockChannel); when(mockCtx.pipeline()).thenReturn(mockPipeline); when(mockChannel.attr(eq(TUNNEL_ESTABLISHED_KEY))).thenReturn(mockAttr); when(mockChannel.id()).thenReturn(mockId); when(mockChannel.pipeline()).thenReturn(mockPipeline); configuration = new NettyConfiguration(SdkHttpConfigurationOption.GLOBAL_HTTP_DEFAULTS); } @AfterClass public static void teardown() { GROUP.shutdownGracefully().awaitUninterruptibly(); } @Test public void tunnelAlreadyEstablished_doesNotAddInitHandler() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); when(mockAttr.get()).thenReturn(true); tunnelPool.acquire().awaitUninterruptibly(); verify(mockPipeline, never()).addLast(anyObject()); } @Test(timeout = 1000) public void tunnelNotEstablished_addsInitHandler() throws InterruptedException { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); when(mockAttr.get()).thenReturn(false); CountDownLatch latch = new CountDownLatch(1); when(mockPipeline.addLast(any(ChannelHandler.class))).thenAnswer(i -> { latch.countDown(); return mockPipeline; }); tunnelPool.acquire(); latch.await(); verify(mockPipeline, times(1)).addLast(any(ProxyTunnelInitHandler.class)); } @Test public void tunnelInitFails_acquireFutureFails() { Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> { initFuture.setFailure(new IOException("boom")); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS,null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().cause()).hasMessage("boom"); } @Test public void tunnelInitSucceeds_acquireFutureSucceeds() { Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().getNow()).isEqualTo(mockChannel); } @Test public void acquireFromDelegatePoolFails_failsFuture() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); when(delegatePool.acquire(any(Promise.class))).thenReturn(GROUP.next().newFailedFuture(new IOException("boom"))); Future<Channel> acquireFuture = tunnelPool.acquire(); assertThat(acquireFuture.awaitUninterruptibly().cause()).hasMessage("boom"); } @Test public void sslContextProvided_andProxyUsingHttps_addsSslHandler() { SslHandler mockSslHandler = mock(SslHandler.class); SSLEngine mockSslEngine = mock(SSLEngine.class); when(mockSslHandler.engine()).thenReturn(mockSslEngine); when(mockSslEngine.getSSLParameters()).thenReturn(mock(SSLParameters.class)); TestSslContext mockSslCtx = new TestSslContext(mockSslHandler); Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx, HTTPS_PROXY_ADDRESS, null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration); tunnelPool.acquire().awaitUninterruptibly(); ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class); verify(mockPipeline, times(2)).addLast(handlersCaptor.capture()); assertThat(handlersCaptor.getAllValues().get(0)).isEqualTo(mockSslHandler); } @Test public void sslContextProvided_andProxyNotUsingHttps_doesNotAddSslHandler() { SslHandler mockSslHandler = mock(SslHandler.class); TestSslContext mockSslCtx = new TestSslContext(mockSslHandler); Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, mockSslCtx, HTTP_PROXY_ADDRESS, null, null, REMOTE_ADDRESS, mockHandler, supplier, configuration); tunnelPool.acquire().awaitUninterruptibly(); ArgumentCaptor<ChannelHandler> handlersCaptor = ArgumentCaptor.forClass(ChannelHandler.class); verify(mockPipeline).addLast(handlersCaptor.capture()); assertThat(handlersCaptor.getAllValues().get(0)).isNotInstanceOf(SslHandler.class); } @Test public void release_releasedToDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); tunnelPool.release(mockChannel); verify(delegatePool).release(eq(mockChannel), any(Promise.class)); } @Test public void release_withGivenPromise_releasedToDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); Promise mockPromise = mock(Promise.class); tunnelPool.release(mockChannel, mockPromise); verify(delegatePool).release(eq(mockChannel), eq(mockPromise)); } @Test public void close_closesDelegatePool() { Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, REMOTE_ADDRESS, mockHandler, configuration); tunnelPool.close(); verify(delegatePool).close(); } @Test public void proxyAuthProvided_addInitHandler_withAuth(){ TestInitHandlerData data = new TestInitHandlerData(); Http1TunnelConnectionPool.InitHandlerSupplier supplier = (srcPool, proxyUser, proxyPassword, remoteAddr, initFuture) -> { initFuture.setSuccess(mockChannel); data.proxyUser(proxyUser); data.proxyPassword(proxyPassword); return mock(ChannelHandler.class); }; Http1TunnelConnectionPool tunnelPool = new Http1TunnelConnectionPool(GROUP.next(), delegatePool, null, HTTP_PROXY_ADDRESS, PROXY_USER, PROXY_PASSWORD, REMOTE_ADDRESS, mockHandler, supplier, configuration); tunnelPool.acquire().awaitUninterruptibly(); assertThat(data.proxyUser()).isEqualTo(PROXY_USER); assertThat(data.proxyPassword()).isEqualTo(PROXY_PASSWORD); } private static class TestInitHandlerData { private String proxyUser; private String proxyPassword; public void proxyUser(String proxyUser) { this.proxyUser = proxyUser; } public String proxyUser() { return this.proxyUser; } public void proxyPassword(String proxyPassword) { this.proxyPassword = proxyPassword; } public String proxyPassword(){ return this.proxyPassword; } } private static class TestSslContext extends SslContext { private final SslHandler handler; protected TestSslContext(SslHandler handler) { this.handler = handler; } @Override public boolean isClient() { return false; } @Override public List<String> cipherSuites() { return null; } @Override public long sessionCacheSize() { return 0; } @Override public long sessionTimeout() { return 0; } @Override public ApplicationProtocolNegotiator applicationProtocolNegotiator() { return null; } @Override public SSLEngine newEngine(ByteBufAllocator alloc) { return null; } @Override public SSLEngine newEngine(ByteBufAllocator alloc, String peerHost, int peerPort) { return null; } @Override public SSLSessionContext sessionContext() { return null; } @Override public SslHandler newHandler(ByteBufAllocator alloc, String host, int port, boolean startTls) { return handler; } } }
36.596639
129
0.711137
5403e750bd4f4fd3009aa555d3e525599c13222b
541
package edu.coldserenity.tij.ch04.ex09; /** * Exercise 9: (1) * <p/> * Create a class with two (overloaded) constructors. * Using this, call the second constructor inside the first one. */ public class ThisConstructor { public ThisConstructor() { System.out.println("In ThisConstructor()"); } public ThisConstructor(String message) { this(); System.out.println("In ThisConstructor(String message)"); } public static void main(String[] args) { new ThisConstructor("Hello"); } }
23.521739
65
0.650647
ff8cee0cd2943c51a59d7a40af230d3ff628e0e4
3,463
/* * Copyright 2004-2007 Gary Bentley * * 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.josql.expressions; import com.gentlyweb.utils.Getter; import org.josql.Query; import org.josql.QueryExecutionException; import org.josql.QueryParseException; import org.josql.internal.Utilities; /** * Represents an "accessor" into an object. An accessor is basically a dot separated list * of method names, such as: <code>myObj.id.name</code>. * <p> * All of the methods referenced must have no arguments and be "public" in the referring class. * You can use either the actual method name or the JavaBean naming convention. * Thus: <code>myObj.id.name</code> might also be represented as: <code>getMyObj.getId.getName</code>. */ public class Accessor extends ValueExpression { private String acc = null; private Getter get = null; public Class getExpectedReturnType (Query q) throws QueryParseException { return this.get.getType (); } public void init (Query q) throws QueryParseException { // Now init the getter. try { this.get = new Getter (this.acc, q.getFromObjectClass ()); } catch (Exception e) { throw new QueryParseException ("Unable to create getter: " + this.acc, e); } } public String getAccessor () { return this.acc; } public void setAccessor (String a) { this.acc = a; } public Getter getGetter () { return this.get; } public void setName (String name) { this.acc = name; } public boolean isTrue (Object o, Query q) throws QueryExecutionException { o = this.evaluate (o, q); if (o == null) { return false; } if (Utilities.isNumber (o)) { return Utilities.getDouble (o) > 0; } if (o instanceof Boolean) { return ((Boolean) o).booleanValue (); } // Not null so return true... return true; } public boolean hasFixedResult (Query q) { // Well duh... return false; } public Object evaluate (Object o, Query q) throws QueryExecutionException { try { return this.get.getValue (o); } catch (Exception e) { throw new QueryExecutionException ("Unable to get value from: " + this + " passed in object type: " + o.getClass ().getName () + " expecting: " + this.get.getType ().getName (), e); } } public boolean equals (Object o) { if (o == null) { return false; } if (!(o instanceof Accessor)) { return false; } Accessor a = (Accessor) o; return this.acc.equals (a.getAccessor ()); } public String toString () { if (this.isBracketed ()) { return "(" + this.acc + ")"; } return this.acc + "[detail: " + this.get + "]"; } }
17.315
102
0.610165
6637cc34494ca6ed6a841c490c0ad304b6b64470
1,192
/******************************************************************************* * Copyright (c) 2021 Microsoft Corporation and others. * 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: * Microsoft Corporation - initial API and implementation *******************************************************************************/ package com.microsoft.java.lsif.core.internal.protocol; import com.microsoft.java.lsif.core.internal.IConstant; public class Document extends Vertex { private String uri; private String languageId; private String contents; public Document(String id, String uri) { super(id, Vertex.DOCUMENT); this.uri = uri; this.languageId = IConstant.JAVA_ID; } public String getUri() { return this.uri; } public String getLanguageId() { return this.languageId; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } }
25.913043
81
0.620805
142e96e3928841a3975a5b467a9742cc87aeb26a
15,915
/* * 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.shardingsphere.sql.parser.sqlserver.visitor.statement.impl; import lombok.NoArgsConstructor; import org.apache.shardingsphere.sql.parser.api.visitor.operation.SQLStatementVisitor; import org.apache.shardingsphere.sql.parser.api.visitor.ASTNode; import org.apache.shardingsphere.sql.parser.api.visitor.type.DDLSQLVisitor; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.AddColumnSpecificationContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.AlterColumnAddOptionContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.AlterDefinitionClauseContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.AlterIndexContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.AlterTableContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.ColumnConstraintContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.ColumnDefinitionContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.ColumnDefinitionOptionContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.ColumnNameContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.CreateDefinitionClauseContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.CreateIndexContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.CreateTableContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.CreateTableDefinitionContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.DropColumnSpecificationContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.DropIndexContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.DropTableContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.ModifyColumnSpecificationContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.TableConstraintContext; import org.apache.shardingsphere.sql.parser.autogen.SQLServerStatementParser.TruncateTableContext; import org.apache.shardingsphere.sql.parser.sql.common.segment.ddl.AlterDefinitionSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.ddl.CreateDefinitionSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.ddl.column.ColumnDefinitionSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.ddl.column.alter.AddColumnDefinitionSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.ddl.column.alter.DropColumnDefinitionSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.ddl.column.alter.ModifyColumnDefinitionSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.ddl.constraint.ConstraintDefinitionSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.ddl.index.IndexSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.column.ColumnSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.generic.DataTypeSegment; import org.apache.shardingsphere.sql.parser.sql.common.segment.generic.table.SimpleTableSegment; import org.apache.shardingsphere.sql.parser.sql.common.value.collection.CollectionValue; import org.apache.shardingsphere.sql.parser.sql.dialect.statement.sqlserver.ddl.SQLServerAlterIndexStatement; import org.apache.shardingsphere.sql.parser.sql.dialect.statement.sqlserver.ddl.SQLServerAlterTableStatement; import org.apache.shardingsphere.sql.parser.sql.dialect.statement.sqlserver.ddl.SQLServerCreateIndexStatement; import org.apache.shardingsphere.sql.parser.sql.dialect.statement.sqlserver.ddl.SQLServerCreateTableStatement; import org.apache.shardingsphere.sql.parser.sql.dialect.statement.sqlserver.ddl.SQLServerDropIndexStatement; import org.apache.shardingsphere.sql.parser.sql.dialect.statement.sqlserver.ddl.SQLServerDropTableStatement; import org.apache.shardingsphere.sql.parser.sql.dialect.statement.sqlserver.ddl.SQLServerTruncateStatement; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.Properties; /** * DDL Statement SQL visitor for SQLServer. */ @NoArgsConstructor public final class SQLServerDDLStatementSQLVisitor extends SQLServerStatementSQLVisitor implements DDLSQLVisitor, SQLStatementVisitor { public SQLServerDDLStatementSQLVisitor(final Properties props) { super(props); } @SuppressWarnings("unchecked") @Override public ASTNode visitCreateTable(final CreateTableContext ctx) { SQLServerCreateTableStatement result = new SQLServerCreateTableStatement(); result.setTable((SimpleTableSegment) visit(ctx.tableName())); if (null != ctx.createDefinitionClause()) { CollectionValue<CreateDefinitionSegment> createDefinitions = (CollectionValue<CreateDefinitionSegment>) visit(ctx.createDefinitionClause()); for (CreateDefinitionSegment each : createDefinitions.getValue()) { if (each instanceof ColumnDefinitionSegment) { result.getColumnDefinitions().add((ColumnDefinitionSegment) each); } else if (each instanceof ConstraintDefinitionSegment) { result.getConstraintDefinitions().add((ConstraintDefinitionSegment) each); } } } return result; } @Override public ASTNode visitCreateDefinitionClause(final CreateDefinitionClauseContext ctx) { CollectionValue<CreateDefinitionSegment> result = new CollectionValue<>(); for (CreateTableDefinitionContext each : ctx.createTableDefinitions().createTableDefinition()) { if (null != each.columnDefinition()) { result.getValue().add((ColumnDefinitionSegment) visit(each.columnDefinition())); } if (null != each.tableConstraint()) { result.getValue().add((ConstraintDefinitionSegment) visit(each.tableConstraint())); } } return result; } @Override public ASTNode visitColumnDefinition(final ColumnDefinitionContext ctx) { ColumnSegment column = (ColumnSegment) visit(ctx.columnName()); DataTypeSegment dataType = (DataTypeSegment) visit(ctx.dataType()); boolean isPrimaryKey = isPrimaryKey(ctx); ColumnDefinitionSegment result = new ColumnDefinitionSegment( ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex(), column, dataType, isPrimaryKey); for (ColumnDefinitionOptionContext each : ctx.columnDefinitionOption()) { for (ColumnConstraintContext columnConstraint : each.columnConstraint()) { if (null != columnConstraint.columnForeignKeyConstraint()) { result.getReferencedTables().add((SimpleTableSegment) visit(columnConstraint.columnForeignKeyConstraint().tableName())); } } } for (ColumnConstraintContext each : ctx.columnConstraints().columnConstraint()) { if (null != each.columnForeignKeyConstraint()) { result.getReferencedTables().add((SimpleTableSegment) visit(each.columnForeignKeyConstraint().tableName())); } } return result; } private boolean isPrimaryKey(final ColumnDefinitionContext ctx) { for (ColumnDefinitionOptionContext each : ctx.columnDefinitionOption()) { for (ColumnConstraintContext columnConstraint : each.columnConstraint()) { if (null != columnConstraint.primaryKeyConstraint() && null != columnConstraint.primaryKeyConstraint().primaryKey()) { return true; } } } for (ColumnConstraintContext each : ctx.columnConstraints().columnConstraint()) { if (null != each.primaryKeyConstraint() && null != each.primaryKeyConstraint().primaryKey()) { return true; } } return false; } @SuppressWarnings("unchecked") @Override public ASTNode visitTableConstraint(final TableConstraintContext ctx) { ConstraintDefinitionSegment result = new ConstraintDefinitionSegment(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex()); if (null != ctx.tablePrimaryConstraint() && null != ctx.tablePrimaryConstraint().primaryKeyUnique().primaryKey()) { if (null != ctx.tablePrimaryConstraint().diskTablePrimaryConstraintOption()) { result.getPrimaryKeyColumns().addAll(((CollectionValue<ColumnSegment>) visit(ctx.tablePrimaryConstraint().diskTablePrimaryConstraintOption().columnNames())).getValue()); } if (null != ctx.tablePrimaryConstraint().memoryTablePrimaryConstraintOption()) { result.getPrimaryKeyColumns().addAll(((CollectionValue<ColumnSegment>) visit(ctx.tablePrimaryConstraint().memoryTablePrimaryConstraintOption().columnNames())).getValue()); } } if (null != ctx.tableForeignKeyConstraint()) { result.setReferencedTable((SimpleTableSegment) visit(ctx.tableForeignKeyConstraint().tableName())); } return result; } @SuppressWarnings("unchecked") @Override public ASTNode visitAlterTable(final AlterTableContext ctx) { SQLServerAlterTableStatement result = new SQLServerAlterTableStatement(); result.setTable((SimpleTableSegment) visit(ctx.tableName())); for (AlterDefinitionClauseContext alterDefinitionClauseContext : ctx.alterDefinitionClause()) { for (AlterDefinitionSegment each : ((CollectionValue<AlterDefinitionSegment>) visit(alterDefinitionClauseContext)).getValue()) { if (each instanceof AddColumnDefinitionSegment) { result.getAddColumnDefinitions().add((AddColumnDefinitionSegment) each); } else if (each instanceof ModifyColumnDefinitionSegment) { result.getModifyColumnDefinitions().add((ModifyColumnDefinitionSegment) each); } else if (each instanceof DropColumnDefinitionSegment) { result.getDropColumnDefinitions().add((DropColumnDefinitionSegment) each); } else if (each instanceof ConstraintDefinitionSegment) { result.getAddConstraintDefinitions().add((ConstraintDefinitionSegment) each); } } } return result; } @SuppressWarnings("unchecked") @Override public ASTNode visitAlterDefinitionClause(final AlterDefinitionClauseContext ctx) { CollectionValue<AlterDefinitionSegment> result = new CollectionValue<>(); if (null != ctx.addColumnSpecification()) { result.getValue().addAll(((CollectionValue<AddColumnDefinitionSegment>) visit(ctx.addColumnSpecification())).getValue()); } if (null != ctx.modifyColumnSpecification()) { result.getValue().add((ModifyColumnDefinitionSegment) visit(ctx.modifyColumnSpecification())); } if (null != ctx.alterDrop() && null != ctx.alterDrop().dropColumnSpecification()) { result.getValue().add((DropColumnDefinitionSegment) visit(ctx.alterDrop().dropColumnSpecification())); } return result; } @Override public ASTNode visitAddColumnSpecification(final AddColumnSpecificationContext ctx) { CollectionValue<AddColumnDefinitionSegment> result = new CollectionValue<>(); if (null != ctx.alterColumnAddOptions()) { for (AlterColumnAddOptionContext each : ctx.alterColumnAddOptions().alterColumnAddOption()) { if (null != each.columnDefinition()) { AddColumnDefinitionSegment addColumnDefinition = new AddColumnDefinitionSegment( each.columnDefinition().getStart().getStartIndex(), each.columnDefinition().getStop().getStopIndex(), Collections.singletonList((ColumnDefinitionSegment) visit(each.columnDefinition()))); result.getValue().add(addColumnDefinition); } } } return result; } @Override public ASTNode visitModifyColumnSpecification(final ModifyColumnSpecificationContext ctx) { // TODO visit pk and table ref ColumnSegment column = (ColumnSegment) visit(ctx.alterColumnOperation().columnName()); DataTypeSegment dataType = (DataTypeSegment) visit(ctx.dataType()); ColumnDefinitionSegment columnDefinition = new ColumnDefinitionSegment(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex(), column, dataType, false); return new ModifyColumnDefinitionSegment(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex(), columnDefinition); } @Override public ASTNode visitDropColumnSpecification(final DropColumnSpecificationContext ctx) { Collection<ColumnSegment> columns = new LinkedList<>(); for (ColumnNameContext each : ctx.columnName()) { columns.add((ColumnSegment) visit(each)); } return new DropColumnDefinitionSegment(ctx.getStart().getStartIndex(), ctx.getStop().getStopIndex(), columns); } @SuppressWarnings("unchecked") @Override public ASTNode visitDropTable(final DropTableContext ctx) { SQLServerDropTableStatement result = new SQLServerDropTableStatement(); result.getTables().addAll(((CollectionValue<SimpleTableSegment>) visit(ctx.tableNames())).getValue()); return result; } @Override public ASTNode visitTruncateTable(final TruncateTableContext ctx) { SQLServerTruncateStatement result = new SQLServerTruncateStatement(); result.getTables().add((SimpleTableSegment) visit(ctx.tableName())); return result; } @Override public ASTNode visitCreateIndex(final CreateIndexContext ctx) { SQLServerCreateIndexStatement result = new SQLServerCreateIndexStatement(); result.setTable((SimpleTableSegment) visit(ctx.tableName())); result.setIndex((IndexSegment) visit(ctx.indexName())); return result; } @Override public ASTNode visitAlterIndex(final AlterIndexContext ctx) { SQLServerAlterIndexStatement result = new SQLServerAlterIndexStatement(); if (null != ctx.indexName()) { result.setIndex((IndexSegment) visit(ctx.indexName())); } result.setTable((SimpleTableSegment) visit(ctx.tableName())); return result; } @Override public ASTNode visitDropIndex(final DropIndexContext ctx) { SQLServerDropIndexStatement result = new SQLServerDropIndexStatement(); result.getIndexes().add((IndexSegment) visit(ctx.indexName())); result.setTable((SimpleTableSegment) visit(ctx.tableName())); return result; } }
57.248201
187
0.734464
0cf72ba8022adbfe16d73c0327ba3c5112ddbbb8
9,252
/******************************************************************************* * Copyright (c) 1998, 2015 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: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.eis.interactions; import java.util.*; import javax.resource.*; import javax.resource.cci.*; import org.eclipse.persistence.internal.helper.DatabaseField; import org.eclipse.persistence.internal.sessions.AbstractRecord; import org.eclipse.persistence.sessions.DatabaseRecord; import org.eclipse.persistence.eis.*; /** * Defines the specification for a call to a JCA interaction using Mapped records. * Builds the input and output records from the arguments. * * @author James * @since OracleAS TopLink 10<i>g</i> (10.0.3) */ public class MappedInteraction extends EISInteraction { protected String inputResultPath; protected Vector argumentNames; /** * Default constructor. */ public MappedInteraction() { super(); this.inputResultPath = ""; } /** * PUBLIC: * Define the argument to the interaction and the field/argument name to be substitute for it. * This is only required if an input row is not used. * The parameterAndArgumentFieldName is the name of the input record argument, * and is the field or argument name to be used to pass to the interaction. * These names are assumed to be the same, if not this method can be called with two arguments. */ public void addArgument(String parameterAndArgumentFieldName) { addArgument(parameterAndArgumentFieldName, parameterAndArgumentFieldName); } /** * PUBLIC: * Define the argument to the interaction and the field/argument name to be substitute for it. * This is only required if an input row is not used. * The parameterName is the name of the input record argument. * The argumentFieldName is the field or argument name to be used to pass to the interaction. * If these names are the same (as they normally are) this method can be called with a single argument. */ public void addArgument(String parameterName, String argumentFieldName) { getArgumentNames().addElement(parameterName); getArguments().addElement(new DatabaseField(argumentFieldName)); } /** * PUBLIC: * Define the argument to the interaction and the value name to be input for it. * This is only required if an input row is not used. * The parameterName is the name of the input record argument. * The argumentValue is the value of the input record argument. */ public void addArgumentValue(String parameterName, Object argumentValue) { getArgumentNames().addElement(parameterName); getArguments().addElement(argumentValue); } /** * PUBLIC: * The input result path defines the root key for the MappedRecord that * the interaction argument is nested into. * This is required for write interaction that take the row build from the mapped object * and need the input to contain that row record as part of the input, instead of the entire input. */ public String getInputResultPath() { return inputResultPath; } /** * PUBLIC: * The input result path defines the root key for the MappedRecord that * the interaction argument is nested into. * This is required for write interaction that take the row build from the mapped object * and need the input to contain that row record as part of the input, instead of the entire input. */ public void setInputResultPath(String inputResultPath) { this.inputResultPath = inputResultPath; } /** * The argument names for the input record. */ public Vector getArgumentNames() { // This is lazy initialized to conserv space on calls that have no parameters. if (argumentNames == null) { argumentNames = new Vector(); } return argumentNames; } /** * INTERNAL: * The argument names for the input record. */ public void setArgumentNames(Vector argumentNames) { this.argumentNames = argumentNames; } /** * Create a mapped input record for this interaction. * Populate the data into the record from this interaction's arguments. */ public Record createInputRecord(EISAccessor accessor) { try { MappedRecord record = null; // The input record can either be build from the interaction arguments, // or the modify row. if ((getInputRow() != null) && (!hasArguments())) { if (getInputResultPath().length() == 0) { record = (MappedRecord)createRecordElement(getInputRecordName(), getInputRow(), accessor); } else { record = accessor.getRecordFactory().createMappedRecord(getInputRecordName()); Object nestedRecord = createRecordElement(getInputResultPath(), getInputRow(), accessor); accessor.getEISPlatform().setValueInRecord(getInputResultPath(), nestedRecord, record, accessor); } } else { record = accessor.getRecordFactory().createMappedRecord(getInputRecordName()); for (int index = 0; index < getArgumentNames().size(); index++) { String parameterName = (String)getArgumentNames().get(index); Object parameter = getParameters().get(index); // If no arguments were passed to the call execution find the parameter from the row. if ((parameter == null) && (getInputRow() != null)) { parameter = getInputRow().get(parameterName); } // Allow for conversion of nested rows into nested records. parameter = createRecordElement(parameterName, parameter, accessor); // Allow for the platform to perform any platform specific record access. accessor.getEISPlatform().setValueInRecord(parameterName, parameter, record, accessor); } } return record; } catch (ResourceException exception) { throw EISException.resourceException(exception, accessor, null); } } /** * Create a mapped input record for this interaction. * Populate the data into the record from this interaction's translation row. */ public Record createTranslationRecord(AbstractRecord transaltionRow, EISAccessor accessor) { return (MappedRecord)createRecordElement(getInputRecordName(), transaltionRow, accessor); } /** * Build a database row from the record returned from the interaction. */ public AbstractRecord buildRow(Record record, EISAccessor accessor) { if (record == null) { return null; } AbstractRecord row = null; if (record instanceof IndexedRecord) { IndexedRecord indexedRecord = (IndexedRecord)record; if (indexedRecord.isEmpty()) { return null; } if (indexedRecord.get(0) instanceof Record) { return buildRow((Record)indexedRecord.get(0), accessor); } } // If not a mapped record then just put it as a result value in the row. if (!(record instanceof MappedRecord)) { row = new DatabaseRecord(1); row.put(getOutputResultPath(), record); return row; } MappedRecord mappedRecord = (MappedRecord)record; // The desired result is either the entire output record, // or a translation of the output with the output arguments. if (hasOutputArguments()) { row = new DatabaseRecord(getOutputArgumentNames().size()); for (int index = 0; index < getOutputArgumentNames().size(); index++) { DatabaseField field = (DatabaseField)getOutputArguments().get(index); row.put(field, mappedRecord.get(getOutputArgumentNames().get(index))); } return row; } else if (getOutputResultPath().length() > 0) { // Extract the desired nested record from the output. mappedRecord = (MappedRecord)mappedRecord.get(getOutputResultPath()); } // Wrapped the record in a database to avoid lossing any information in conversion to database row, // also gets around problem of some adatpers not supporting keySet or entrySet. row = new EISMappedRecord(mappedRecord, accessor); return row; } }
42.833333
117
0.642131
8457cd1516c6ed5c698a7aa21d8ae9b2959b7172
1,232
//--------------------------------------------------------------------------------------- // Copyright (c) 2001-2019 by PDFTron Systems Inc. All Rights Reserved. // Consult legal.txt regarding legal and license information. //--------------------------------------------------------------------------------------- package com.pdftron.pdf.utils; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.support.annotation.Nullable; import java.lang.ref.WeakReference; /** * A version of {@link AsyncTask} class that keeps a weak reference to the context, so * the context can be accessed (if still alive). */ public abstract class CustomAsyncTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> { private WeakReference<Context> mContext; public CustomAsyncTask(Context context) { mContext = new WeakReference<>(context); } /** * @return The context if still alive */ @Nullable protected Context getContext() { Context context = mContext.get(); if (context instanceof Activity && ((Activity) context).isFinishing()) { context = null; } return context; } }
30.8
89
0.590097
5af262b5cd85ef272275dad7cd5184a34aeb0125
592
package org.aksw.gson.utils; import com.google.gson.JsonElement; /** * A Json transformer is a function that maps a JsonElement to some other object of type T. * * Standard use case for transformers are either rewriting json elements or converting them to objects comprising standard java classes (maps, lists, numerics, strings, null) * * * @author raven * * @param <T> */ public abstract class JsonTransformerBase<T> implements JsonTransformer<T>, JsonVisitor<T> { @Override public T apply(JsonElement json) { T result = JsonWalker.visit(json, this); return result; } }
23.68
174
0.738176
1302a3ec3a2ace0f73200858e41872fc9c1a6904
5,817
package mb.pie.dagger; import dagger.BindsOptionalOf; import dagger.Module; import dagger.Provides; import dagger.multibindings.ElementsIntoSet; import mb.log.api.LoggerFactory; import mb.pie.api.MapTaskDefs; import mb.pie.api.Pie; import mb.pie.api.PieBuilder; import mb.pie.api.PieBuilder.LayerFactory; import mb.pie.api.PieBuilder.StoreFactory; import mb.pie.api.PieChildBuilder; import mb.pie.api.Share; import mb.pie.api.TaskDef; import mb.pie.api.Tracer; import mb.pie.api.serde.Serde; import mb.pie.api.stamp.OutputStamper; import mb.pie.api.stamp.ResourceStamper; import mb.resource.ReadableResource; import mb.resource.ResourceService; import mb.resource.hierarchical.HierarchicalResource; import javax.inject.Named; import javax.inject.Provider; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; @Module(includes = PieProviderModule.class) public abstract class PieOptionalsProviderModule { @BindsOptionalOf @Named("parent") abstract Pie parentPie(); @BindsOptionalOf abstract Supplier<PieBuilder> builderSupplier(); @BindsOptionalOf abstract Function<LoggerFactory, Serde> serdeFactory(); @BindsOptionalOf abstract StoreFactory storeFactory(); @BindsOptionalOf abstract Function<LoggerFactory, Share> shareFactory(); @BindsOptionalOf abstract OutputStamper defaultOutputStamper(); @BindsOptionalOf @Named("require") abstract ResourceStamper<ReadableResource> defaultRequireReadableResourceStamper(); @BindsOptionalOf @Named("provide") abstract ResourceStamper<ReadableResource> defaultProvideReadableResourceStamper(); @BindsOptionalOf @Named("require") abstract ResourceStamper<HierarchicalResource> defaultRequireHierarchicalResourceStamper(); @BindsOptionalOf @Named("provide") abstract ResourceStamper<HierarchicalResource> defaultProvideHierarchicalResourceStamper(); @BindsOptionalOf abstract LayerFactory layerFactory(); @BindsOptionalOf abstract Function<LoggerFactory, Tracer> tracerFactory(); @Provides @PieScope @SuppressWarnings("OptionalUsedAsFieldOrParameterType") static Pie providePie( @Named("parent") Optional<Pie> parentPie, Optional<Supplier<PieBuilder>> builderSupplier, Set<TaskDef<?, ?>> taskDefs, ResourceService resourceService, Optional<Function<LoggerFactory, Serde>> serdeFactory, Optional<StoreFactory> storeFactory, Optional<Function<LoggerFactory, Share>> shareFactory, Optional<OutputStamper> defaultOutputStamper, @Named("require") Optional<ResourceStamper<ReadableResource>> defaultRequireReadableResourceStamper, @Named("provide") Optional<ResourceStamper<ReadableResource>> defaultProvideReadableResourceStamper, @Named("require") Optional<ResourceStamper<HierarchicalResource>> defaultRequireHierarchicalResourceStamper, @Named("provide") Optional<ResourceStamper<HierarchicalResource>> defaultProvideHierarchicalResourceStamper, Optional<LayerFactory> layerFactory, Optional<LoggerFactory> loggerFactory, Optional<Function<LoggerFactory, Tracer>> tracerFactory ) { return parentPie.map(p -> { final PieChildBuilder builder = p.createChildBuilder(); builder.withTaskDefs(new MapTaskDefs(taskDefs)); builder.withResourceService(resourceService); serdeFactory.ifPresent(builder::overrideSerdeFactory); storeFactory.ifPresent(builder::overrideStoreFactory); shareFactory.ifPresent(builder::overrideShareFactory); defaultOutputStamper.ifPresent(builder::withDefaultOutputStamper); defaultRequireReadableResourceStamper.ifPresent(builder::withDefaultRequireReadableResourceStamper); defaultProvideReadableResourceStamper.ifPresent(builder::withDefaultProvideReadableResourceStamper); defaultRequireHierarchicalResourceStamper.ifPresent(builder::withDefaultRequireHierarchicalResourceStamper); defaultProvideHierarchicalResourceStamper.ifPresent(builder::withDefaultProvideHierarchicalResourceStamper); layerFactory.ifPresent(builder::withLayerFactory); loggerFactory.ifPresent(builder::withLoggerFactory); tracerFactory.ifPresent(builder::withTracerFactory); return builder.build(); }).orElseGet(() -> builderSupplier.map(bp -> { final PieBuilder builder = bp.get(); builder.withTaskDefs(new MapTaskDefs(taskDefs)); builder.withResourceService(resourceService); serdeFactory.ifPresent(builder::withSerdeFactory); storeFactory.ifPresent(builder::withStoreFactory); shareFactory.ifPresent(builder::withShareFactory); defaultOutputStamper.ifPresent(builder::withDefaultOutputStamper); defaultRequireReadableResourceStamper.ifPresent(builder::withDefaultRequireReadableResourceStamper); defaultProvideReadableResourceStamper.ifPresent(builder::withDefaultProvideReadableResourceStamper); defaultRequireHierarchicalResourceStamper.ifPresent(builder::withDefaultRequireHierarchicalResourceStamper); defaultProvideHierarchicalResourceStamper.ifPresent(builder::withDefaultProvideHierarchicalResourceStamper); layerFactory.ifPresent(builder::withLayerFactory); loggerFactory.ifPresent(builder::withLoggerFactory); tracerFactory.ifPresent(builder::withTracerFactory); return builder.build(); }).orElseThrow(() -> new IllegalStateException("Cannot create PIE instance; PIE builder provider has not been set, nor has a parent PIE instance been set"))); } }
47.292683
166
0.762592
bff3d84c46dce6b5a48311a6505eeac412290977
2,340
package com.nodecollege.cloud.service.job; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.nodecollege.cloud.common.model.QueryVO; import com.nodecollege.cloud.common.model.po.SyncJob; import com.nodecollege.cloud.common.model.po.SyncJobLog; import com.nodecollege.cloud.core.annotation.SyncJobAnnotation; import com.nodecollege.cloud.service.SyncJobLogService; import lombok.extern.slf4j.Slf4j; import org.quartz.DisallowConcurrentExecution; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.PersistJobDataAfterExecution; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.QuartzJobBean; import org.springframework.stereotype.Component; import java.util.Calendar; import java.util.Date; import java.util.List; @Slf4j @PersistJobDataAfterExecution @DisallowConcurrentExecution @Component @SyncJobAnnotation(jobName = "定时删除任务日志", cronExpression = "0 0 1 * * ?", jobParam = "{\"retentionDays\": 30}") public class DeleteSyncLogJob extends QuartzJobBean { @Autowired private SyncJobLogService syncJobLogService; @Override protected void executeInternal(JobExecutionContext context) { long startTime = System.currentTimeMillis(); JobDataMap map = context.getJobDetail().getJobDataMap(); SyncJob syncJob = JSON.parseObject(map.getString("syncJob"), SyncJob.class); JSONObject jobParam = JSONObject.parseObject(syncJob.getJobParam()); // 获取保留天数 Integer retentionDays = jobParam.getInteger("retentionDays"); if (retentionDays == null) { // 默认30天 retentionDays = 30; } Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.add(Calendar.DATE, -retentionDays); QueryVO queryDelete = new QueryVO(); queryDelete.setEndTime(calendar.getTime()); List<SyncJobLog> delList = syncJobLogService.getLogList(queryDelete); for (SyncJobLog log : delList) { syncJobLogService.delLog(log); } syncJobLogService.saveLog(SyncJobLog.info(syncJob, "保留最近" + retentionDays + "天日志,删除过期日志" + delList.size() + "条!", startTime)); log.info("定时删除同步任务日志结束!耗时:{}", System.currentTimeMillis() - startTime); } }
37.741935
134
0.736752
c74355f332737f83fae5303226c8509b9b749c7b
140
package com.brainmatics.belajar.java; public class Halo { public static void main(String[] x){ System.out.println("Halo Java"); } }
20
38
0.7
534653c02241116a8dff64befcdb5915ae59ced3
2,265
package br.com.ricardosander.accesscontrolboardservice.config; import br.com.ricardosander.accesscontrolboardservice.dto.UserIdentifierDTO; import br.com.ricardosander.accesscontrolboardservice.model.Identifier; import br.com.ricardosander.accesscontrolboardservice.model.IdentifierType; import br.com.ricardosander.accesscontrolboardservice.model.User; import br.com.ricardosander.accesscontrolboardservice.repository.IdentifierRepository; import br.com.ricardosander.accesscontrolboardservice.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Configuration; import java.util.Arrays; @Configuration public class Instantiation implements CommandLineRunner { @Autowired private UserRepository userRepository; @Autowired private IdentifierRepository identifierRepository; @Override public void run(String... args) throws Exception { userRepository.deleteAll(); identifierRepository.deleteAll(); User user1 = new User(null); User user2 = new User(null); User user3 = new User(null); userRepository.saveAll(Arrays.asList(user1, user2, user3)); Identifier identifier1 = new Identifier(null, "123", "12345", IdentifierType.CARD, new UserIdentifierDTO(user1)); Identifier identifier2 = new Identifier(null, "123", "12346", IdentifierType.CARD, new UserIdentifierDTO(user2)); Identifier identifier3 = new Identifier(null, "321", "12345", IdentifierType.CARD, new UserIdentifierDTO(user3)); Identifier identifier4 = new Identifier(null, "123", "12347", IdentifierType.CARD, new UserIdentifierDTO(user1)); Identifier identifier5 = new Identifier(null, "123", "12348", IdentifierType.CARD, new UserIdentifierDTO(user2)); identifierRepository.saveAll( Arrays.asList(identifier1, identifier2, identifier3, identifier4, identifier5)); user1.getIdentifiers().addAll(Arrays.asList(identifier1, identifier4)); user2.getIdentifiers().addAll(Arrays.asList(identifier2, identifier5)); user3.getIdentifiers().addAll(Arrays.asList(identifier3)); userRepository.saveAll(Arrays.asList(user1, user2, user3)); } }
39.051724
96
0.778808
b2a75f6ec6f569e2170070dc4560d72f6936bb7f
6,861
/* * Copyright 2012-2013 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.slc.sli.sif.translation; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import openadk.library.common.EntryType; import openadk.library.common.EntryTypeCode; import openadk.library.common.ExitType; import openadk.library.common.ExitTypeCode; import openadk.library.common.GradeLevel; import openadk.library.common.GradeLevelCode; import openadk.library.common.StudentLEARelationship; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.slc.sli.sif.domain.converter.DateConverter; import org.slc.sli.sif.AdkTest; import org.slc.sli.sif.domain.converter.EntryTypeConverter; import org.slc.sli.sif.domain.converter.ExitTypeConverter; import org.slc.sli.sif.domain.converter.GradeLevelsConverter; import org.slc.sli.sif.domain.converter.SchoolYearConverter; import org.slc.sli.sif.domain.slientity.StudentSchoolAssociationEntity; import org.slc.sli.sif.slcinterface.SifIdResolver; /** * * StudentLEARelationship unit tests * */ public class StudentLeaRelationshipTranslationTaskTest extends AdkTest { @InjectMocks private final StudentLeaRelationshipTranslationTask translator = new StudentLeaRelationshipTranslationTask(); @Mock SifIdResolver mockSifIdResolver; @Mock SchoolYearConverter schoolYearConverter; @Mock GradeLevelsConverter gradeLevelsConverter; @Mock EntryTypeConverter entryTypeConverter; @Mock ExitTypeConverter exitTypeConverter; @Mock DateConverter dateConverter; @Before public void setupMocks() { MockitoAnnotations.initMocks(this); } @Test public void testNotNull() throws SifTranslationException { List<StudentSchoolAssociationEntity> result = translator.translate(new StudentLEARelationship(), null); Assert.assertNotNull("Result was null", result); Assert.assertEquals(1, result.size()); } @Test public void testBasicFields() throws SifTranslationException { StudentLEARelationship slr = new StudentLEARelationship(); slr.setStudentPersonalRefId("studentRefID"); slr.setLEAInfoRefId("LEAInfoRefID"); slr.setSchoolYear(Integer.valueOf(2001)); Mockito.when(mockSifIdResolver.getSliGuid("studentRefID", null)).thenReturn("SLI_StudentGUID"); Mockito.when(mockSifIdResolver.getSliGuid("LEAInfoRefID", null)).thenReturn("SLI_SchoolGUID"); Mockito.when(schoolYearConverter.convert(Integer.valueOf(2001))).thenReturn("2001"); List<StudentSchoolAssociationEntity> result = translator.translate(slr, null); Assert.assertEquals(1, result.size()); StudentSchoolAssociationEntity entity = result.get(0); Assert.assertEquals("student Id is expected to be 'SLI_StudentGUID'", "SLI_StudentGUID", entity.getStudentId()); Assert.assertEquals("school Id is expected to be 'SLI_SchoolGUID'", "SLI_SchoolGUID", entity.getSchoolId()); Assert.assertEquals("school yewar is expected to be '2001'", "2001", entity.getSchoolYear()); } @Test public void testEntryType() throws SifTranslationException { StudentLEARelationship slr = new StudentLEARelationship(); EntryType entryType = new EntryType(EntryTypeCode._0619_1832); slr.setEntryType(entryType); Mockito.when(entryTypeConverter.convert(entryType)).thenReturn("Transfer from a charter school"); List<StudentSchoolAssociationEntity> result = translator.translate(slr, null); Assert.assertEquals(1, result.size()); StudentSchoolAssociationEntity entity = result.get(0); Assert.assertEquals("entry type is expected to be 'Transfer from a charter school'", "Transfer from a charter school", entity.getEntryType()); } @Test public void testExitType() throws SifTranslationException { StudentLEARelationship slr = new StudentLEARelationship(); ExitType exitType = new ExitType(ExitTypeCode._1923_DIED_OR_INCAPACITATED); slr.setExitType(exitType); Mockito.when(exitTypeConverter.convert(exitType)).thenReturn("Died or is permanently incapacitated"); List<StudentSchoolAssociationEntity> result = translator.translate(slr, null); Assert.assertEquals(1, result.size()); StudentSchoolAssociationEntity entity = result.get(0); Assert.assertEquals("exit withdraw type is expected to be 'Died or is permanently incapacitated'", "Died or is permanently incapacitated", entity.getExitWithdrawType()); } @Test public void testGradeLevel() throws SifTranslationException { StudentLEARelationship slr = new StudentLEARelationship(); GradeLevel gradeLevel = new GradeLevel(GradeLevelCode._10); slr.setGradeLevel(gradeLevel); Mockito.when(gradeLevelsConverter.convert(gradeLevel)).thenReturn("Tenth grade"); List<StudentSchoolAssociationEntity> result = translator.translate(slr, null); Assert.assertEquals(1, result.size()); StudentSchoolAssociationEntity entity = result.get(0); Assert.assertEquals("entry grade level is expected to be 'Tenth grade'", "Tenth grade", entity.getEntryGradeLevel()); } @Test public void testDates() throws SifTranslationException { StudentLEARelationship slr = new StudentLEARelationship(); Calendar hire = new GregorianCalendar(2004, Calendar.FEBRUARY, 1); Calendar terminate = new GregorianCalendar(2005, Calendar.DECEMBER, 29); slr.setEntryDate(hire); slr.setExitDate(terminate); Mockito.when(dateConverter.convert(hire)).thenReturn("hireDate"); Mockito.when(dateConverter.convert(terminate)).thenReturn("terminateDate"); List<StudentSchoolAssociationEntity> result = translator.translate(slr, null); Assert.assertEquals(1, result.size()); StudentSchoolAssociationEntity entity = result.get(0); Assert.assertEquals("hireDate", entity.getEntryDate()); Assert.assertEquals("terminateDate", entity.getExitWithdrawDate()); } }
39.889535
120
0.738231
c8acc2ec289ce101018e75f12c783cf183a530a1
1,495
package com.tvd12.ezyfox.testing.entity; import java.util.HashMap; import java.util.HashSet; import org.testng.annotations.Test; import com.tvd12.ezyfox.collect.Sets; import com.tvd12.ezyfox.entity.EzyEmptyObject; import com.tvd12.ezyfox.factory.EzyEntityFactory; public class EzyEmptyObjectTest { @Test public void test() { EzyEmptyObject object = (EzyEmptyObject) EzyEntityFactory.EMPTY_OBJECT; assert object.size() == 0; assert !object.containsKey("a"); assert !object.isNotNullValue("a"); try {object.get("a");} catch (Exception e) {assert e instanceof UnsupportedOperationException;}; try {object.get("a", Integer.class);} catch (Exception e) {assert e instanceof UnsupportedOperationException;}; try {object.getValue("a", Integer.class);} catch (Exception e) {assert e instanceof UnsupportedOperationException;}; assert object.keySet().size() == 0; assert object.entrySet().size() == 0; assert object.toMap().isEmpty(); assert object.put("a", 1).equals(1); object.putAll(new HashMap<>()); assert object.remove("a") == null; object.removeAll(Sets.newHashSet(1, 2, 3)); object.clear(); assert !object.containsKeys(new HashSet<>()); try {object.compute("a", (a, b) -> 1);} catch (Exception e) {assert e instanceof UnsupportedOperationException;}; try {object.clone();} catch (Exception e) {assert e instanceof CloneNotSupportedException;}; try {object.duplicate();} catch (Exception e) {assert e instanceof UnsupportedOperationException;}; } }
39.342105
118
0.734448
ede236c5955793b19e01496f01148a81759d272d
4,663
package br.edu.AtividadeLab4; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Agenda { private List<Aluno> alunos = new ArrayList<>(); private List<Professor> professores = new ArrayList<>(); Scanner scanner = new Scanner(System.in); private int indexA = 0; private int indexP = 0; private int indx; public void cadastrar() { System.out.println("Deseja cadastrar aluno ou professor ?"); String resp = scanner.next(); System.out.println("Insira o nome: "); String nome = scanner.next(); System.out.println("Insira o telefone: "); String telefone = scanner.next(); System.out.println("Insira o email: "); String email = scanner.next(); if (resp.toLowerCase().equals("aluno")) { System.out.println("Insira o n�mero da matricula"); String matricula = scanner.next(); alunos.add(new Aluno(nome, telefone, email, matricula, indexA)); indexA++; } else if (resp.toLowerCase().equals("professor")) { System.out.println("Insira o n�mero de registro: "); String register = scanner.next(); System.out.println("Insira a quantidade de horas/aula: "); String horas = scanner.next(); professores.add(new Professor(nome, telefone, email, register, horas, indexP)); indexP++; } } public void editar() { System.out.println("Edi��o de contatos"); System.out.println("Deseja editar professor ou aluno ?"); String resp = scanner.next(); if(resp.toLowerCase().equals("aluno")) { System.out.println("Escolha o ID aluno a ser editado: "); for(Aluno aluno:alunos) { System.out.println("ID - " + aluno.getId() + " Nome: " + aluno.getNome()); } indx = scanner.nextInt(); } else if(resp.toLowerCase().equals("professor")) { System.out.println("Escolha o ID do professor a ser editado: "); for(Professor professor: professores) { System.out.println("ID - " + professor.getId() + " Nome: " + professor.getNome()); } indx = scanner.nextInt(); } System.out.println("Insira as novas informa��es: "); System.out.println("Nome: "); String nome = scanner.next(); System.out.println("Telefone: "); String telefone = scanner.next(); System.out.println("Email: "); String email = scanner.next(); if (resp.toLowerCase().equals("aluno")) { System.out.println("Insira seu n�mero de m�tricula: "); String matricula = scanner.next(); Aluno alunoEditado = alunos.get(indx); alunoEditado.setNome(nome); alunoEditado.setTelefone(telefone); alunoEditado.setEmail(email); alunoEditado.setNumeroMatricula(matricula); } else if (resp.toLowerCase().equals("professor")) { System.out.println("Insira seu n�mero de registro: "); String reg = scanner.next(); System.out.println("Insira a quantidade de horas aula: "); String horas = scanner.next(); Professor profEditado = professores.get(indx); profEditado.setNome(nome); profEditado.setTelefone(telefone); profEditado.setEmail(email); profEditado.setNumeroRegistro(reg); profEditado.setQuantidadeHoraAula(horas); } System.out.println("Altera��es feitas com sucesso!"); } public void excluir() { System.out.println("Exclus�o de usu�rio"); System.out.println("Excluir aluno ou professor ?"); String ap = scanner.next(); if(ap.toLowerCase().equals("aluno")) { System.out.println("Escolha o ID aluno a ser excluido: "); for(Aluno aluno:alunos) { System.out.println("ID - " + aluno.getId() + " Nome: " + aluno.getNome()); } indx = scanner.nextInt(); alunos.remove(alunos.get(indx)); System.out.println("Aluno removido com sucesso"); } else if(ap.toLowerCase().equals("professor")) { System.out.println("Escolha o ID do professor a ser editado: "); for(Professor professor: professores) { System.out.println("ID - " + professor.getId() + " Nome: " + professor.getNome()); } indx = scanner.nextInt(); professores.remove(professores.get(indx)); System.out.println("Professor removido com sucesso!"); } } public void listarTodos() { System.out.println("Lista de contatos de alunos: "); for (Aluno aluno : alunos) { System.out.println(aluno.dadosFormatados()); } System.out.println("Lista de contatos de professores"); for (Professor professor : professores) { System.out.println(professor.dadosFormatados()); } } }
25.762431
87
0.63071
7cc7b1e9ed59d118569fd52cafedf2d13907238a
6,570
/* * Copyright 2016 Huawei Technologies Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openo.baseservice.roa.util.restclient; import static org.junit.Assert.assertEquals; import org.openo.baseservice.util.impl.SystemEnvVariablesDefImpl; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import net.sf.json.JSONObject; import java.io.File; import java.io.IOException; import java.net.URL; import mockit.Mock; import mockit.MockUp; import mockit.integration.junit4.JMockit; /** * <br/> * <p> * </p> * * @author * @version 20-Jun-2016 */ @RunWith(JMockit.class) public class TestRestfulConfigure { /** * <br/> * * @throws java.lang.Exception * @since */ @BeforeClass public static void setUpBeforeClass() throws Exception { setAppRoot(); } /** * <br/> * * @throws java.lang.Exception * @since */ @AfterClass public static void tearDownAfterClass() throws Exception { } /** * <br/> * * @throws java.lang.Exception * @since */ @Before public void setUp() throws Exception { } /** * <br/> * * @throws java.lang.Exception * @since */ @After public void tearDown() throws Exception { } private static void setAppRoot() { final URL resource = ClassLoader.getSystemResource("etc/conf/restclient.json"); final String urlPath = resource.getPath().replace("etc/conf/restclient.json", ""); try { final String path = new File(urlPath).getCanonicalPath(); System.out.println("path: " + path); System.setProperty("catalina.base", path); System.out.println("approot:" + System.getProperty("catalina.base")); } catch(final IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * <br/> * @throws Exception * @since */ @Test public final void testRestfulConfigure() throws Exception { final RestfulConfigure configure = new RestfulConfigure(); final RestfulOptions options = configure.getOptions(); assertEquals("127.0.0.1", options.getHost()); assertEquals(8080, options.getPort()); assertEquals(1000, options.getIntOption("ConnectTimeout")); assertEquals(10, options.getIntOption("thread")); assertEquals(500000, options.getIntOption("idletimeout")); assertEquals(10000, options.getIntOption("timeout")); } /** * <br/> * @throws Exception * @since */ @Test public final void testRestfulConfigureAppRootNull() throws Exception { new MockUp<SystemEnvVariablesDefImpl>() { @Mock public String getAppRoot() { return null; } }; final RestfulConfigure configure = new RestfulConfigure(); final RestfulOptions options = configure.getOptions(); assertEquals("", options.getHost()); assertEquals(0, options.getPort()); assertEquals(3000, options.getIntOption("ConnectTimeout")); assertEquals(200, options.getIntOption("thread")); assertEquals(30000, options.getIntOption("idletimeout")); assertEquals(30000, options.getIntOption("timeout")); } /** * <br/> * * @throws Exception * @since */ @Test public final void testRestfulConfigureDefault() throws Exception { { new MockUp<File>() { @Mock public boolean isFile() { return false; } }; final RestfulConfigure configure = new RestfulConfigure(); final RestfulOptions options = configure.getOptions(); assertEquals("", options.getHost()); assertEquals(0, options.getPort()); assertEquals(3000, options.getIntOption("ConnectTimeout")); assertEquals(200, options.getIntOption("thread")); assertEquals(30000, options.getIntOption("idletimeout")); assertEquals(30000, options.getIntOption("timeout")); } } /** * <br/> * * @throws Exception * @since */ @Test public final void testRestfulConfigureException() throws Exception { new MockUp<JSONObject>() { @Mock JSONObject fromObject(final Object object) throws IOException { throw new IOException(); } }; final RestfulConfigure configure = new RestfulConfigure(); final RestfulOptions options = configure.getOptions(); assertEquals("", options.getHost()); assertEquals(0, options.getPort()); assertEquals(3000, options.getIntOption("ConnectTimeout")); assertEquals(200, options.getIntOption("thread")); assertEquals(30000, options.getIntOption("idletimeout")); assertEquals(30000, options.getIntOption("timeout")); } /** * * @since */ @Test public final void testRestfulConfigureString() { final String configFile = "rest-client-test.json"; final String appRoot = System.getProperty("catalina.base"); final RestfulConfigure configure = new RestfulConfigure(appRoot + File.separator + configFile); final RestfulOptions options = configure.getOptions(); assertEquals("10.10.10.10", options.getHost()); assertEquals(443, options.getPort()); assertEquals(10, options.getIntOption("ConnectTimeout")); assertEquals(100, options.getIntOption("thread")); assertEquals(30, options.getIntOption("idletimeout")); assertEquals(60, options.getIntOption("timeout")); } /** * <br/> * * @since */ @Test public final void testGetOptions() { } }
27.605042
103
0.61446
2992cafe7660d4a2e0013ea0a8e9dbf4f3c10b48
1,904
package org.tc; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; //@WebServlet("/servlet3") public class Servlet3 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); System.out.println("I am servlet3"); //设置输出格式和字符编码 resp.setContentType("text/html;charset=utf-8"); //向页面输出内容 PrintWriter out = resp.getWriter(); out.println("<h1>I am servlet3</h1>"); ServletContext application = this.getServletContext(); String name = (String) application.getAttribute("name"); System.out.println("servlet3 got name: "+name); out.println("servlet3 got name:"+name); System.out.println("servlet3 got it"); application.setAttribute("love","Liudehua love ylq"); application.getRequestDispatcher("/servlet4").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("servlet3: dopost"); resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); out.println("<h1>I am servlet3</h1>"); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.service(req, resp); System.out.println("I am servlet3"); resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); out.println("<h1>I am servlet3</h1>"); } }
35.259259
115
0.693803
5afad4e471f7a50e813c9828cee8f00d4679260f
9,166
package chickenados.autocommands; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.CRServo; import chickenados.robotv1.RobotV1; import chickenados.robotv1.RobotV1VisionAnalyzer; import chickenados.robotv2.RobotV2; import chickenados.robotv3.RobotV3; import chickenlib.util.CknEvent; import chickenlib.CknStateMachine; import chickenlib.CknTaskManager; import chickenlib.util.CknUtil; @Autonomous(name = "V3 Depot") public class V3Depot extends LinearOpMode{ CknTaskManager mgr = new CknTaskManager(); enum State{ SCAN_MINERALS, LOWER_LIFT, RELEASE_GRABBER, TURN_TO_ORIGIN, TURN_TO_SCORE, TURN_TO_MINERAL, DRIVE_TO_MINERAL, TURN_TO_DEPOT, DRIVE_TO_DEPOT, TURN_TO_DROP, DROP_MARKER, RESET_SERVO, LINE_UP_FOR_CRATER, RAISE_XRAIL, SCORE_MARKER, RESET_MARKER, DRIVE_TO_CRATER, END; } // AUTONOMOUS CONSTANTS private final boolean DO_SCAN_MINERALS = true; private final int SCAN_TIMEOUT = 5; private final double LEFT_MINERAL_ANGLE = 40; private final double RIGHT_MINERAL_ANGLE = -35; // END AUTONOMOUS CONSTANTS private double angleToMaintain; CknStateMachine<State> sm = new CknStateMachine<>(); private CknEvent event = new CknEvent(); private RobotV3 robot; private RobotV1VisionAnalyzer.GoldState goldState = RobotV1VisionAnalyzer.GoldState.UNKNOWN; private State currentState; @Override public void runOpMode() throws InterruptedException{ robot = new RobotV3(hardwareMap, telemetry, false, true); if(DO_SCAN_MINERALS){ robot.activateVision(); sm.start(State.SCAN_MINERALS); } else { sm.start(State.LOWER_LIFT); } event.set(true); waitForStart(); while(opModeIsActive()) { CknUtil.CknLoopCounter.getInstance().loop++; mgr.executeTasks(CknTaskManager.TaskType.PRECONTINUOUS); robot.dashboard.setLine(1, "State: " + currentState); robot.dashboard.setLine(2, "Event: " + event.isTriggered()); if (sm.isReady()) { currentState = sm.getState(); switch (currentState) { case SCAN_MINERALS: event.reset(); double startTime = CknUtil.getCurrentTime(); while(goldState == RobotV1VisionAnalyzer.GoldState.UNKNOWN && CknUtil.getCurrentTime() < startTime + SCAN_TIMEOUT){ goldState = robot.analyzer.analyzeTFOD(robot.tfod.getUpdatedRecognitions()); robot.dashboard.setLine(3, "Gold State: " + goldState); } event.set(true); sm.waitForEvent(event, State.LOWER_LIFT); break; case LOWER_LIFT: event.reset(); robot.lift.raiseLift(event,4.5); sm.waitForEvent(event, State.RELEASE_GRABBER); break; case RELEASE_GRABBER: event.reset(); robot.grabber.release(event); sm.waitForEvent(event, State.TURN_TO_ORIGIN); break; case TURN_TO_ORIGIN: event.reset(); robot.pidDrive.driveDistanceTank(0,0,1,event); sm.waitForEvent(event,State.TURN_TO_SCORE); break; case TURN_TO_SCORE: event.reset(); robot.pidDrive.driveDistanceTank(3, 0, 1.75, event); // If we didn't pick up the gold pos, just drive through the center one. if(goldState == RobotV1VisionAnalyzer.GoldState.UNKNOWN || goldState == RobotV1VisionAnalyzer.GoldState.CENTER){ sm.waitForEvent(event, State.DRIVE_TO_DEPOT); } else { sm.waitForEvent(event, State.TURN_TO_MINERAL); } break; case TURN_TO_MINERAL: event.reset(); // Either turn towards left or right mineral. if(goldState == RobotV1VisionAnalyzer.GoldState.LEFT){ robot.pidDrive.driveDistanceTank(0, LEFT_MINERAL_ANGLE, 2, event); angleToMaintain = LEFT_MINERAL_ANGLE; } else { robot.pidDrive.driveDistanceTank(0, RIGHT_MINERAL_ANGLE, 2, event); angleToMaintain = RIGHT_MINERAL_ANGLE; } sm.waitForEvent(event, State.DRIVE_TO_MINERAL); break; case DRIVE_TO_MINERAL: event.reset(); angleToMaintain = robot.locationTracker.getLocation().heading; robot.pidDrive.driveDistanceTank(17, angleToMaintain, 2, event); sm.waitForEvent(event, State.TURN_TO_DEPOT); break; case TURN_TO_DEPOT: event.reset(); if(goldState == RobotV1VisionAnalyzer.GoldState.LEFT) angleToMaintain = -35; if(goldState == RobotV1VisionAnalyzer.GoldState.RIGHT) angleToMaintain = 40; robot.pidDrive.driveDistanceTank(0, angleToMaintain, 2, event); sm.waitForEvent(event, State.DRIVE_TO_DEPOT); break; case DRIVE_TO_DEPOT: event.reset(); if(goldState == RobotV1VisionAnalyzer.GoldState.UNKNOWN || goldState == RobotV1VisionAnalyzer.GoldState.CENTER) { robot.pidDrive.driveDistanceTank(17, 0, 2.5, event); } else { angleToMaintain = robot.locationTracker.getLocation().heading; if(goldState == RobotV1VisionAnalyzer.GoldState.LEFT){ robot.pidDrive.driveDistanceTank(14, angleToMaintain, 1.5, event); } else { robot.pidDrive.driveDistanceTank(14, angleToMaintain, 1.5, event); } } sm.waitForEvent(event, State.LINE_UP_FOR_CRATER); break; /*case TURN_TO_DROP: event.reset(); //robot.pidDrive.driveDistanceTank(0, 90, 2.5, event); sm.waitForEvent(event, State.DROP_MARKER); break;*/ /* case DROP_MARKER: event.reset(); robot.collectorBox.extend(event); sm.waitForEvent(event, State.RESET_SERVO); break; case RESET_SERVO: event.reset(); robot.collectorBox.reset(event); sm.waitForEvent(event, State.LINE_UP_FOR_CRATER); break; */ case LINE_UP_FOR_CRATER: event.reset(); robot.pidDrive.driveDistanceTank(0,125,2,event); sm.waitForEvent(event, State.RAISE_XRAIL); break; case RAISE_XRAIL: event.reset(); robot.xRail.extend(event); sm.waitForEvent(event, State.SCORE_MARKER); break; case SCORE_MARKER: event.reset(); robot.collectorBox.extend(event); sm.waitForEvent(event, State.RESET_MARKER); break; case RESET_MARKER: event.reset(); robot.collectorBox.reset(event); sm.waitForEvent(event,State.DRIVE_TO_CRATER); break; case DRIVE_TO_CRATER: event.reset(); robot.pidDrive.driveDistanceTank( 70, 123, 2.5,event); sm.waitForEvent(event, State.END); break; case END: event.reset(); sm.stop(); break; } } mgr.executeTasks(CknTaskManager.TaskType.POSTCONTINUOUS); } } }
34.984733
104
0.499236
40d9f1d5c9977a2c08122f3c8fdf62c110cace12
141
package com.ocdsoft.bacta.swg.server.event; /** * Created by Kyle on 9/5/2014. */ public enum ObservableGameEvent { POSTURE_CHANGE }
14.1
43
0.70922
df93838a93069b0d5c693c18f5544eafe6abc25d
3,780
package pl.luxdev.mbot.listeners; import java.util.HashMap; import com.github.theholywaffle.teamspeak3.api.ChannelProperty; import com.github.theholywaffle.teamspeak3.api.event.ClientJoinEvent; import com.github.theholywaffle.teamspeak3.api.wrapper.ClientInfo; import pl.luxdev.mbot.basic.DatabasedClient; import pl.luxdev.mbot.basic.TeamSpeakUser; import pl.luxdev.mbot.basic.util.DatabaseClientUtil; import pl.luxdev.mbot.basic.util.TeamSpeakUserUtil; import pl.luxdev.mbot.events.EventHandler; import pl.luxdev.mbot.events.EventType; import pl.luxdev.mbot.instances.FirstInstance; import pl.luxdev.mbot.managers.Config; import pl.luxdev.mbot.managers.ConfigManager; import pl.luxdev.mbot.utils.BotUtils; import pl.luxdev.mbot.utils.StringUtils; public class ClientJoinList implements EventHandler<ClientJoinEvent> { public void handle(ClientJoinEvent event, FirstInstance bot) { try{ if(check(event, bot))return; int clientId = event.getClientId(); int dbClientId = event.getClientDatabaseId(); Config config = ConfigManager.getConfig(); if (!config.getSettings().canJoin(event.getClientNickname())) { bot.getApi().kickClientFromServer(config.getSettings().getBannedNicknameMessage(), clientId); } TeamSpeakUser user = new TeamSpeakUser(BotUtils.getClient(clientId)); TeamSpeakUserUtil.registerUser(user); DatabaseClientUtil.addToCDBID(event.getClientId(), event.getClientDatabaseId()); if(!DatabaseClientUtil.isInDatabase(dbClientId)){ DatabasedClient dbClient = new DatabasedClient(dbClientId); dbClient.setLastConnect(System.currentTimeMillis()); dbClient.setClientDBId(dbClientId); dbClient.setDisconnected(false); dbClient.setNick(event.getClientNickname()); dbClient.setUid(event.getUniqueClientIdentifier()); dbClient.changed(); DatabaseClientUtil.addToDatabase(dbClient, dbClientId); }else{ DatabasedClient dbClient = DatabaseClientUtil.getDBClient(dbClientId); dbClient.setLastConnect(System.currentTimeMillis()); dbClient.setNick(event.getClientNickname()); dbClient.setDisconnected(false); dbClient.changed(); } ClientInfo client = (ClientInfo) BotUtils.getClient(event.getUniqueClientIdentifier()); String message = StringUtils.parseMessage(config.getSettings().getWelcomeMessage()).toString(); message = StringUtils.basicVariables(message); message = StringUtils.userVariables(client, message); bot.getApi().sendPrivateMessage(event.getClientId(), message); if (client.getTotalConnections() == 1) { HashMap<ChannelProperty, String> properties = new HashMap<>(); properties.put(ChannelProperty.CHANNEL_DESCRIPTION, StringUtils.userVariables(client,config.getSettings().getNewUserChannelMessage())); properties.put(ChannelProperty.CHANNEL_NAME, StringUtils.userVariables(client, "[lspacer][»] "+config.getSettings().getNewUserChannelName())); bot.getApi().editChannel(config.getSettings().getNewUserChannelId(), properties); } }catch(Exception e){ e.printStackTrace(System.out); } } public EventType getEventType() { return EventType.CLIENT_JOIN_EVENT; } public boolean check(ClientJoinEvent e, FirstInstance bot) { if (e.getUniqueClientIdentifier() == "serveradmin") { return true; } if (e.getUniqueClientIdentifier() == "ServerQuery") { return true; } if (e.getUniqueClientIdentifier() == null) { return true; } if (e.getClientType() == 1) { return true; } if(bot.getApi().getClientInfo(e.getClientId()).isServerQueryClient()){ return true; } return false; } }
43.448276
147
0.724074
6b368b47eb92f484d61216cb31082e28e616d49a
2,391
package com.artemis.parallel_world.mixin; import com.google.common.collect.Lists; import net.minecraft.structure.StructurePiece; import net.minecraft.structure.StructureStart; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockBox; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.registry.Registry; import net.minecraft.world.StructureWorldAccess; import net.minecraft.world.gen.StructureAccessor; import net.minecraft.world.gen.chunk.ChunkGenerator; import net.minecraft.world.gen.feature.FeatureConfig; import net.minecraft.world.gen.feature.StructureFeature; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import java.util.Iterator; import java.util.List; import java.util.Random; @Mixin(StructureStart.class) public final class StructureStartMixin<C extends FeatureConfig> { @Final @Shadow protected final List<StructurePiece> children = Lists.newArrayList(); @Shadow @Final private StructureFeature<C> feature; @Inject(method = "generateStructure", at = @At(value = "INVOKE", target = "Ljava/util/List;iterator()Ljava/util/Iterator;")) private void checkAltitude(StructureWorldAccess world, StructureAccessor structureAccessor, ChunkGenerator chunkGenerator, Random random, BlockBox box, ChunkPos chunkPos, CallbackInfo ci) { Iterator iterator = this.children.iterator(); if (world.getRegistryManager().get(Registry.DIMENSION_TYPE_KEY).getId(world.getDimension()).equals(new Identifier("parallel_world", "tethys")) && this.feature.equals(StructureFeature.VILLAGE)) { while (iterator.hasNext()) { StructurePiece structurePiece = (StructurePiece)iterator.next(); if (structurePiece.getBoundingBox().getMinY() < 30) { iterator.remove(); } } if (this.children.isEmpty()) { return; } else iterator = this.children.iterator(); } else iterator = this.children.iterator(); } }
41.224138
193
0.740276
066f58f98dc6a326f958760f1762d4b11359f0eb
425
package fi.iki.murgo.iltasoitto.app; import android.content.Context; import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; public class HarjuLauncher extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent service = new Intent(context, MusicPlayerService.class); startWakefulService(context, service); } }
30.357143
71
0.774118
a3bb8d98b999fffa369c52951f23c15b49654a42
1,732
/* * Copyright 2020 Wuyi Chen. * * 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.ftgo.apigateway.model; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; /** * The order information. * * @author Wuyi Chen * @date 05/15/2020 * @version 1.0 * @since 1.0 */ public class OrderInfo { private String orderId; private String state; public OrderInfo() {} /** * @param orderId * @param state */ public OrderInfo(String orderId, String state) { this.orderId = orderId; this.state = state; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } @Override public boolean equals(Object o) { return EqualsBuilder.reflectionEquals(this, o); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } }
26.646154
75
0.699192
083ba8eaaa37dba46266e1494b47c52d2d22c13f
3,992
package com.simbest.cores.app.model; import com.fasterxml.jackson.annotation.JsonFormat; import com.simbest.cores.model.GenericModel; import com.simbest.cores.utils.annotations.NotNullColumn; import com.wordnik.swagger.annotations.ApiModel; import com.wordnik.swagger.annotations.ApiModelProperty; import javax.persistence.*; import java.util.Date; /** * 业务代办回调任务 * * @author lishuyi * */ @Entity @Table(name = "app_process_task_callbackretry") @ApiModel public class ProcessTaskCallbackRetry extends GenericModel<ProcessTaskCallbackRetry>{ private static final long serialVersionUID = 406815278844587818L; @Id @Column(name = "id") @SequenceGenerator(name="app_callback_retry_seq", sequenceName="app_callback_retry_seq") @GeneratedValue(strategy=GenerationType.AUTO, generator="app_callback_retry_seq") @ApiModelProperty(value="主键Id") private Integer id; @Column(name = "processServiceClass", nullable = false) @ApiModelProperty(value="流程服务Bean") private String processServiceClass; @Temporal(TemporalType.TIMESTAMP) @Column(name = "lastExecuteDate", nullable = false) @ApiModelProperty(value="最后执行时间") private Date lastExecuteDate; @Column(name = "executeTimes", nullable = false) @ApiModelProperty(value="执行次数") private Integer executeTimes; @Column(name = "callbackType", nullable = false) @ApiModelProperty(value="回调类型") private String callbackType; @ApiModelProperty(value="任务Id") private Long taskId; @Column(name = "typeId", nullable = false) @ApiModelProperty(value="流程类型Id") private Integer typeId; @Column(name = "headerId", nullable = false) @ApiModelProperty(value="流程头Id") private Integer headerId; @Column(name = "receiptId", nullable = false) @ApiModelProperty(value="业务单据Id") private Long receiptId; @Column(name = "stepId", nullable = false) @ApiModelProperty(value="当前环节Id") private Integer stepId; @Column(name = "currentUserId", nullable = true, length = 50) @ApiModelProperty(value="受理人Id") private Integer currentUserId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getProcessServiceClass() { return processServiceClass; } public void setProcessServiceClass(String processServiceClass) { this.processServiceClass = processServiceClass; } public Long getTaskId() { return taskId; } public void setTaskId(Long taskId) { this.taskId = taskId; } @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8") public Date getLastExecuteDate() { return lastExecuteDate; } public void setLastExecuteDate(Date lastExecuteDate) { this.lastExecuteDate = lastExecuteDate; } public Integer getExecuteTimes() { return executeTimes; } public void setExecuteTimes(Integer executeTimes) { this.executeTimes = executeTimes; } public Integer getTypeId() { return typeId; } public void setTypeId(Integer typeId) { this.typeId = typeId; } public Integer getHeaderId() { return headerId; } public void setHeaderId(Integer headerId) { this.headerId = headerId; } public Long getReceiptId() { return receiptId; } public void setReceiptId(Long receiptId) { this.receiptId = receiptId; } public Integer getStepId() { return stepId; } public void setStepId(Integer stepId) { this.stepId = stepId; } public Integer getCurrentUserId() { return currentUserId; } public void setCurrentUserId(Integer currentUserId) { this.currentUserId = currentUserId; } public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } }
24.490798
92
0.682365
4a32dba04b7277df1b80b3a93d93072eaad2c2a6
3,344
package cd4017be.automation.jeiPlugin; import java.util.ArrayList; import java.util.Arrays; import cd4017be.lib.Gui.SlotHolo; import cd4017be.lib.util.OreDictStack; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ClickType; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.oredict.OreDictionary; public class Utils { public static Object getItems(Object o) { if (o instanceof ItemStack) return (ItemStack)o; else if (o instanceof OreDictStack) { OreDictStack obj = (OreDictStack)o; ItemStack[] list = obj.getItems(); return Arrays.asList(list); } else return null; } public static boolean valid(Object o) { if (o == null || o instanceof ItemStack) return true; else if (o instanceof OreDictStack) return !OreDictionary.getOres(((OreDictStack)o).id).isEmpty(); else if (o instanceof FluidStack) return true; else return false; } @SideOnly(Side.CLIENT) public static boolean transferSlots(Container cont, EntityPlayer player, TransferEntry trans, boolean max) { PlayerControllerMP contr = Minecraft.getMinecraft().playerController; ItemStack stack, stack1; int n = 0; for (int s : trans.src) { if (!max && n >= trans.reqAm) break; stack = stackInSlot(cont, s); if (stack == null) continue; n += stack.stackSize; if (s == trans.dest) continue; if (max || n <= trans.reqAm) { contr.windowClick(cont.windowId, s, 0, ClickType.PICKUP, player); contr.windowClick(cont.windowId, trans.dest, 0, ClickType.PICKUP, player); contr.windowClick(cont.windowId, s, 0, ClickType.PICKUP, player); } else { if ((stack1 = stackInSlot(cont, trans.dest)) != null && !cd4017be.lib.util.Utils.itemsEqual(stack, stack1) && !clearSlot(cont, player, trans.dest)) return false; contr.windowClick(cont.windowId, s, 0, ClickType.PICKUP, player); for (int i = trans.reqAm - n + stack.stackSize; i > 0; i--) contr.windowClick(cont.windowId, trans.dest, 1, ClickType.PICKUP, player); contr.windowClick(cont.windowId, s, 0, ClickType.PICKUP, player); return true; } } return true; } @SideOnly(Side.CLIENT) public static boolean clearSlot(Container cont, EntityPlayer player, int slot) { Minecraft.getMinecraft().playerController.windowClick(cont.windowId, slot, 0, ClickType.QUICK_MOVE, player); return !cont.getSlot(slot).getHasStack(); } public static ItemStack stackInSlot(Container cont, int s) { Slot slot = cont.getSlot(s); return slot == null && !(slot instanceof SlotHolo) ? null : slot.getStack(); } public static class TransferEntry { public TransferEntry(int dest) { this.dest = dest; } public final int dest; public int reqAm; public ArrayList<Integer> src = new ArrayList<Integer>(); public ItemStack targetI; public boolean hasEnough(boolean max) { return targetI != null && targetI.stackSize >= (max ? targetI.getMaxStackSize() : reqAm); } } }
36.347826
166
0.709629
af14b1bddb4773d2dac6f68f940584a40af6d3b4
1,490
package ua.lviv.navpil.jeetutorial.jaxrs; import org.glassfish.jersey.internal.util.Base64; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import java.util.StringTokenizer; @Path("my-res") public class MyResource { @POST @Path("one") public Response one(@HeaderParam("Authorization") String authorization) { if (authorization != null && !authorization.isEmpty()) { String encodedUserPassword = authorization.replaceFirst("Basic ", ""); String usernameAndPassword = new String(Base64.decode(encodedUserPassword.getBytes())); int firstColon = usernameAndPassword.indexOf(":"); if (firstColon >= 0) { String username = usernameAndPassword.substring(0, firstColon); String password = usernameAndPassword.substring(firstColon + 1); if ("admin".equals(username) && "root".equals(password)) { return Response.ok().entity("Hello you").build(); } } } return Response .status(401) .header("WWW-Authenticate", "Basic realm=\"My Realm\"") .entity("You can't access the resource") .build(); } @GET @Path("two") public Response two() { return Response.status(200).entity("All is good").build(); } }
32.391304
99
0.608725
afd1249722b6b29b16e3df8c4a3af910a487a391
911
import ioc.Book; import ioc.Student; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author zhigang.xu * @date 2020/5/12 23:20 */ public class Main { public static void main(String[] args){ ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class); User user = (User) ac.getBean("user"); System.out.println(user.toString()); ApplicationContext xmlAc = new ClassPathXmlApplicationContext("src/main/resource/book.xml"); Book book = xmlAc.getBean("book", Book.class); System.out.println(book); ApplicationContext studentContext = new ClassPathXmlApplicationContext("../resource/student.xml"); Student student = studentContext.getBean("student", Student.class); System.out.println(student); } }
35.038462
100
0.781559
a2642dbbb28c07cc9780411f501dc1f4c8b864d1
9,923
package it.firegloves.mempoi.integration; import it.firegloves.mempoi.MemPOI; import it.firegloves.mempoi.builder.MempoiBuilder; import it.firegloves.mempoi.builder.MempoiPivotTableBuilder; import it.firegloves.mempoi.builder.MempoiSheetBuilder; import it.firegloves.mempoi.domain.MempoiSheet; import it.firegloves.mempoi.domain.MempoiTable; import it.firegloves.mempoi.exception.MempoiException; import it.firegloves.mempoi.styles.template.StandardStyleTemplate; import it.firegloves.mempoi.testutil.AssertionHelper; import it.firegloves.mempoi.testutil.TestHelper; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFPivotTable; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.sql.PreparedStatement; import java.sql.SQLException; public class PivotTableIT extends IntegrationBaseIT { @Rule public ExpectedException exceptionRule = ExpectedException.none(); private XSSFWorkbook wb = new XSSFWorkbook(); // TODO add check if table area are ovelapping? @Before public void setup() throws SQLException { this.prepStmt = this.createStatement(); } @Test public void addPivotTableWithPositionAndAreaReference() throws Exception { File fileDest = new File(this.outReportFolder.getAbsolutePath(), "test_with_pivot_table_and_position_and_area_reference.xlsx"); MempoiSheet mempoiSheet = MempoiSheetBuilder.aMempoiSheet() .withSheetName(TestHelper.SHEET_NAME) .withPrepStmt(prepStmt) .withMempoiPivotTableBuilder(TestHelper.getTestMempoiPivotTableBuilderForIT(wb, null)) .build(); MemPOI memPOI = MempoiBuilder.aMemPOI() .withWorkbook(wb) .withFile(fileDest) .withStyleTemplate(new StandardStyleTemplate()) .addMempoiSheet(mempoiSheet) .build(); String fileName = memPOI.prepareMempoiReportToFile().get(); AssertionHelper.validateGeneratedFilePivotTable(this.createStatement(), fileName, TestHelper.MEMPOI_COLUMN_NAMES, TestHelper.MEMPOI_COLUMN_NAMES, new StandardStyleTemplate(), 0); Workbook loadedWb = TestHelper.openFile(fileName); XSSFPivotTable pivotTable = ((XSSFSheet) loadedWb.getSheet(TestHelper.SHEET_NAME)).getPivotTables().get(0); AssertionHelper.assertPivotTable(pivotTable, mempoiSheet.getMempoiPivotTable().get(), mempoiSheet.getColumnList()); } @Test public void addPivotTableWithAreaReferenceSourceOnDifferentSheet() throws Exception { File fileDest = new File(this.outReportFolder.getAbsolutePath(), "test_with_pivot_table_and_area_referencce_on_different_sheet.xlsx"); MempoiSheet mempoiSheet1 = MempoiSheetBuilder.aMempoiSheet() .withSheetName(TestHelper.SHEET_NAME) .withPrepStmt(prepStmt) .build(); MempoiPivotTableBuilder mempoiPivotTableBuilder = TestHelper.getTestMempoiPivotTableBuilderForIT(wb, mempoiSheet1); MempoiSheet mempoiSheet2 = MempoiSheetBuilder.aMempoiSheet() .withSheetName(TestHelper.SHEET_NAME_2) .withPrepStmt(this.createStatement()) .withMempoiPivotTableBuilder(mempoiPivotTableBuilder) .build(); MemPOI memPOI = MempoiBuilder.aMemPOI() .withWorkbook(wb) .withFile(fileDest) .withStyleTemplate(new StandardStyleTemplate()) .addMempoiSheet(mempoiSheet1) .addMempoiSheet(mempoiSheet2) .build(); String fileName = memPOI.prepareMempoiReportToFile().get(); AssertionHelper.validateGeneratedFilePivotTable(this.createStatement(), fileName, TestHelper.MEMPOI_COLUMN_NAMES, TestHelper.MEMPOI_COLUMN_NAMES, new StandardStyleTemplate(), 0); Workbook loadedWb = TestHelper.openFile(fileName); XSSFPivotTable pivotTable = ((XSSFSheet) loadedWb.getSheet(TestHelper.SHEET_NAME_2)).getPivotTables().get(0); AssertionHelper.assertPivotTable(pivotTable, mempoiSheet2.getMempoiPivotTable().get(), mempoiSheet2.getColumnList()); } @Test public void addPivotTableWithPositionAndTableSource() throws Exception { File fileDest = new File(this.outReportFolder.getAbsolutePath(), "test_with_pivot_table_and_position_and_table.xlsx"); MempoiTable mempoiTable = TestHelper.getTestMempoiTableBuilder(wb) .withAreaReferenceSource(TestHelper.AREA_REFERENCE_TABLE_DB_DATA) .build(); MempoiPivotTableBuilder mempoiPivotTableBuilder = TestHelper.getTestMempoiPivotTableBuilderForIT(wb, null) .withAreaReferenceSource(null) .withMempoiTableSource(mempoiTable); MempoiSheet mempoiSheet = MempoiSheetBuilder.aMempoiSheet() .withSheetName(TestHelper.SHEET_NAME) .withPrepStmt(prepStmt) .withMempoiTable(mempoiTable) .withMempoiPivotTableBuilder(mempoiPivotTableBuilder) .build(); MemPOI memPOI = MempoiBuilder.aMemPOI() .withWorkbook(wb) .withFile(fileDest) .withStyleTemplate(new StandardStyleTemplate()) .addMempoiSheet(mempoiSheet) .build(); String fileName = memPOI.prepareMempoiReportToFile().get(); AssertionHelper.validateGeneratedFilePivotTable(this.createStatement(), fileName, TestHelper.MEMPOI_COLUMN_NAMES, TestHelper.MEMPOI_COLUMN_NAMES, new StandardStyleTemplate(), 0); Workbook loadedWb = TestHelper.openFile(fileName); XSSFPivotTable pivotTable = ((XSSFSheet) loadedWb.getSheet(TestHelper.SHEET_NAME)).getPivotTables().get(0); AssertionHelper.assertPivotTable(pivotTable, mempoiSheet.getMempoiPivotTable().get(), mempoiSheet.getColumnList()); } @Test public void addPivotTableWithPositionAndTableSourceOnDifferentSheet() throws Exception { File fileDest = new File(this.outReportFolder.getAbsolutePath(), "test_with_pivot_table_and_position_and_table_on_different_sheet.xlsx"); MempoiTable mempoiTable = TestHelper.getTestMempoiTableBuilder(wb) .withAreaReferenceSource(TestHelper.AREA_REFERENCE_TABLE_DB_DATA) .build(); MempoiSheet mempoiSheet1 = MempoiSheetBuilder.aMempoiSheet() .withSheetName(TestHelper.SHEET_NAME) .withPrepStmt(prepStmt) .withMempoiTable(mempoiTable) .build(); MempoiPivotTableBuilder mempoiPivotTableBuilder = TestHelper.getTestMempoiPivotTableBuilderForIT(wb, null) .withAreaReferenceSource(null) .withMempoiTableSource(mempoiTable); MempoiSheet mempoiSheet2 = MempoiSheetBuilder.aMempoiSheet() .withSheetName(TestHelper.SHEET_NAME_2) .withPrepStmt(this.createStatement()) .withMempoiPivotTableBuilder(mempoiPivotTableBuilder) .build(); MemPOI memPOI = MempoiBuilder.aMemPOI() .withWorkbook(wb) .withFile(fileDest) .withStyleTemplate(new StandardStyleTemplate()) .addMempoiSheet(mempoiSheet1) .addMempoiSheet(mempoiSheet2) .build(); String fileName = memPOI.prepareMempoiReportToFile().get(); AssertionHelper.validateGeneratedFilePivotTable(this.createStatement(), fileName, TestHelper.MEMPOI_COLUMN_NAMES, TestHelper.MEMPOI_COLUMN_NAMES, new StandardStyleTemplate(), 0); Workbook loadedWb = TestHelper.openFile(fileName); XSSFPivotTable pivotTable = ((XSSFSheet) loadedWb.getSheet(TestHelper.SHEET_NAME_2)).getPivotTables().get(0); AssertionHelper.assertPivotTable(pivotTable, mempoiSheet2.getMempoiPivotTable().get(), mempoiSheet2.getColumnList()); } @Test(expected = MempoiException.class) public void addPivotTableWithTableAsSourceContainedInNotStillGeneratedSheetWillThrowMempoiException() throws Throwable { MempoiTable mempoiTable = TestHelper.getTestMempoiTableBuilder(wb) .withAreaReferenceSource(TestHelper.AREA_REFERENCE_TABLE_DB_DATA) .build(); MempoiSheet mempoiSheet1 = MempoiSheetBuilder.aMempoiSheet() .withSheetName(TestHelper.SHEET_NAME) .withPrepStmt(prepStmt) .withMempoiTable(mempoiTable) .build(); MempoiPivotTableBuilder mempoiPivotTableBuilder = TestHelper.getTestMempoiPivotTableBuilderForIT(wb, null) .withAreaReferenceSource(null) .withMempoiTableSource(mempoiTable); MempoiSheet mempoiSheet2 = MempoiSheetBuilder.aMempoiSheet() .withSheetName(TestHelper.SHEET_NAME_2) .withPrepStmt(this.createStatement()) .withMempoiPivotTableBuilder(mempoiPivotTableBuilder) .build(); MemPOI memPOI = MempoiBuilder.aMemPOI() .withWorkbook(wb) .withFile(new File("temp")) .withStyleTemplate(new StandardStyleTemplate()) .addMempoiSheet(mempoiSheet2) .addMempoiSheet(mempoiSheet1) .build(); try { memPOI.prepareMempoiReportToFile().get(); } catch (Exception e) { throw e.getCause(); } } @Override public PreparedStatement createStatement() throws SQLException { return this.conn.prepareStatement(this.createQuery(TestHelper.TABLE_PIVOT_TABLE, TestHelper.MEMPOI_COLUMN_NAMES, TestHelper.MEMPOI_COLUMN_NAMES, -1)); } }
43.90708
186
0.698881
34c7f0cc2d12e39c86d3a24497d290306a0c2aa5
782
package dev.bkelly.phonenumber.dto; import com.fasterxml.jackson.annotation.JsonIgnore; public class PhoneNumber { private final long id; private final String number; private final Customer customer; private boolean active; public PhoneNumber(long id, String number, Customer customer, boolean active) { this.id = id; this.number = number; this.customer = customer; this.active = active; } public long getId() { return id; } public String getNumber() { return number; } public Customer getCustomer() { return customer; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } }
19.55
83
0.622762
52246dcb0f779213fb4f1b2433953bae203e9283
762
package PetSitters.auxiliary; import org.apache.commons.lang3.text.StrSubstitutor; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Map; public class ReadWebPage { public String getProcessedText(String pathToFile, Map<String, String> template) throws IOException { String path = new File(".").getCanonicalPath(); String htmlPage = new String(Files.readAllBytes(Paths.get(path + pathToFile))); return StrSubstitutor.replace(htmlPage, template); } public String getText(String pathToFile) throws IOException { String path = new File(".").getCanonicalPath(); return new String(Files.readAllBytes(Paths.get(path + pathToFile))); } }
33.130435
104
0.727034
3189aa89e9ca94ae89fe36f1f7b8f5f1ea9e64d4
4,400
/* * copyright 2012, gash * * Gash 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 poke.server.management; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import poke.core.Mgmt.Management; import poke.server.management.ManagementQueue.ManagementQueueEntry; import poke.server.managers.ElectionManager; import poke.server.managers.HeartbeatManager; import poke.server.managers.JobManager; import poke.server.managers.NetworkManager; /** * The inbound management worker is the cortex for all work related to the * Health and Status (H&S) of the node. * * Example work includes processing job bidding, elections, network connectivity * building. An instance of this worker is blocked on the socket listening for * events. If you want to approximate a timer, executes on a consistent interval * (e.g., polling, spin-lock), you will have to implement a thread that injects * events into this worker's queue. * * HB requests to this node are NOT processed here. Nodes making a request to * receive heartbeats are in essence requesting to establish an edge (comm) * between two nodes. On failure, the connecter must initiate a reconnect - to * produce the heartbeatMgr. * * On loss of connection: When a connection is lost, the emitter will not try to * establish the connection. The edge associated with the lost node is marked * failed and all outbound (enqueued) messages are dropped (TBD as we could * delay this action to allow the node to detect and re-establish the * connection). * * Connections are bi-directional (reads and writes) at this time. * * @author gash * */ public class InboundMgmtWorker extends Thread { protected static Logger logger = LoggerFactory.getLogger("management"); int workerId; boolean forever = true; public InboundMgmtWorker(ThreadGroup tgrp, int workerId) { super(tgrp, "inbound-mgmt-" + workerId); this.workerId = workerId; if (ManagementQueue.outbound == null) throw new RuntimeException("connection worker detected null queue"); } @Override public void run() { while (true) { if (!forever && ManagementQueue.inbound.size() == 0) break; try { // block until a message is enqueued ManagementQueueEntry msg = ManagementQueue.inbound.take(); if (logger.isDebugEnabled()) logger.debug("Inbound management message received"); Management mgmt = (Management) msg.req; if (mgmt.hasBeat()) { /** * Incoming: this is from a node we requested to create a * connection (edge) to. In other words, we need to track * that this connection is healthy by receiving HB messages. * * Incoming are connections this node establishes, which is * handled by the HeartbeatPusher. */ logger.info("In Inbound Beat "); HeartbeatManager.getInstance().processRequest(mgmt); /** * If we have a network (more than one node), check to see * if a election manager has been declared. If not, start an * election. * * The flaw to this approach is from a bootstrap PoV. * Consider a network of one node (myself), an event-based * monitor does not detect the leader is myself. However, I * cannot allow for each node joining the network to cause a * leader election. */ ElectionManager.getInstance().assessCurrentState(mgmt); } else if (mgmt.hasRaftmessage()) { ElectionManager.getInstance().processRequest(mgmt); } else if (mgmt.hasGraph()) { NetworkManager.getInstance().processRequest(mgmt, msg.channel); } else logger.error("Unknown management message"); } catch (InterruptedException ie) { break; } catch (Exception e) { logger.error("Unexpected processing failure, halting worker.", e); break; } } if (!forever) { logger.info("connection queue closing"); } } }
34.375
80
0.711818
966b18cf9e0522e2ec6deeb6cb6a148388fafbc7
1,885
/* * 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.usergrid.tools; import org.apache.usergrid.management.ManagementService; import org.apache.usergrid.persistence.EntityManagerFactory; import java.util.UUID; class DryRunUserOrgManager extends UserOrgManager { public DryRunUserOrgManager(EntityManagerFactory emf, ManagementService managementService) { super( emf, managementService ); } @Override public void removeUserFromOrg(OrgUser user, Org org) throws Exception { } @Override public void addUserToOrg(OrgUser user, Org org) throws Exception { } @Override public void addAppToOrg(UUID appId, Org org) throws Exception { } @Override public void removeOrgUser(OrgUser orgUser) { } @Override public void updateOrgUser(OrgUser targetUserEntity) { } @Override public void setOrgUserName(OrgUser other, String newUserName) { } @Override public void removeAppFromOrg(UUID appId, Org org) throws Exception { } @Override public void removeOrg(Org keeper, Org duplicate) throws Exception { } }
29.920635
96
0.735809
71d9581e3e10cdb6bfd4466a759c9a4fd344b83f
2,869
package com.botongsoft.rfid.ui.adapter; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import com.botongsoft.rfid.R; import com.botongsoft.rfid.common.utils.UIUtils; import com.botongsoft.rfid.ui.fragment.BaseFragment; import com.botongsoft.rfid.ui.fragment.ScanCheckPlanListFragment; import java.util.List; /**http://www.jianshu.com/p/043020843899 * http://www.daozhihun.com/p/2044 * Created by pc on 2017/6/26. * FragmentStatePagerAdapter 和前面的 FragmentPagerAdapter 一样,是继承子 PagerAdapter。但是,和 FragmentPagerAdapter 不一样的是, * 正如其类名中的 'State' 所表明的含义一样,该 PagerAdapter 的实现将只保留当前页面,当页面离开视线后,就会被消除,释放其资源; * 而在页面需要显示时,生成新的页面(就像 ListView 的实现一样)。这么实现的好处就是当拥有大量的页面时,不必在内存中占用大量的内存。 getItem() 一个该类中新增的虚函数。 函数的目的为生成新的 Fragment 对象。 Fragment.setArguments() 这种只会在新建 Fragment 时执行一次的参数传递代码,可以放在这里。 由于 FragmentStatePagerAdapter.instantiateItem() 在大多数情况下,都将调用 getItem() 来生成新的对象,因此如果在该函数中放置与数据集相关的 setter 代码, 基本上都可以在 instantiateItem() 被调用时执行,但这和设计意图不符。毕竟还有部分可能是不会调用 getItem() 的。因此这部分代码应该放到 instantiateItem() 中。 instantiateItem() 除非碰到 FragmentManager 刚好从 SavedState 中恢复了对应的 Fragment 的情况外,该函数将会调用 getItem() 函数,生成新的 Fragment 对象。新的对象将被 FragmentTransaction.add()。 FragmentStatePagerAdapter 就是通过这种方式,每次都创建一个新的 Fragment,而在不用后就立刻释放其资源,来达到节省内存占用的目的的。 destroyItem() 将 Fragment 移除,即调用 FragmentTransaction.remove(),并释放其资源。 */ public class CheckPlanFragmentAdapter extends FragmentStatePagerAdapter { private List<BaseFragment> mFragments; private final String[] titles; public CheckPlanFragmentAdapter(FragmentManager fm, List<BaseFragment> fragments) { super(fm); this.titles = UIUtils.getContext().getResources().getStringArray(R.array.check_plandetail_type); mFragments = fragments; notifyDataSetChanged(); } @Override public int getItemPosition(Object object) { if(object instanceof ScanCheckPlanListFragment){ return PagerAdapter.POSITION_NONE; }else{ return PagerAdapter.POSITION_UNCHANGED;} // 系统默认返回的是 POSITION_UNCHANGED,未改变 // return super.getItemPosition(object); } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return mFragments.size(); } @Override public CharSequence getPageTitle(int position) { return titles[position]; } // @Override // public void destroyItem(ViewGroup container, int position, Object object) { // // TODO Auto-generated method stub // Log.e( "-----destroyItem()-销毁->" , titles[position]+""); // super.destroyItem(container, position, object); // } }
37.75
138
0.727083
580c87bffb5d9d50cc424278b81ba76d9a72f03e
1,751
package tracker; import org.junit.Test; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import org.junit.Test; public class TrackerTest { ////@Test public void whenInitThenNoExceptionsAndConnectionIsNotNull() throws Exception { try (Tracker t = new Tracker()) { t.init(); assertThat(t.connectionIsNull(), is(false)); } } //@Test public void whenAddItemThenFindThisItem() throws Exception { try (Tracker t = new Tracker()) { t.init(); Item i = new Item(1, "item"); i = t.add(i); List<Item> items = t.findByName("item"); assertThat(items.get(items.size() - 1).equals(i), is(true)); } } //@Test public void whenUpdateItemThenItemUpdated() throws Exception { try (Tracker t = new Tracker()) { t.init(); Item i1 = new Item(1, "item"); i1 = t.add(i1); i1.setName("change"); t.replace(i1.getId(), i1); Item i2 = t.findById(i1.getId()); assertThat(i2.getName(), is("change")); } } //@Test public void whenDeleteNItemsThenNumberOfItemsDecreaseByN() throws Exception { try (Tracker t = new Tracker()) { t.init(); int n = t.findAll().size(); int id = 0; for (int i = 0; i < 10; i++) { id = t.add(new Item(1, "item")).getId(); } for (int j = 0; j < 5; j++) { t.delete(id - j); } assertThat(t.findAll().size(), is(n + 5)); } } }
25.376812
72
0.496859
e13284e4029ff0f0f7a8434d6e4633cf69bbaecc
7,885
// -------------------------------------------------------------------------------- // Copyright 2002-2022 Echo Three, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // -------------------------------------------------------------------------------- package com.echothree.model.control.inventory.server.logic; import com.echothree.control.user.inventory.common.spec.InventoryConditionUniversalSpec; import com.echothree.model.control.inventory.common.exception.DuplicateInventoryConditionNameException; import com.echothree.model.control.inventory.common.exception.UnknownInventoryConditionNameException; import com.echothree.model.control.inventory.common.exception.UnknownDefaultInventoryConditionException; import com.echothree.model.control.inventory.server.control.InventoryControl; import com.echothree.model.control.core.common.ComponentVendors; import com.echothree.model.control.core.common.EntityTypes; import com.echothree.model.control.core.common.exception.InvalidParameterCountException; import com.echothree.model.control.core.server.logic.EntityInstanceLogic; import com.echothree.model.data.inventory.server.entity.InventoryCondition; import com.echothree.model.data.core.server.entity.EntityInstance; import com.echothree.model.data.party.server.entity.Language; import com.echothree.util.common.message.ExecutionErrors; import com.echothree.util.common.persistence.BasePK; import com.echothree.util.server.control.BaseLogic; import com.echothree.util.server.message.ExecutionErrorAccumulator; import com.echothree.util.server.persistence.EntityPermission; import com.echothree.util.server.persistence.Session; public class InventoryConditionLogic extends BaseLogic { private InventoryConditionLogic() { super(); } private static class InventoryConditionLogicHolder { static InventoryConditionLogic instance = new InventoryConditionLogic(); } public static InventoryConditionLogic getInstance() { return InventoryConditionLogicHolder.instance; } public InventoryCondition createInventoryCondition(final ExecutionErrorAccumulator eea, final String inventoryConditionName, final Boolean isDefault, final Integer sortOrder, final Language language, final String description, final BasePK createdBy) { var inventoryControl = Session.getModelController(InventoryControl.class); InventoryCondition inventoryCondition = inventoryControl.getInventoryConditionByName(inventoryConditionName); if(inventoryCondition == null) { inventoryCondition = inventoryControl.createInventoryCondition(inventoryConditionName, isDefault, sortOrder, createdBy); if(description != null) { inventoryControl.createInventoryConditionDescription(inventoryCondition, language, description, createdBy); } } else { handleExecutionError(DuplicateInventoryConditionNameException.class, eea, ExecutionErrors.DuplicateInventoryConditionName.name(), inventoryConditionName); } return inventoryCondition; } public InventoryCondition getInventoryConditionByName(final ExecutionErrorAccumulator eea, final String inventoryConditionName, final EntityPermission entityPermission) { var inventoryControl = Session.getModelController(InventoryControl.class); InventoryCondition inventoryCondition = inventoryControl.getInventoryConditionByName(inventoryConditionName, entityPermission); if(inventoryCondition == null) { handleExecutionError(UnknownInventoryConditionNameException.class, eea, ExecutionErrors.UnknownInventoryConditionName.name(), inventoryConditionName); } return inventoryCondition; } public InventoryCondition getInventoryConditionByName(final ExecutionErrorAccumulator eea, final String inventoryConditionName) { return getInventoryConditionByName(eea, inventoryConditionName, EntityPermission.READ_ONLY); } public InventoryCondition getInventoryConditionByNameForUpdate(final ExecutionErrorAccumulator eea, final String inventoryConditionName) { return getInventoryConditionByName(eea, inventoryConditionName, EntityPermission.READ_WRITE); } public InventoryCondition getInventoryConditionByUniversalSpec(final ExecutionErrorAccumulator eea, final InventoryConditionUniversalSpec universalSpec, boolean allowDefault, final EntityPermission entityPermission) { InventoryCondition inventoryCondition = null; var inventoryControl = Session.getModelController(InventoryControl.class); String inventoryConditionName = universalSpec.getInventoryConditionName(); var parameterCount = (inventoryConditionName == null ? 0 : 1) + EntityInstanceLogic.getInstance().countPossibleEntitySpecs(universalSpec); switch(parameterCount) { case 0: if(allowDefault) { inventoryCondition = inventoryControl.getDefaultInventoryCondition(entityPermission); if(inventoryCondition == null) { handleExecutionError(UnknownDefaultInventoryConditionException.class, eea, ExecutionErrors.UnknownDefaultInventoryCondition.name()); } } else { handleExecutionError(InvalidParameterCountException.class, eea, ExecutionErrors.InvalidParameterCount.name()); } break; case 1: if(inventoryConditionName == null) { var entityInstance = EntityInstanceLogic.getInstance().getEntityInstance(eea, universalSpec, ComponentVendors.ECHOTHREE.name(), EntityTypes.InventoryCondition.name()); if(!eea.hasExecutionErrors()) { inventoryCondition = inventoryControl.getInventoryConditionByEntityInstance(entityInstance, entityPermission); } } else { inventoryCondition = getInventoryConditionByName(eea, inventoryConditionName, entityPermission); } break; default: handleExecutionError(InvalidParameterCountException.class, eea, ExecutionErrors.InvalidParameterCount.name()); break; } return inventoryCondition; } public InventoryCondition getInventoryConditionByUniversalSpec(final ExecutionErrorAccumulator eea, final InventoryConditionUniversalSpec universalSpec, boolean allowDefault) { return getInventoryConditionByUniversalSpec(eea, universalSpec, allowDefault, EntityPermission.READ_ONLY); } public InventoryCondition getInventoryConditionByUniversalSpecForUpdate(final ExecutionErrorAccumulator eea, final InventoryConditionUniversalSpec universalSpec, boolean allowDefault) { return getInventoryConditionByUniversalSpec(eea, universalSpec, allowDefault, EntityPermission.READ_WRITE); } public void deleteInventoryCondition(final ExecutionErrorAccumulator eea, final InventoryCondition inventoryCondition, final BasePK deletedBy) { var inventoryControl = Session.getModelController(InventoryControl.class); inventoryControl.deleteInventoryCondition(inventoryCondition, deletedBy); } }
53.277027
166
0.73811
ef60846e1091458a1133a8704329c76663cba613
5,941
package yooco.uchain.uchainwallet.utils; import yooco.uchain.uchainwallet.base.BaseFragment; import yooco.uchain.uchainwallet.global.Constant; import yooco.uchain.uchainwallet.view.page.assets.AssetsFragment; import yooco.uchain.uchainwallet.view.page.excitation.ExcitationFragment; import yooco.uchain.uchainwallet.view.page.me.MeFragment; import yooco.uchain.uchainwallet.view.page.me.MeManageDetailFragment; import yooco.uchain.uchainwallet.view.page.me.MeTransactionRecordFragment; import yooco.uchain.uchainwallet.view.page.me.portrait.MeCommonPortraitFragment; import yooco.uchain.uchainwallet.view.page.me.portrait.MeEnterpriseKeyFragment; import yooco.uchain.uchainwallet.view.page.me.portrait.MeEnterprisePortraitFragment; import yooco.uchain.uchainwallet.view.page.wallet.BackupFragment; import yooco.uchain.uchainwallet.view.page.wallet.ConfirmMnemonicFragment; import yooco.uchain.uchainwallet.view.page.wallet.CopyMnemonicFragment; import yooco.uchain.uchainwallet.view.page.wallet.ImportKeystoreFragment; import yooco.uchain.uchainwallet.view.page.wallet.ImportMnemonicFragment; public class FragmentFactory { private static AssetsFragment sAssetsFragment; //0 private static MeFragment sMeFragment; //1 private static ExcitationFragment sExcitationFragment; //2 private static BackupFragment sBackupFragment; private static CopyMnemonicFragment sCopyMnemonicFragment; private static ConfirmMnemonicFragment sConfirmMnemonicFragment; private static MeManageDetailFragment sMeManageDetailFragment; private static MeTransactionRecordFragment sMeTransactionRecordFragment; private static MeCommonPortraitFragment sMeCommonPortraitFragment; private static MeEnterprisePortraitFragment sMeEnterprisePortraitFragment; private static MeEnterpriseKeyFragment sMeEnterpriseKeyFragment; private static ImportMnemonicFragment sImportMnemonicFragment; private static ImportKeystoreFragment sImportKeystoreFragment; public static BaseFragment getFragment(int position) { BaseFragment baseFragment = null; switch (position) { case 0: if (null == sAssetsFragment) { sAssetsFragment = new AssetsFragment(); } baseFragment = sAssetsFragment; break; case 1: if (null == sMeFragment) { sMeFragment = new MeFragment(); } baseFragment = sMeFragment; break; case 2: if (null == sExcitationFragment) { sExcitationFragment = new ExcitationFragment(); } baseFragment = sExcitationFragment; break; default: break; } return baseFragment; } public static BaseFragment getFragment(String fragmentTag) { BaseFragment baseFragment = null; switch (fragmentTag) { case Constant.FRAGMENT_TAG_BACKUP: if (null == sBackupFragment) { sBackupFragment = new BackupFragment(); } baseFragment = sBackupFragment; break; case Constant.FRAGMENT_TAG_COPY_MNEMONIC: if (null == sCopyMnemonicFragment) { sCopyMnemonicFragment = new CopyMnemonicFragment(); } baseFragment = sCopyMnemonicFragment; break; case Constant.FRAGMENT_TAG_CONFIRM_MNEMONIC: if (null == sConfirmMnemonicFragment) { sConfirmMnemonicFragment = new ConfirmMnemonicFragment(); } baseFragment = sConfirmMnemonicFragment; break; case Constant.FRAGMENT_TAG_ME_MANAGE_DETAIL: if (null == sMeManageDetailFragment) { sMeManageDetailFragment = new MeManageDetailFragment(); } baseFragment = sMeManageDetailFragment; break; case Constant.FRAGMENT_TAG_ME_TRANSACTION_RECORD: if (null == sMeTransactionRecordFragment) { sMeTransactionRecordFragment = new MeTransactionRecordFragment(); } baseFragment = sMeTransactionRecordFragment; break; case Constant.FRAGMENT_TAG_IMPORT_MNEMONIC: if (null == sImportMnemonicFragment) { sImportMnemonicFragment = new ImportMnemonicFragment(); } baseFragment = sImportMnemonicFragment; break; case Constant.FRAGMENT_TAG_IMPORT_KEYSTORE: if (null == sImportKeystoreFragment) { sImportKeystoreFragment = new ImportKeystoreFragment(); } baseFragment = sImportKeystoreFragment; break; case Constant.FRAGMENT_TAG_ME_COMMON_PORTRAIT: if (null == sMeCommonPortraitFragment) { sMeCommonPortraitFragment = new MeCommonPortraitFragment(); } baseFragment = sMeCommonPortraitFragment; break; case Constant.FRAGMENT_TAG_ME_ENTERPRISE_PORTRAIT: if (null == sMeEnterprisePortraitFragment) { sMeEnterprisePortraitFragment = new MeEnterprisePortraitFragment(); } baseFragment = sMeEnterprisePortraitFragment; break; case Constant.FRAGMENT_TAG_ME_ENTERPRISE_KEY: if (null == sMeEnterpriseKeyFragment) { sMeEnterpriseKeyFragment = new MeEnterpriseKeyFragment(); } baseFragment = sMeEnterpriseKeyFragment; break; default: break; } return baseFragment; } }
44.335821
87
0.641643
75985a6413a47fbb027e490e97c26ac5e2d999a6
77
package com.joiller.gulimall.common.valid; public interface UpdateGroup { }
15.4
42
0.805195
8460da8ae957bf6c013bfaff00c82cce5c5d770e
4,981
package com.ruoyi.web.controller.poetry; import com.alibaba.fastjson.JSONArray; import com.ruoyi.common.annotation.Log; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.enums.BusinessType; import com.ruoyi.common.utils.file.JSONFilePoetry; import com.ruoyi.common.utils.poi.ExcelUtil; import com.ruoyi.poetry.domain.PoetryAuthor; import com.ruoyi.poetry.service.IPoetryAuthorService; import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; /** * 作者Controller * * @author ruoyi * @date 2019-12-31 */ @Controller @RequestMapping("/poetry/author") public class PoetryAuthorController extends BaseController { private String prefix = "poetry/author"; @Value("${ruoyi.profile}") private String baseLocation; @Autowired private IPoetryAuthorService poetryAuthorService; @RequiresPermissions("poetry:author:view") @GetMapping() public String author() { return prefix + "/author"; } /** * 查询作者列表 */ @RequiresPermissions("poetry:author:list") @PostMapping("/list") @ResponseBody public TableDataInfo list(PoetryAuthor poetryAuthor) { startPage(); List<PoetryAuthor> list = poetryAuthorService.selectPoetryAuthorList(poetryAuthor); return getDataTable(list); } /** * 导出作者列表 */ @RequiresPermissions("poetry:author:export") @PostMapping("/export") @ResponseBody public AjaxResult export(PoetryAuthor poetryAuthor) { List<PoetryAuthor> list = poetryAuthorService.selectPoetryAuthorList(poetryAuthor); ExcelUtil<PoetryAuthor> util = new ExcelUtil<PoetryAuthor>(PoetryAuthor.class); return util.exportExcel(list, "author"); } /** * 新增作者 */ @GetMapping("/add") public String add() { return prefix + "/add"; } /** * 新增保存作者 */ @RequiresPermissions("poetry:author:add") @Log(title = "作者", businessType = BusinessType.INSERT) @PostMapping("/add") @ResponseBody public AjaxResult addSave(PoetryAuthor poetryAuthor) { return toAjax(poetryAuthorService.insertPoetryAuthor(poetryAuthor)); } /** * 修改作者 */ @GetMapping("/edit/{id}") public String edit(@PathVariable("id") String id, ModelMap mmap) { PoetryAuthor poetryAuthor = poetryAuthorService.selectPoetryAuthorById(id); mmap.put("poetryAuthor", poetryAuthor); return prefix + "/edit"; } /** * 修改保存作者 */ @RequiresPermissions("poetry:author:edit") @Log(title = "作者", businessType = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody public AjaxResult editSave(PoetryAuthor poetryAuthor) { return toAjax(poetryAuthorService.updatePoetryAuthor(poetryAuthor)); } /** * 删除作者 */ @RequiresPermissions("poetry:author:remove") @Log(title = "作者", businessType = BusinessType.DELETE) @PostMapping( "/remove") @ResponseBody public AjaxResult remove(String ids) { return toAjax(poetryAuthorService.deletePoetryAuthorByIds(ids)); } /** * 导入诗词文章列表 */ @ApiOperation("导入作者json文件") @RequiresPermissions("poetry:author:import") @PostMapping("/authorImport") @ResponseBody public AjaxResult authorImport(@RequestParam("file") MultipartFile multipartFile) { int insertNum = 0; JSONFilePoetry jsonFilePoetry = new JSONFilePoetry(); try { // 将文件缓存到服务器,然后获取解析 JSONArray jsonArray = jsonFilePoetry.readJsonData(multipartFile); List<PoetryAuthor> poetryAuthors = jsonArray.toJavaList(PoetryAuthor.class); // 说明:json文件部分字符存在乱码问题 // int num = poetryAuthorService.batchInsertPoetryAuthor(poetryAuthors); for (PoetryAuthor poetryAuthor : poetryAuthors) { try { poetryAuthor.setCreateBy("admin"); int retNum = poetryAuthorService.insertPoetryAuthor(poetryAuthor); if(retNum>0){ insertNum++; } }catch (Exception e){ logger.error("作者新增异常:"+e.getMessage()); } } } catch (IOException e) { e.printStackTrace(); return AjaxResult.error(e.getMessage()); } return new AjaxResult(AjaxResult.Type.SUCCESS,"导入json新增作者数量:"+insertNum); } }
29.826347
91
0.663321
14afcdf24f07933178464d35e1adaf6b119c1d94
27,882
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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.dremio.dac.server; import static com.dremio.dac.server.FamilyExpectation.CLIENT_ERROR; import static com.dremio.dac.server.JobsServiceTestUtils.submitJobAndGetData; import static com.dremio.dac.server.test.SampleDataPopulator.DEFAULT_USER_NAME; import static com.dremio.service.users.SystemUser.SYSTEM_USERNAME; import static java.lang.String.format; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.FileWriter; import java.nio.file.DirectoryStream; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.UUID; import javax.ws.rs.client.Entity; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import org.apache.arrow.memory.BufferAllocator; import org.apache.hadoop.conf.Configuration; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.dremio.common.util.FileUtils; import com.dremio.common.utils.PathUtils; import com.dremio.common.utils.SqlUtils; import com.dremio.dac.api.Dataset; import com.dremio.dac.explore.model.FileFormatUI; import com.dremio.dac.explore.model.InitialPreviewResponse; import com.dremio.dac.homefiles.HomeFileConf; import com.dremio.dac.homefiles.HomeFileSystemStoragePlugin; import com.dremio.dac.homefiles.HomeFileTool; import com.dremio.dac.model.folder.Folder; import com.dremio.dac.model.folder.FolderPath; import com.dremio.dac.model.job.JobDataFragment; import com.dremio.dac.model.spaces.Home; import com.dremio.dac.model.spaces.HomeName; import com.dremio.dac.server.test.SampleDataPopulator; import com.dremio.dac.util.DatasetsUtil; import com.dremio.exec.catalog.CatalogServiceImpl; import com.dremio.exec.catalog.CatalogUser; import com.dremio.exec.catalog.MetadataRequestOptions; import com.dremio.exec.hadoop.HadoopFileSystem; import com.dremio.exec.store.CatalogService; import com.dremio.exec.store.SchemaConfig; import com.dremio.exec.store.dfs.FileSystemPlugin; import com.dremio.file.File; import com.dremio.file.FilePath; import com.dremio.io.FSInputStream; import com.dremio.io.file.FileAttributes; import com.dremio.io.file.FileSystem; import com.dremio.io.file.Path; import com.dremio.options.OptionValue; import com.dremio.service.job.proto.QueryType; import com.dremio.service.jobs.JobRequest; import com.dremio.service.jobs.JobsService; import com.dremio.service.jobs.SqlQuery; import com.dremio.service.namespace.NamespaceKey; import com.dremio.service.namespace.dataset.proto.DatasetConfig; import com.dremio.service.namespace.dataset.proto.DatasetType; import com.dremio.service.namespace.file.FileFormat; import com.dremio.service.namespace.file.proto.ExcelFileConfig; import com.dremio.service.namespace.file.proto.FileConfig; import com.dremio.service.namespace.file.proto.FileType; import com.dremio.service.namespace.file.proto.JsonFileConfig; import com.dremio.service.namespace.file.proto.TextFileConfig; import com.dremio.service.namespace.file.proto.XlsFileConfig; import com.dremio.service.namespace.proto.EntityId; import com.dremio.service.namespace.source.proto.SourceConfig; import com.dremio.service.namespace.space.proto.FolderConfig; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import io.protostuff.ByteString; /** * Test home files. */ public class TestHomeFiles extends BaseTestServer { private static final String HOME_NAME = HomeName.getUserHomePath(SampleDataPopulator.DEFAULT_USER_NAME).getName(); private BufferAllocator allocator; @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); private FileSystem fs; @Before public void setup() throws Exception { clearAllDataExceptUser(); getPopulator().populateTestUsers(); this.fs = l(HomeFileTool.class).getConf().getFilesystemAndCreatePaths(getCurrentDremioDaemon().getDACConfig().thisNode); allocator = getSabotContext().getAllocator().newChildAllocator(getClass().getName(), 0, Long.MAX_VALUE); } @After public void cleanUp() { allocator.close(); } private void checkFileData(String location) throws Exception { Path serverFileDirPath = Path.of(location); assertTrue(fs.exists(serverFileDirPath)); List<FileAttributes> files; try (DirectoryStream<FileAttributes> stream = fs.list(serverFileDirPath)) { files = Lists.newArrayList(stream); } assertEquals(1, files.size()); final FileAttributes attributes = files.get(0); int fileSize = (int)attributes.size(); final byte[] data = new byte[fileSize]; FSInputStream inputStream = fs.open(attributes.getPath()); org.apache.hadoop.io.IOUtils.readFully(inputStream, data, 0, fileSize); inputStream.close(); assertEquals("{\"person_id\": 1, \"salary\": 10}", new String(data)); } private void checkFileDoesNotExist(String location) throws Exception { Path serverFileDirPath = Path.of(location); assertFalse(fs.exists(serverFileDirPath)); } @Test public void testHome() throws Exception { Home home = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME)).buildGet(), Home.class); assertNotNull(home.getId()); java.io.File inputFile = temporaryFolder.newFile("input.json"); try(FileWriter fileWriter = new FileWriter(inputFile)) { fileWriter.write("{\"person_id\": 1, \"salary\": 10}"); } FormDataMultiPart form = new FormDataMultiPart(); FormDataBodyPart fileBody = new FormDataBodyPart("file", inputFile, MediaType.MULTIPART_FORM_DATA_TYPE); form.bodyPart(fileBody); FormDataBodyPart fileNameBody = new FormDataBodyPart("fileName", "file1"); form.bodyPart(fileNameBody); doc("upload file to staging"); File file1Staged = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/").queryParam("extension", "json")).buildPost( Entity.entity(form, form.getMediaType())), File.class); FileFormat file1StagedFormat = file1Staged.getFileFormat().getFileFormat(); assertEquals("file1", file1StagedFormat.getName()); assertEquals(asList(HOME_NAME, "file1"), file1StagedFormat.getFullPath()); assertEquals(FileType.JSON, file1StagedFormat.getFileType()); fileBody.cleanup(); checkFileData(file1StagedFormat.getLocation()); // external query String fileLocation = PathUtils.toDottedPath(Path.of(file1StagedFormat.getLocation())); SqlQuery query = new SqlQuery(format("select * from table(%s.%s (%s)) limit 500", SqlUtils.quoteIdentifier(HomeFileSystemStoragePlugin.HOME_PLUGIN_NAME), fileLocation, file1StagedFormat.toTableOptions()), SampleDataPopulator.DEFAULT_USER_NAME); doc("querying file"); try (final JobDataFragment truncData = submitJobAndGetData(l(JobsService.class), JobRequest.newBuilder() .setSqlQuery(query) .setQueryType(QueryType.UI_PREVIEW) .build(), 0, 500, allocator)) { assertEquals(1, truncData.getReturnedRowCount()); assertEquals(2, truncData.getColumns().size()); } doc("previewing staged file"); JobDataFragment data = expectSuccess(getBuilder(getAPIv2().path("/home/" + HOME_NAME + "/file_preview_unsaved/file1")).buildPost(Entity.json(file1StagedFormat)), JobDataFragment.class); assertEquals(1, data.getReturnedRowCount()); assertEquals(2, data.getColumns().size()); // finish upload File file1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_finish/file1")).buildPost(Entity.json(file1StagedFormat)), File.class); FileFormat file1Format = file1.getFileFormat().getFileFormat(); assertEquals("file1", file1Format.getName()); assertEquals(asList(HOME_NAME, "file1"), file1Format.getFullPath()); assertEquals(FileType.JSON, file1Format.getFileType()); checkFileData(file1Format.getLocation()); checkFileDoesNotExist(file1StagedFormat.getLocation()); // test upload cancel form = new FormDataMultiPart(); fileBody = new FormDataBodyPart("file", inputFile, MediaType.MULTIPART_FORM_DATA_TYPE); form.bodyPart(fileBody); form.bodyPart(new FormDataBodyPart("fileName", "file2")); doc("upload second file to staging"); File file2Staged = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/").queryParam("extension", "json")).buildPost( Entity.entity(form, form.getMediaType())), File.class); FileFormat file2StagedFormat = file2Staged.getFileFormat().getFileFormat(); assertEquals("file2", file2StagedFormat.getName()); assertEquals(asList(HOME_NAME, "file2"), file2StagedFormat.getFullPath()); assertEquals(FileType.JSON, file2StagedFormat.getFileType()); fileBody.cleanup(); checkFileData(file2StagedFormat.getLocation()); // cancel upload doc("cancel upload for second file"); expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_cancel/file2")).buildPost(Entity.json(file2StagedFormat))); checkFileDoesNotExist(file2StagedFormat.getLocation()); expectError(CLIENT_ERROR, getBuilder(getAPIv2().path("home/" + HOME_NAME + "/file/file2")).buildGet(), NotFoundErrorMessage.class); doc("getting a file"); File file2 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/file/file1")).buildGet(), File.class); FileFormat file2Format = file2.getFileFormat().getFileFormat(); assertEquals("file1", file2Format.getName()); assertEquals(asList(HOME_NAME, "file1"), file2Format.getFullPath()); assertEquals(FileType.JSON, file2Format.getFileType()); doc("querying file"); try (final JobDataFragment truncData = submitJobAndGetData(l(JobsService.class), JobRequest.newBuilder() .setSqlQuery(new SqlQuery("select * from \"" + HOME_NAME + "\".file1", SampleDataPopulator.DEFAULT_USER_NAME)) .build(), 0, 500, allocator)) { assertEquals(1, truncData.getReturnedRowCount()); assertEquals(2, truncData.getColumns().size()); } doc("creating dataset from home file"); InitialPreviewResponse response = expectSuccess(getBuilder(getAPIv2().path( "/home/" + HOME_NAME + "/new_untitled_from_file/file1")).buildPost(Entity.json("")), InitialPreviewResponse.class); assertEquals(2, response.getData().getColumns().size()); doc("renaming file"); File file3 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/file_rename/file1").queryParam("renameTo", "file1r")) .buildPost(Entity.json(new FileConfig())), File.class); FileFormat file3Format = file3.getFileFormat().getFileFormat(); assertEquals("file1r", file3Format.getName()); assertEquals(asList(HOME_NAME, "file1r"), file3Format.getFullPath()); assertEquals(FileType.JSON, file3Format.getFileType()); expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/file/file1r")).buildGet(), File.class); expectError(CLIENT_ERROR, getBuilder(getAPIv2().path("home/" + HOME_NAME + "/file/file1")).buildGet(), NotFoundErrorMessage.class); Home home1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME)).buildGet(), Home.class); assertEquals(1, home1.getContents().getFiles().size()); doc("creating a folder"); String folderPath = "home/" + HOME_NAME + "/folder/"; final Folder putFolder1 = expectSuccess(getBuilder(getAPIv2().path(folderPath)).buildPost(Entity.json("{\"name\": \"f1\"}")), Folder.class); assertEquals("f1", putFolder1.getName()); doc("get folder"); Folder f1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/folder/f1")).buildGet(), Folder.class); assertEquals("f1", f1.getName()); Assert.assertArrayEquals(new String[]{HOME_NAME, "f1"}, f1.getFullPathList().toArray()); } @Test // DX-5410 public void formatChangeForUploadedHomeFile() throws Exception { FormDataMultiPart form = new FormDataMultiPart(); FormDataBodyPart fileBody = new FormDataBodyPart("file", FileUtils.getResourceAsFile("/datasets/csv/pipe.csv"), MediaType.MULTIPART_FORM_DATA_TYPE); form.bodyPart(fileBody); form.bodyPart(new FormDataBodyPart("fileName", "pipe")); doc("uploading a text file"); File file1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/").queryParam("extension", "csv")) .buildPost(Entity.entity(form, form.getMediaType())), File.class); file1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_finish/pipe")) .buildPost(Entity.json(file1.getFileFormat().getFileFormat())), File.class); final FileFormat defaultFileFormat = file1.getFileFormat().getFileFormat(); assertTrue(defaultFileFormat instanceof TextFileConfig); assertEquals(",", ((TextFileConfig)defaultFileFormat).getFieldDelimiter()); doc("change the format settings of uploaded file"); final TextFileConfig newFileFormat = (TextFileConfig)defaultFileFormat; newFileFormat.setFieldDelimiter("|"); final FileFormat updatedFileFormat = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/file_format/pipe")) .buildPut(Entity.json(newFileFormat)), FileFormatUI.class).getFileFormat(); assertTrue(updatedFileFormat instanceof TextFileConfig); assertEquals("|", ((TextFileConfig)updatedFileFormat).getFieldDelimiter()); } @Test public void testUploadXlsxFile() throws Exception { testUploadExcelFile(false); } @Test public void testUploadXlsFile() throws Exception { testUploadExcelFile(true); } @Test public void testUploadDisabled() throws Exception { try { // disable uploads getSabotContext().getOptionManager().setOption(OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, UIOptions.ALLOW_FILE_UPLOADS.getOptionName(), false)); FormDataMultiPart form = new FormDataMultiPart(); FormDataBodyPart fileBody = new FormDataBodyPart("file", FileUtils.getResourceAsFile("/datasets/csv/pipe.csv"), MediaType.MULTIPART_FORM_DATA_TYPE); form.bodyPart(fileBody); form.bodyPart(new FormDataBodyPart("fileName", "pipe")); expectStatus(Response.Status.FORBIDDEN, getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/").queryParam("extension", "csv")).buildPost(Entity.entity(form, form.getMediaType()))); } finally { // re-enable uploads getSabotContext().getOptionManager().setOption(OptionValue.createBoolean(OptionValue.OptionType.SYSTEM, UIOptions.ALLOW_FILE_UPLOADS.getOptionName(), true)); } } private void testUploadExcelFile(final boolean isXLS) throws Exception { final String extension = isXLS ? "xls" : "xlsx"; final FileType fileType = isXLS ? FileType.XLS : FileType.EXCEL; FormDataMultiPart form = new FormDataMultiPart(); FormDataBodyPart fileBody = new FormDataBodyPart("file", FileUtils.getResourceAsFile("/testfiles/excel." + extension), MediaType.MULTIPART_FORM_DATA_TYPE); form.bodyPart(fileBody); form.bodyPart(new FormDataBodyPart("fileName", "excel")); doc("uploading excel file"); File file1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/") .queryParam("extension", extension)) .buildPost(Entity.entity(form, form.getMediaType())), File.class); file1 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_finish/excel")) .buildPost(Entity.json(file1.getFileFormat().getFileFormat())), File.class); FileFormat file1Format = file1.getFileFormat().getFileFormat(); assertEquals("excel", file1Format.getName()); assertEquals(asList(HOME_NAME, "excel"), file1Format.getFullPath()); assertEquals(fileType, file1Format.getFileType()); fileBody.cleanup(); doc("getting a excel file"); File file2 = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/file/excel")).buildGet(), File.class); FileFormat file2Format = file2.getFileFormat().getFileFormat(); assertEquals("excel", file2Format.getName()); assertEquals(asList(HOME_NAME, "excel"), file2Format.getFullPath()); assertEquals(fileType, file2Format.getFileType()); doc("querying excel file"); try (final JobDataFragment truncData = submitJobAndGetData(l(JobsService.class), JobRequest.newBuilder().setSqlQuery(new SqlQuery("select * from \"" + HOME_NAME + "\".\"excel\"", SampleDataPopulator.DEFAULT_USER_NAME)).build(), 0, 500, allocator)) { assertEquals(6, truncData.getReturnedRowCount()); assertEquals(5, truncData.getColumns().size()); } doc("previewing excel file"); if (file2Format instanceof ExcelFileConfig) { ((ExcelFileConfig) file2Format).setExtractHeader(true); } else { ((XlsFileConfig) file2Format).setExtractHeader(true); } JobDataFragment data = expectSuccess(getBuilder(getAPIv2().path("/home/" + HOME_NAME + "/file_preview/excel")).buildPost(Entity.json(file2Format)), JobDataFragment.class); assertEquals(5, data.getReturnedRowCount()); assertEquals(5, data.getColumns().size()); doc("creating dataset from excel file"); InitialPreviewResponse previewResponse = expectSuccess(getBuilder(getAPIv2().path( "/home/" + HOME_NAME + "/new_untitled_from_file/excel")).buildPost(Entity.json("")), InitialPreviewResponse.class); assertEquals(5, previewResponse.getData().getColumns().size()); } public static void uploadFile(HomeFileConf homeFileStore, Path inputFile, String name, String extension ,FileFormat fileFormat, FolderPath parent) throws Exception { FilePath filePath; if (parent == null) { filePath = new FilePath(ImmutableList.of(HomeName.getUserHomePath(DEFAULT_USER_NAME).getName(), name)); } else { List<String> path = Lists.newArrayList(parent.toPathList()); path.add(name); filePath = new FilePath(path); } FSInputStream inputStream = HadoopFileSystem.getLocal(new Configuration()).open(inputFile); FileSystem fs = homeFileStore.getFilesystemAndCreatePaths(null); final SecurityContext mockSecurityContext = mock(SecurityContext.class); when(mockSecurityContext.getUserPrincipal()).thenReturn(() -> DEFAULT_USER_NAME); Path stagingLocation = new HomeFileTool(homeFileStore, fs, "localhost", mockSecurityContext) .stageFile(filePath, extension, inputStream); Path finalLocation = new HomeFileTool(homeFileStore, fs, "localhost", mockSecurityContext) .saveFile(stagingLocation, filePath, extension); inputStream.close(); // create file in namespace fileFormat.setFullPath(filePath.toPathList()); fileFormat.setName(name); fileFormat.setLocation(finalLocation.toString()); DatasetConfig datasetConfig = DatasetsUtil.toDatasetConfig(fileFormat.asFileConfig(), DatasetType.PHYSICAL_DATASET_HOME_FILE, null, new EntityId(UUID.randomUUID().toString())); newCatalogService().getCatalog(MetadataRequestOptions.of( SchemaConfig.newBuilder(CatalogUser.from(SYSTEM_USERNAME)) .build())) .createOrUpdateDataset(newNamespaceService(), new NamespaceKey(HomeFileSystemStoragePlugin.HOME_PLUGIN_NAME), filePath.toNamespaceKey(), datasetConfig); } private void runTests(HomeFileConf homeFileStore) throws Exception { // text file Path textFile = Path.of(FileUtils.getResourceAsFile("/datasets/text/comma.txt").getAbsolutePath()); uploadFile(homeFileStore, textFile, "comma", "txt", new TextFileConfig().setFieldDelimiter(","), null); Path csvFile = Path.of(FileUtils.getResourceAsFile("/datasets/csv/comma.csv").getAbsolutePath()); uploadFile(homeFileStore, csvFile, "comma1", "csv", new TextFileConfig().setFieldDelimiter(","), null); Path jsonFile = Path.of(FileUtils.getResourceAsFile("/datasets/users.json").getAbsolutePath()); uploadFile(homeFileStore, jsonFile, "users", "json", new JsonFileConfig(), null); Path excelFile = Path.of(FileUtils.getResourceAsFile("/testfiles/excel.xlsx").getAbsolutePath()); uploadFile(homeFileStore, excelFile, "excel", "xlsx", new ExcelFileConfig(), null); // query files runQuery(l(JobsService.class), "comma", 4, 3, null, allocator); runQuery(l(JobsService.class), "comma1", 4, 3, null, allocator); runQuery(l(JobsService.class), "users", 3, 2, null, allocator); runQuery(l(JobsService.class), "excel", 6, 5, null, allocator); // add file to folder FolderPath folderPath = new FolderPath(ImmutableList.of(HomeName.getUserHomePath(DEFAULT_USER_NAME).getName(), "testupload")); newNamespaceService().addOrUpdateFolder(folderPath.toNamespaceKey(), new FolderConfig() .setName("testupload") .setFullPathList(folderPath.toPathList())); uploadFile(homeFileStore, textFile, "comma", "txt", new TextFileConfig().setFieldDelimiter(","), folderPath); runQuery(l(JobsService.class), "comma", 4, 3, folderPath, allocator); } @Test public void testNASFileStore() throws Exception { final CatalogServiceImpl catalog = (CatalogServiceImpl) l(CatalogService.class); final SourceConfig config = catalog.getManagedSource(HomeFileSystemStoragePlugin.HOME_PLUGIN_NAME).getId().getClonedConfig(); final ByteString oldConfig = config.getConfig(); final HomeFileConf nasHomeFileStore = new HomeFileConf(Path.of("file:///" + BaseTestServer.folder1.getRoot().toString() + "/" + "testNASFileStore/").toString(), "localhost"); nasHomeFileStore.getFilesystemAndCreatePaths("localhost"); config.setConnectionConf(nasHomeFileStore); catalog.getSystemUserCatalog().updateSource(config); HomeFileTool tool = l(HomeFileTool.class); try { runTests(nasHomeFileStore); } finally { tool.clear(); // reset plugin SourceConfig backConfig = catalog.getManagedSource(HomeFileSystemStoragePlugin.HOME_PLUGIN_NAME).getId().getClonedConfig(); backConfig.setConfig(oldConfig); catalog.getSystemUserCatalog().updateSource(backConfig); } } @Test public void testPDFSFileStore() throws Exception { FileSystemPlugin fsp = l(CatalogService.class).getSource(HomeFileSystemStoragePlugin.HOME_PLUGIN_NAME); HomeFileConf conf = (HomeFileConf) fsp.getConfig(); HomeFileTool tool = l(HomeFileTool.class); try { runTests(conf); } finally { tool.clear(); } } @Test public void testHomeUploadValidation() throws Exception { Home home = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME)).buildGet(), Home.class); assertNotNull(home.getId()); String homeFileName = "file2"; java.io.File inputFile = temporaryFolder.newFile("input-2.json"); try (FileWriter fileWriter = new FileWriter(inputFile)) { fileWriter.write("{\"person_id\": 1, \"salary\": 10}"); } FormDataMultiPart form = new FormDataMultiPart(); FormDataBodyPart fileBody = new FormDataBodyPart("file", inputFile, MediaType.MULTIPART_FORM_DATA_TYPE); form.bodyPart(fileBody); FormDataBodyPart fileNameBody = new FormDataBodyPart("fileName", homeFileName); form.bodyPart(fileNameBody); doc("upload file to staging"); File file1Staged = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/").queryParam("extension", "json")).buildPost( Entity.entity(form, form.getMediaType())), File.class); FileFormat file1StagedFormat = file1Staged.getFileFormat().getFileFormat(); assertEquals(homeFileName, file1StagedFormat.getName()); assertEquals(asList(HOME_NAME, homeFileName), file1StagedFormat.getFullPath()); assertEquals(FileType.JSON, file1StagedFormat.getFileType()); // change the location to the original file location's parent folder file1StagedFormat.setLocation(inputFile.getParent()); // the upload endpoints should fail given that the location is not correct expectStatus(Response.Status.BAD_REQUEST, getBuilder(getAPIv2().path("/home/" + HOME_NAME + "/file_preview_unsaved/" + homeFileName)).buildPost(Entity.json(file1StagedFormat))); expectStatus(Response.Status.BAD_REQUEST, getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_finish/" + homeFileName)).buildPost(Entity.json(file1StagedFormat))); fileBody.cleanup(); final HomeFileTool tool = l(HomeFileTool.class); final FilePath filePath = new FilePath(Arrays.asList("@dremio", "filename")); // this is the root path for a user when staging files java.nio.file.Path validRootPathForUser = Paths.get(tool.getStagingLocation(filePath, "json").getParent().toString()); // valid path assertTrue(tool.validStagingLocation(Path.of(validRootPathForUser.resolve("foo").toString()))); assertFalse(tool.validStagingLocation(Path.of(validRootPathForUser.resolve("foo/../../../../").toString()))); assertFalse(tool.validStagingLocation(Path.of("/invalid/path"))); // one level above the valid root, won't include the username and therefore invalid assertFalse(tool.validStagingLocation(Path.of(validRootPathForUser.getParent().resolve("foo").toString()))); } @Test public void testPUTRequestOnHomefile() throws Exception { final Home home = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME)).buildGet(), Home.class); assertNotNull(home.getId()); final java.io.File inputFile = temporaryFolder.newFile("input.json"); try(FileWriter fileWriter = new FileWriter(inputFile)) { fileWriter.write("{\"person_id\": 1, \"salary\": 10}"); } final String fileName = "file3"; final FormDataMultiPart form = new FormDataMultiPart(); final FormDataBodyPart fileBody = new FormDataBodyPart("file", inputFile, MediaType.MULTIPART_FORM_DATA_TYPE); form.bodyPart(fileBody); final FormDataBodyPart fileNameBody = new FormDataBodyPart("fileName", fileName); form.bodyPart(fileNameBody); doc("upload file to staging"); final File file1Staged = expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_start/").queryParam("extension", "json")).buildPost( Entity.entity(form, form.getMediaType())), File.class); final FileFormat file1StagedFormat = file1Staged.getFileFormat().getFileFormat(); assertEquals(fileName, file1StagedFormat.getName()); assertEquals(asList(HOME_NAME, fileName), file1StagedFormat.getFullPath()); assertEquals(FileType.JSON, file1StagedFormat.getFileType()); // finish upload expectSuccess(getBuilder(getAPIv2().path("home/" + HOME_NAME + "/upload_finish/" + fileName)).buildPost(Entity.json(file1StagedFormat)), File.class); fileBody.cleanup(); final Dataset dataset = expectSuccess(getBuilder(getPublicAPI(3).path("/catalog/").path("by-path").path("/%40dremio/" + fileName)).buildGet(), new GenericType<Dataset>() { }); expectSuccess(getBuilder(getPublicAPI(3).path("/catalog/").path(dataset.getId())).buildPut(Entity.json(dataset))); } }
48.322357
231
0.741554
2924af7ab710a0efdda17db6e2fdecb2b23e7df9
5,825
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.bsd.hawkularFxReports.details; import java.io.IOException; import java.util.Date; import java.util.List; import com.fasterxml.jackson.core.type.TypeReference; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import de.bsd.hawkularFxReports.Generator; import de.bsd.hawkularFxReports.ValueKeeper; import de.bsd.hawkularFxReports.model.Metric; import net.sf.dynamicreports.jasper.builder.JasperReportBuilder; import net.sf.dynamicreports.report.base.expression.AbstractSimpleExpression; import net.sf.dynamicreports.report.builder.DynamicReports; import net.sf.dynamicreports.report.builder.column.Columns; import net.sf.dynamicreports.report.builder.column.TextColumnBuilder; import net.sf.dynamicreports.report.datasource.DRDataSource; import net.sf.dynamicreports.report.definition.ReportParameters; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.design.JRDesignField; /** * A HighLow chart * * @author Heiko W. Rupp */ public class HiLoChart extends AbstractSimpleExpression<JasperReportBuilder> { private String seriesTitle; private String metricIdSuffix; public HiLoChart(String seriesTitle) { this(seriesTitle,null); } public HiLoChart(String seriesTitle, String metricIdSuffix) { this.seriesTitle = seriesTitle; this.metricIdSuffix = metricIdSuffix; } @Override public JasperReportBuilder evaluate(ReportParameters reportParameters) { // FInd the metric id, which is passed in from the outside DRDataSource ds = reportParameters.getParameterValue("REPORT_DATA_SOURCE"); // String id = ds.currentRecord.get("id"); JRDesignField field = new JRDesignField(); field.setName("id"); String id; try { id = (String) ds.getFieldValue(field); } catch (JRException e) { e.printStackTrace(); // TODO: Customise this generated block return null; } JRDataSource metrics = getMetrics(id); TextColumnBuilder<String> seriesColumn = Columns.column("series",String.class); TextColumnBuilder<Date> dateColumn = Columns.column("start",Date.class); TextColumnBuilder<Double> highColumn = Columns.column("high",Double.class); TextColumnBuilder<Double> avgColumn = Columns.column("avg",Double.class); TextColumnBuilder<Double> lowColumn = Columns.column("low",Double.class); JasperReportBuilder report = DynamicReports.report(); report.setDataSource(new JREmptyDataSource()); report.summary(DynamicReports.cht.highLowChart() .setDate(dateColumn) .setHigh(highColumn) .setLow(lowColumn) .setOpen(avgColumn) .setClose(avgColumn) .setVolume(avgColumn) .setShowOpenTicks(true) .setShowCloseTicks(true) .setDataSource(metrics) .setSeries(seriesColumn) ); return report; } public JRDataSource getMetrics(String id) { ValueKeeper keeper = ValueKeeper.getInstance(); String theId = id; if (metricIdSuffix !=null) { theId+= metricIdSuffix; } // We need to escape all the "crap" characters in the id so that the URL conforms // to java.net.URI theId = theId.replaceAll("\\[","%5B"); theId = theId.replaceAll("]","%5D"); theId = theId.replaceAll(" ","%20"); theId = theId.replaceAll("/","%2F"); String url = keeper.getBaseUrl() + "hawkular/metrics/gauges/" + theId + "/data?buckets=120"; try { System.out.println("Looking for metrics data at " + url); Request request = new Request.Builder() .url(url) .get() .addHeader("Authorization", "Basic " + keeper.getBase64Creds()) .addHeader("Accept","application/json") .addHeader("Hawkular-Tenant", keeper.getTenantId()) .build(); Response response = new OkHttpClient().newCall(request).execute(); if (response.code()!=200) { System.err.println("Fetching metrics failed: " + response.toString()); return new JREmptyDataSource(); } DRDataSource dataSource = new DRDataSource("series","start","high","avg","low"); String payload = response.body().string(); List<Metric> metrics = Generator.mapfromString(payload, new TypeReference<List<Metric>>() { }); for (Metric m : metrics) { dataSource.add(seriesTitle,new Date(m.getStart()),m.getMax(),m.getAvg(),m.getMin()); } return dataSource; } catch (IOException e) { e.printStackTrace(); // TODO: Customise this generated block } return new JREmptyDataSource(); } }
35.95679
107
0.655966
aa12674efe4cfed8c75f570c73683fd68ecbf271
2,132
/* * Copyright 2012-2013 inBloom, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.slc.sli.validation.schema; import java.util.HashMap; import java.util.Map; /** * Enumeration representing a restriction on a value. * * @author Ryan Farris <rfarris@wgen.net> * */ public enum Restriction { /** * regular expression a value must conform to */ PATTERN("pattern"), /** * exact length of a string or list */ LENGTH("length"), /** * minimum length of a string or list */ MIN_LENGTH("min-length"), /** * max length of a string or list */ MAX_LENGTH("max-length"), /** * minimum value of a number */ MIN_INCLUSIVE("min"), /** * maximum value of a number */ MAX_INCLUSIVE("max"), /** * minimum value of a number, exclusive */ MIN_EXCLUSIVE("min-exclusive"), /** * maximum value of a number, exclusive */ MAX_EXCLUSIVE("max-exclusive"); private final String value; private static final Map<String, Restriction> LOOKUP = new HashMap<String, Restriction>(); static { for (Restriction r : values()) { LOOKUP.put(r.getValue(), r); } } private Restriction(String value) { this.value = value; } public String getValue() { return value; } public static boolean isRestriction(String value) { return LOOKUP.containsKey(value); } public static Restriction fromValue(String value) { return LOOKUP.get(value); } }
24.227273
94
0.625235
b39449f5d4bbe4b3aecb2fbaaa2d6aa41f4c1fe9
651
package com.gikk.twirk.types.notice; import com.gikk.twirk.enums.NOTICE_EVENT; import com.gikk.twirk.types.TagMap; import com.gikk.twirk.types.TwitchTags; import com.gikk.twirk.types.twitchMessage.TwitchMessage; public class DefaultNoticeBuilder implements NoticeBuilder { NOTICE_EVENT event; String message; String rawLine; String rawEvent; @Override public Notice build(TwitchMessage message) { TagMap r = message.getTagMap(); this.rawEvent = r.getAsString(TwitchTags.MESSAGE_ID); this.event = NOTICE_EVENT.of(rawEvent); this.message = message.getContent(); this.rawLine = message.getRaw(); return new NoticeImpl(this); } }
24.111111
60
0.77573
96fd649877ddbe0cfba6e32a899969d4fc792497
2,770
package com.jeremy.filter; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SignatureException; import io.jsonwebtoken.impl.crypto.MacProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.Key; import java.util.HashMap; /** * Created by Jeremy on 2017/2/24. */ public class AuthFilter implements Filter { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Value("${login-CheckURL}") private String loginCheckURL; @Value("${login-PageURL}") private String loginPageURL; private HashMap keyMap; @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("filter init"); keyMap = new HashMap(); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("TestFilter"); HttpServletRequest request = (HttpServletRequest)servletRequest; HttpServletResponse response = (HttpServletResponse)servletResponse; String uri = request.getRequestURI(); if("/web".equals(uri)){ try { String key = String.valueOf(keyMap.get(request.getParameter("username"))); String token = String.valueOf(keyMap.get(request.getParameter("token"))); Jwts.parser().setSigningKey(key).parseClaimsJws(token); //OK, we can trust this JWT System.out.println("suc"); request.setAttribute("token",token); } catch (SignatureException e) { System.out.println("fail"); request.removeAttribute("token"); //don't trust the JWT! } }else if("/login".equals(uri)){ Key key = MacProvider.generateKey(); logger.debug("username:"+request.getParameter("fId")); String token = Jwts.builder() .setSubject(request.getParameter("fId")) .signWith(SignatureAlgorithm.HS512, key) .compact(); request.setAttribute("token",token); System.out.println(token); } filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { System.out.println("filter destory"); } }
32.209302
113
0.65704
9ce5a9377171bd8e4ddd7e0dc6f979dbb66bf610
1,700
/******************************************************************************* * Copyright 2018 572682 * * 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 us.dot.its.jpo.ode; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; //import mockit.integration.junit4.JMockit; //@RunWith(JMockit.class) public class SystemConfigTest { @Test public void testDoConfig() { SystemConfig testSystemConfig = new SystemConfig(14, "testSchemaName"); testSystemConfig.doConfig(); } @Test public void testSettersAndGetters() { String testSchemaName = "testSchemaName12356"; int testThreadCount = 5; SystemConfig testSystemConfig = new SystemConfig(123, "originalSchemaName"); testSystemConfig.setSchemaName(testSchemaName); testSystemConfig.setThreadCount(testThreadCount); assertEquals("Incorrect schemaName", testSchemaName, testSystemConfig.getSchemaName()); assertEquals("Incorrect threadCount", testThreadCount, testSystemConfig.getThreadCount()); } }
32.692308
98
0.662353
6437ed92687b42c9a67b8035bca0d009967fec0e
2,885
package io.redintro.graphqldemo.adapter.out.persistence; import org.junit.jupiter.api.Test; import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; public class BookJpaEntityTest { @Test public void shouldCreateBookJpaEntityNoParams() { BookJpaEntity bookJpaEntity = new BookJpaEntity(); assertThat(bookJpaEntity, is(notNullValue())); assertThat(bookJpaEntity.getId(), is(nullValue())); assertThat(bookJpaEntity.getTitle(), is(nullValue())); assertThat(bookJpaEntity.getPageCount(), is(0)); assertThat(bookJpaEntity.getAuthor(), is(nullValue())); } @Test public void shouldCreateBookJpaEntityWithoutId() { BookJpaEntity bookJpaEntity = new BookJpaEntity(bookJpaEntityFixture().getTitle(), bookJpaEntityFixture().getIsbn(), bookJpaEntityFixture().getPageCount(), bookJpaEntityFixture().getAuthor()); assertThat(bookJpaEntity.getId(), is(nullValue())); assertThat(bookJpaEntity.getTitle(), is(equalTo(bookJpaEntityFixture().getTitle()))); assertThat(bookJpaEntity.getIsbn(), is(equalTo(bookJpaEntityFixture().getIsbn()))); assertThat(bookJpaEntity.getPageCount(), is(equalTo(bookJpaEntityFixture().getPageCount()))); assertThat(bookJpaEntity.getAuthor().getId(), is(equalTo(bookJpaEntityFixture().getAuthor().getId()))); assertThat(bookJpaEntity.getAuthor().getFirstName(), is(equalTo(bookJpaEntityFixture().getAuthor().getFirstName()))); assertThat(bookJpaEntity.getAuthor().getLastName(), is(equalTo(bookJpaEntityFixture().getAuthor().getLastName()))); } @Test public void shouldCreateBookJpaEntity() { BookJpaEntity bookJpaEntity = bookJpaEntityFixture(); assertThat(bookJpaEntity.getId(), is(equalTo(bookJpaEntityFixture().getId()))); assertThat(bookJpaEntity.getTitle(), is(equalTo(bookJpaEntityFixture().getTitle()))); assertThat(bookJpaEntity.getIsbn(), is(equalTo(bookJpaEntityFixture().getIsbn()))); assertThat(bookJpaEntity.getPageCount(), is(equalTo(bookJpaEntityFixture().getPageCount()))); assertThat(bookJpaEntity.getAuthor().getId(), is(equalTo(bookJpaEntityFixture().getAuthor().getId()))); assertThat(bookJpaEntity.getAuthor().getFirstName(), is(equalTo(bookJpaEntityFixture().getAuthor().getFirstName()))); assertThat(bookJpaEntity.getAuthor().getLastName(), is(equalTo(bookJpaEntityFixture().getAuthor().getLastName()))); } private BookJpaEntity bookJpaEntityFixture() { return new BookJpaEntity(UUID.fromString("bde85949-c3c7-46d1-a9f2-b515c9dcf9fd"), "Americana", "0123456789-10", 367, new AuthorJpaEntity(UUID.fromString("0a19d1c8-b231-4993-9c01-54332228e4ca"), "Don", "DeLillo")); } }
50.614035
125
0.706412
e3a6a5498688bc9e539598122343ba6bba351544
8,154
/* * Copyright 2015-2019 Jeff Hain * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.jadecy.allx; import java.io.File; import java.util.Arrays; import java.util.List; import junit.framework.TestCase; import net.jadecy.DepUnit; import net.jadecy.ElemType; import net.jadecy.Jadecy; import net.jadecy.names.InterfaceNameFilter; import net.jadecy.names.NameFilters; import net.jadecy.parsing.ParsingFilters; import net.jadecy.parsing.test1.A; import net.jadecy.parsing.test2.B; import net.jadecy.parsing.test$.$; import net.jadecy.parsing.test$.$X; import net.jadecy.tests.JdcTestCompHelper; /** * Tests dependencies of and within this library. * * Must not be run concurrently. */ public class DepsTest extends TestCase { //-------------------------------------------------------------------------- // PUBLIC METHODS //-------------------------------------------------------------------------- public DepsTest() { } /* * Dependencies. */ public void testPackagesDeps_main() { final DepUnit depUnit = newDepUnit(Arrays.asList(JdcTestCompHelper.MAIN_SRC_PATH)); final ElemType elemType = ElemType.PACKAGE; depUnit.addAllowedDirectDeps( elemType, NameFilters.equalsName("net.jadecy"), new InterfaceNameFilter[]{ NameFilters.startsWithName("java.lang"), NameFilters.startsWithName("java.util"), NameFilters.startsWithName("java.io"), NameFilters.startsWithName("net.jadecy.code"), NameFilters.startsWithName("net.jadecy.graph"), NameFilters.startsWithName("net.jadecy.names"), NameFilters.startsWithName("net.jadecy.parsing"), NameFilters.startsWithName("net.jadecy.utils"), }); depUnit.addAllowedDirectDeps( elemType, NameFilters.equalsName("net.jadecy.cmd"), new InterfaceNameFilter[]{ NameFilters.startsWithName("java.lang"), NameFilters.startsWithName("java.util"), NameFilters.startsWithName("java.io"), NameFilters.equalsName("net.jadecy"), NameFilters.startsWithName("net.jadecy.code"), NameFilters.startsWithName("net.jadecy.names"), NameFilters.startsWithName("net.jadecy.parsing"), NameFilters.startsWithName("net.jadecy.utils"), }); depUnit.addAllowedDirectDeps( elemType, NameFilters.equalsName("net.jadecy.code"), new InterfaceNameFilter[]{ NameFilters.startsWithName("java.lang"), NameFilters.startsWithName("java.util"), NameFilters.startsWithName("java.io"), NameFilters.startsWithName("net.jadecy.graph"), NameFilters.startsWithName("net.jadecy.names"), NameFilters.startsWithName("net.jadecy.utils"), }); depUnit.addAllowedDirectDeps( elemType, NameFilters.equalsName("net.jadecy.comp"), new InterfaceNameFilter[]{ NameFilters.startsWithName("java.lang"), NameFilters.startsWithName("java.util"), NameFilters.startsWithName("java.io"), NameFilters.startsWithName("java.nio"), NameFilters.startsWithName("javax.tools"), NameFilters.startsWithName("net.jadecy.names"), NameFilters.startsWithName("net.jadecy.utils"), }); depUnit.addAllowedDirectDeps( elemType, NameFilters.equalsName("net.jadecy.graph"), new InterfaceNameFilter[]{ NameFilters.startsWithName("java.lang"), NameFilters.startsWithName("java.util"), NameFilters.startsWithName("net.jadecy.utils"), }); depUnit.addAllowedDirectDeps( elemType, NameFilters.equalsName("net.jadecy.parsing"), new InterfaceNameFilter[]{ NameFilters.startsWithName("java.lang"), NameFilters.startsWithName("java.util"), NameFilters.startsWithName("java.io"), NameFilters.startsWithName("net.jadecy.code"), NameFilters.startsWithName("net.jadecy.names"), NameFilters.startsWithName("net.jadecy.utils"), }); depUnit.addAllowedDirectDeps( elemType, NameFilters.equalsName("net.jadecy.utils"), new InterfaceNameFilter[]{ NameFilters.startsWithName("java.lang"), NameFilters.startsWithName("java.util"), NameFilters.startsWithName("java.io"), }); depUnit.checkDeps(elemType); } /* * Cycles. */ public void testClassesCycles_all() { final DepUnit depUnit = newDepUnit(JdcTestCompHelper.ALL_SRC_PATH_LIST); final ElemType elemType = ElemType.CLASS; /* * */ depUnit.addAllowedCycle( elemType, new String[]{ A.class.getName(), B.class.getName(), }); depUnit.addAllowedCycle( elemType, new String[]{ $.class.getName(), $.$$.class.getName(), }); depUnit.addAllowedCycle( elemType, new String[]{ $X.class.getName(), $X.Y.class.getName(), }); /* * */ depUnit.checkShortestCycles(elemType); } public void testPackagesCycles_all() { final DepUnit depUnit = newDepUnit(JdcTestCompHelper.ALL_SRC_PATH_LIST); final ElemType elemType = ElemType.PACKAGE; depUnit.addAllowedCycle( elemType, new String[]{ A.class.getPackage().getName(), B.class.getPackage().getName(), }); depUnit.checkShortestCycles(elemType); } //-------------------------------------------------------------------------- // PRIVATE METHODS //-------------------------------------------------------------------------- /** * @return Jadecy with parsing done. */ private static Jadecy newJadecy(List<String> srcDirPathList) { final String compDirPath = JdcTestCompHelper.ensureCompiledAndGetOutputDirPath(srcDirPathList); // We don't care about intra-class cycles. final boolean mustMergeNestedClasses = true; final boolean apiOnly = false; final Jadecy jadecy = new Jadecy( mustMergeNestedClasses, apiOnly); // We only care about this project, so we don't parse the JDK. jadecy.parser().accumulateDependencies( new File(compDirPath), ParsingFilters.defaultInstance()); return jadecy; } private static DepUnit newDepUnit(List<String> srcDirPathList) { return new DepUnit(newJadecy(srcDirPathList)); } }
36.079646
103
0.541329
c34d374843111370910d77020ed18f67238c5609
2,700
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Model; import java.io.PrintWriter; import java.util.Comparator; import java.util.List; /** * * @author Quick Fix Demons */ public class InviaDomande extends Thread { //private Socket socket; //private Scanner scanner; //private int ID; private List<Utente> utenti; private Settings impostazioni; private List<PrintWriter> output; public InviaDomande(List<PrintWriter> out, List<Utente> users, Settings imp) { super(); this.output = out; this.utenti = users; this.impostazioni = imp; } @Override public void run() { for(Domanda d : impostazioni.getQuestions()) { if(impostazioni.getIndiceDomanda() == 0) { send("Iniziamo con il gioco!"); try { Thread.sleep(5000); } catch (InterruptedException ex) { ex.printStackTrace(); } } else { send("Ottimo lavoro, prossima domanda!"); try { Thread.sleep(5000); } catch (InterruptedException ex) { ex.printStackTrace(); } } String pacchetto = "Domanda N." + (impostazioni.getIndiceDomanda() + 1) + ": " + d.getQuestion(); if(!d.isTrueOrFalse()) { for(int i = 0; i< d.getRisposte().length; i++) { pacchetto += " - " + (i + 1) + ") " + d.getRisposte()[i]; } } else { pacchetto += " - VERO - FALSO"; } send(pacchetto); try { Thread.sleep(d.getTempoRisposta() * 1000); } catch (InterruptedException ex) { ex.printStackTrace(); } System.out.println("Go next"); impostazioni.incrementaIndice(); } send("Fine partita!"); try { Thread.sleep(5000); } catch (InterruptedException ex) { ex.printStackTrace(); } String classifica = ""; utenti.sort(Comparator.comparing(Utente::getPunti)); for(int i = 0; i<utenti.size(); i++) { classifica += "#" + (i + 1) + " " + utenti.get(i).getNickname() + "\n"; } send(classifica); } public void send(String msg) { for(int i = 0; i<output.size(); i++) { output.get(i).println(msg); } } }
30
109
0.498148
7b9d999f5e221f4b76f73dcb6af652942f89980f
1,468
package fi.tiedeseura.robotstories; import android.app.Activity; import android.util.Log; /** * Created by mikko on 6.8.15. */ public class CDUConnection extends Thread { private boolean running = false; private CDUEmulator emulator; private BluetoothConnection bluetooth; private Activity activity; public CDUConnection(Activity a) { activity = a; bluetooth = new BluetoothConnection(a); emulator = new CDUEmulator(); } public void setRunning(boolean run) { running = run; } @Override public void run() { //bluetooth.start(); while (running) { //Log.d("", "CUDThread"); try { if(bluetooth.connected()) { String msg = bluetooth.readMessage(); parseMessage(msg); } sleep(100); } catch (Exception e) {} } bluetooth.cancel(); } public void sendMessage(String msg) { if(bluetooth.connected()) { bluetooth.sendMessage(msg); } else { findCDU(); bluetooth.sendMessage(msg); } } public void findCDU() { bluetooth.searchForDevices(); } public boolean parseMessage(String msg) { if(msg != null) { Log.d("CDU", msg); return true; } Log.d("CDU", "Received a null message"); return false; } }
24.065574
57
0.536785
629a07506f6b57984aac635bf801ef32160ef065
295
package online.wangxuan.java8.chap9; import java.util.List; /** * @author wangxuan * @date 2019/1/13 6:31 PM */ public class Utils { public static void paint(List<Resizable> l) { l.forEach(r -> { r.setAbsoluteSize(42, 42); r.draw(); }); } }
16.388889
49
0.555932
69c41373112edab813cd7ec92a7bf36bce93d501
1,478
package io.craft.atom.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * A Gzip utility class that zip and unzip bytes. * * @author mindwind * @version 1.0, Jun 3, 2012 */ public class GzipUtil { /** * Compress data bytes by gzip algorithm * * @param data * @return compressed data * @throws IOException */ public static byte[] gzip(byte[] data) throws IOException { if (data == null) { return data; } ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gos = null; try { gos = new GZIPOutputStream(out); gos.write(data); } finally { if (gos != null) { gos.close(); } } return out.toByteArray(); } /** * Decompress data bytes with gzip algorithm. * * @param data * @return data decompressed. * @throws IOException */ public static byte[] ungzip(byte[] data) throws IOException { if (data == null) { return data; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(data); GZIPInputStream gis = null; try { gis = new GZIPInputStream(in); byte[] buffer = new byte[1024]; int n; while ((n = gis.read(buffer)) >= 0) { out.write(buffer, 0, n); } } finally { if (gis != null) { gis.close(); } } return out.toByteArray(); } }
19.972973
62
0.650203
a3c9c6803717b6b3e57a45f7bca69aed5f6a7e16
2,209
/* * Copyright 2017 Idaho National Laboratory. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gov.inl.SIEVAS.common; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.WebUtils; /** * Class to handle the CSRF headers * @author monejh */ public class CsrfHeaderFilter extends OncePerRequestFilter { /*** * Handles the setting of the cookie for the CSRF token. * @param request The request object * @param response The response object. * @param filterChain The filterChain being used. * @throws ServletException * @throws IOException */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class .getName()); if (csrf != null) { Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN"); String token = csrf.getToken(); if (cookie == null || token != null && !token.equals(cookie.getValue())) { cookie = new Cookie("XSRF-TOKEN", token); cookie.setPath("/"); response.addCookie(cookie); } } filterChain.doFilter(request, response); } }
34.515625
84
0.684925
a11a5decf9c4b40f32bc685b71d568cd8074491c
861
package com.NowakArtur97.WorldOfManga.feature.user; import lombok.*; import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "role", schema = "world_of_manga") @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "role_id") @Setter(value = AccessLevel.PRIVATE) private Long id; @Column(name = "name") private String name; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Role)) return false; Role role = (Role) o; return Objects.equals(getId(), role.getId()) && Objects.equals(getName(), role.getName()); } @Override public int hashCode() { return Objects.hash(getId(), getName()); } }
20.023256
58
0.636469
5690dbe13186c72324a817d98c490b8ad3e0bf7f
678
package leetcode; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * @author ytjia created on 2017-09-15 19:26 */ public class FriendCirclesTest { FriendCircles.Solution solution; @Before public void setUp() throws Exception { FriendCircles friendCircles = new FriendCircles(); solution = friendCircles.new Solution(); } @Test public void testC() throws Exception { int[] a = new int[] {1, 0, 0, 1}; int[] b = new int[] {0, 1, 1, 0}; int[] c = new int[] {0, 1, 1, 1}; int[] d = new int[] {1, 0, 1, 1}; int[][] m = new int[][] {a, b, c, c}; Assert.assertEquals(1, solution.findCircleNum(m)); } }
21.1875
54
0.615044
684563ad5fe228a0834a1c78e4b455e52e991f10
622
package com.spacetimecat.concurrent.lock.example; import com.spacetimecat.concurrent.lock.Lock; final class LoggingLock implements Lock { private final Lock delegate; LoggingLock (Lock delegate) { this.delegate = delegate; } @Override public boolean acquire () { System.out.printf("%s: acquiring\n", delegate); final boolean ok = delegate.acquire(); System.out.printf("%s: %s\n", delegate, ok); return ok; } @Override public void release () { System.out.printf("%s: releasing", delegate); delegate.release(); } }
20.733333
55
0.617363
0e96077a77533e15d7ee3a8f118499f02adc7e07
1,496
import java.io.BufferedReader; import java.io.InputStreamReader; /** * @author Ketan Mehta * @date * @problem_link https://www.codechef.com/problems/HILLS */ class HILLS { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); String toks[] = null; for (int i = 0; i < t; i++) { toks = br.readLine().trim().split(" "); int n,u,d; n = Integer.parseInt(toks[0]); u = Integer.parseInt(toks[1]); d = Integer.parseInt(toks[2]); long[] hills = new long[n]; toks = br.readLine().trim().split(" "); for(int j=0; j<n; j++){ hills[j] = Integer.parseInt(toks[j]); } System.out.println(solve(hills,u,d)); } br.close(); } private static long solve(long[] hills, long u, long d) { long answer = 1; long lifeline = 1; for(int i=1; i<hills.length; i++){ long current = hills[i-1]; long next = hills[i]; if(current == next){ answer++; continue; } boolean currentIsMax = current > next; long lowerJump,higherJump; if(currentIsMax){ lowerJump = current - next; if(lowerJump <= d){ answer++; continue; } else if(lifeline == 1){ lifeline -- ; answer++; continue; } else{ break; } } else{ higherJump = next - current; if(higherJump <= u){ answer++; continue; } else{ break; } } } return answer; } }
20.493151
75
0.581551
6a97dd03616dd7a89b5fbb4cc2b7f8383de41320
2,456
/************************************************************************************ * PswGenDesktop - Manages your websites and repeatably generates passwords for them * PswGenDroid - Generates your passwords managed by PswGenDesktop on your mobile * * Copyright (C) 2005-2018 Uwe Damken * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ************************************************************************************/ package de.dknapps.pswgendroid.adapter; import android.util.JsonWriter; import de.dknapps.pswgencore.util.CommonJsonWriter; import java.io.IOException; import java.io.OutputStreamWriter; public class CommonJsonWriterAndroidImpl implements CommonJsonWriter { private JsonWriter writer; public CommonJsonWriterAndroidImpl(OutputStreamWriter outputStreamWriter) { writer = new JsonWriter(outputStreamWriter); } @Override public CommonJsonWriter beginArray() throws IOException { writer.beginArray(); return this; } @Override public CommonJsonWriter beginObject() throws IOException { writer.beginObject(); return this; } @Override public void close() throws IOException { writer.close(); } @Override public CommonJsonWriter endArray() throws IOException { writer.endArray(); return this; } @Override public CommonJsonWriter endObject() throws IOException { writer.endObject(); return this; } @Override public CommonJsonWriter name(String name) throws IOException { writer.name(name); return this; } @Override public CommonJsonWriter value(boolean value) throws IOException { writer.value(value); return this; } @Override public CommonJsonWriter value(long value) throws IOException { writer.value(value); return this; } @Override public CommonJsonWriter value(String value) throws IOException { writer.value(value); return this; } @Override public void setIndent(String indent) throws IOException { writer.setIndent(indent); } }
26.12766
86
0.708062
8b2544d54d2d6b1341ca496e4cfc77ae7c08bc89
887
package org.omg.hw.CosNotifyChannelAdmin; /** * Generated from IDL definition of exception "AdminLimitExceeded" * @author JacORB IDL compiler */ public final class AdminLimitExceeded extends org.omg.CORBA.UserException { public AdminLimitExceeded() { super(org.omg.hw.CosNotifyChannelAdmin.AdminLimitExceededHelper.id()); } public org.omg.hw.CosNotifyChannelAdmin.AdminLimit admin_property_err; public AdminLimitExceeded(java.lang.String _reason,org.omg.hw.CosNotifyChannelAdmin.AdminLimit admin_property_err) { super(org.omg.hw.CosNotifyChannelAdmin.AdminLimitExceededHelper.id()+ " " + _reason); this.admin_property_err = admin_property_err; } public AdminLimitExceeded(org.omg.hw.CosNotifyChannelAdmin.AdminLimit admin_property_err) { super(org.omg.hw.CosNotifyChannelAdmin.AdminLimitExceededHelper.id()); this.admin_property_err = admin_property_err; } }
31.678571
115
0.807215
fefabb901d875039bffe57d3d9dbf185f224f115
445
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.debugs.messaging.parser; /** * * @author van de Bugs <van.de.bugs@gmail.com> */ public class ParserException extends Exception { public ParserException(int index, char value, char expected) { super("Invalid character '" + (value > 0 ? value : "") + "' at index " + index + ", expected '" + expected + "'."); } }
26.176471
123
0.638202
03570b8c4e6c54bdd8ca7167c2d28da9de4b9312
88,323
/* * This file was automatically generated by EvoSuite * Sat Nov 07 23:09:36 GMT 2020 */ package org.objectweb.asm.jip; import org.junit.Test; import static org.junit.Assert.*; import static org.evosuite.runtime.EvoAssertions.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; import org.objectweb.asm.jip.AnnotationVisitor; import org.objectweb.asm.jip.Attribute; import org.objectweb.asm.jip.ByteVector; import org.objectweb.asm.jip.ClassWriter; import org.objectweb.asm.jip.Label; import org.objectweb.asm.jip.MethodWriter; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class MethodWriter_ESTest extends MethodWriter_ESTest_scaffolding { /** //Test case number: 0 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test000() throws Throwable { int[] intArray0 = new int[5]; int int0 = MethodWriter.getNewOffset(intArray0, intArray0, 83, (-1979)); assertEquals((-2062), int0); } /** //Test case number: 1 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test001() throws Throwable { int[] intArray0 = new int[4]; intArray0[3] = 292552704; int int0 = MethodWriter.getNewOffset(intArray0, intArray0, 7, 292552704); assertEquals(585105401, int0); } /** //Test case number: 2 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test002() throws Throwable { byte[] byteArray0 = new byte[4]; byteArray0[2] = (byte) (-4); // Undeclared exception! try { MethodWriter.readInt(byteArray0, 1); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 4 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 3 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test003() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-1447), "d/ak&N_", "org.objectweb.asm.jip.Attribute", "W0Rnn", (String[]) null, false, false); methodWriter0.classReaderOffset = (-2245); int int0 = methodWriter0.getSize(); assertEquals(6, int0); } /** //Test case number: 4 /*Coverage entropy=0.6554817739013927 */ @Test(timeout = 4000) public void test004() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O<W/Pa`!FSUQv", "X", "i* O<W/Pa`!FSUQv", stringArray0, false, false); Label label0 = new Label(); label0.position = 1; methodWriter0.visitLocalVariable("i* O<W/Pa`!FSUQv", "`", "i* O<W/Pa`!FSUQv", label0, label0, 4); } /** //Test case number: 5 /*Coverage entropy=1.539084642427773 */ @Test(timeout = 4000) public void test005() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "org.objectweb.asm.jip.ClassWriter", (String[]) null, false, true); Label label0 = new Label(); Label label1 = new Label(); Label[] labelArray0 = new Label[7]; labelArray0[0] = label0; labelArray0[1] = label1; labelArray0[2] = label0; labelArray0[3] = label1; labelArray0[4] = label1; labelArray0[5] = label1; labelArray0[6] = label1; methodWriter0.visitTableSwitchInsn(251658240, (-910), label0, labelArray0); assertEquals(7, labelArray0.length); } /** //Test case number: 6 /*Coverage entropy=0.6517565611726531 */ @Test(timeout = 4000) public void test006() throws Throwable { ClassWriter classWriter0 = new ClassWriter(463); String[] stringArray0 = new String[7]; stringArray0[0] = "f,QASJ"; stringArray0[1] = "i* O><W?/P<a`!FSUQv"; stringArray0[2] = "f,QASJ"; stringArray0[3] = "f,QASJ"; stringArray0[4] = "i* O><W?/P<a`!FSUQv"; stringArray0[5] = "i* O><W?/P<a`!FSUQv"; stringArray0[6] = "f,QASJ"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "f,QASJ", "f,QASJ", "i* O><W?/P<a`!FSUQv", stringArray0, false, false); methodWriter0.visitIincInsn(8, (-128)); } /** //Test case number: 7 /*Coverage entropy=0.6890092384766586 */ @Test(timeout = 4000) public void test007() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1048575, "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "8N\"Nh:rLs(+?`<w\"42", (String[]) null, false, false); methodWriter0.visitIincInsn(1, 127); } /** //Test case number: 8 /*Coverage entropy=1.087074155537762 */ @Test(timeout = 4000) public void test008() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "Deprecated", (String[]) null, true, false); methodWriter0.visitIincInsn(1, (-890)); } /** //Test case number: 9 /*Coverage entropy=1.0594782926538544 */ @Test(timeout = 4000) public void test009() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); methodWriter0.visitMethodInsn(2, "Bhs?", "m4n=+P$0 wj(7E", "zoh:q=W.3)1/3sS"); } /** //Test case number: 10 /*Coverage entropy=1.0710185424099148 */ @Test(timeout = 4000) public void test010() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); methodWriter0.visitFieldInsn(2328, "zoh:q=W.3)1/3sS", "SourceFile", "Lo;Y"); } /** //Test case number: 11 /*Coverage entropy=1.0437570363314084 */ @Test(timeout = 4000) public void test011() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); methodWriter0.visitTypeInsn(200, "org.objectweb.asm.jip.Label"); } /** //Test case number: 12 /*Coverage entropy=1.013261884144225 */ @Test(timeout = 4000) public void test012() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "org.objectweb.asm.jip.ClassWriter", (String[]) null, false, true); methodWriter0.visitVarInsn(127, 1); } /** //Test case number: 13 /*Coverage entropy=1.1892881679862324 */ @Test(timeout = 4000) public void test013() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); methodWriter0.visitMultiANewArrayInsn("org.objectweb.asm.jip.MethodWriter", 2); methodWriter0.visitVarInsn(168, 177); } /** //Test case number: 14 /*Coverage entropy=1.3074892671218044 */ @Test(timeout = 4000) public void test014() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); methodWriter0.visitMultiANewArrayInsn("org.objectweb.asm.jip.MethodWriter", 2); methodWriter0.visitIntInsn(131072, (-2525)); } /** //Test case number: 15 /*Coverage entropy=1.2394967485779314 */ @Test(timeout = 4000) public void test015() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "B>P1sO4", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); methodWriter0.visitInsn(177); } /** //Test case number: 16 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test016() throws Throwable { byte[] byteArray0 = new byte[12]; MethodWriter.writeShort(byteArray0, (byte)0, (byte)0); assertEquals(12, byteArray0.length); } /** //Test case number: 17 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test017() throws Throwable { byte[] byteArray0 = new byte[7]; int int0 = MethodWriter.readUnsignedShort(byteArray0, 0); assertEquals(0, int0); } /** //Test case number: 18 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test018() throws Throwable { byte[] byteArray0 = new byte[7]; byteArray0[1] = (byte)17; int int0 = MethodWriter.readUnsignedShort(byteArray0, 1); assertEquals(4352, int0); } /** //Test case number: 19 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test019() throws Throwable { byte[] byteArray0 = new byte[3]; short short0 = MethodWriter.readShort(byteArray0, (byte)0); assertEquals((short)0, short0); } /** //Test case number: 20 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test020() throws Throwable { byte[] byteArray0 = new byte[3]; byteArray0[2] = (byte) (-128); short short0 = MethodWriter.readShort(byteArray0, 1); assertEquals((short)128, short0); } /** //Test case number: 21 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test021() throws Throwable { byte[] byteArray0 = new byte[2]; byteArray0[0] = (byte) (-111); short short0 = MethodWriter.readShort(byteArray0, (byte)0); assertEquals((short) (-28416), short0); } /** //Test case number: 22 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test022() throws Throwable { byte[] byteArray0 = new byte[7]; int int0 = MethodWriter.readInt(byteArray0, (byte)0); assertEquals(0, int0); } /** //Test case number: 23 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test023() throws Throwable { byte[] byteArray0 = new byte[5]; byteArray0[3] = (byte)1; int int0 = MethodWriter.readInt(byteArray0, (byte)0); assertEquals(1, int0); } /** //Test case number: 24 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test024() throws Throwable { byte[] byteArray0 = new byte[12]; byteArray0[1] = (byte) (-58); int int0 = MethodWriter.readInt(byteArray0, 1); assertEquals((-973078528), int0); } /** //Test case number: 25 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test025() throws Throwable { // Undeclared exception! try { MethodWriter.writeShort((byte[]) null, 2169, (byte) (-33)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 26 /*Coverage entropy=1.0437570363314084 */ @Test(timeout = 4000) public void test026() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "B>P1sO4", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, true); // Undeclared exception! try { methodWriter0.visitVarInsn(168, 1443168256); fail("Expecting exception: RuntimeException"); } catch(RuntimeException e) { // // JSR/RET are not supported with computeFrames option // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 27 /*Coverage entropy=1.0239287996389363 */ @Test(timeout = 4000) public void test027() throws Throwable { ClassWriter classWriter0 = new ClassWriter((-25)); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "7}<j$.;1?", "9o)VXVr3jH*rdo;", "sJc{`$WJ7J;\"", (String[]) null, false, true); // Undeclared exception! try { methodWriter0.visitVarInsn((-25), 2562); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 28 /*Coverage entropy=1.0717300941124526 */ @Test(timeout = 4000) public void test028() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); // Undeclared exception! try { methodWriter0.visitVarInsn(233, (-5)); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 233 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 29 /*Coverage entropy=0.8981370031878679 */ @Test(timeout = 4000) public void test029() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); // Undeclared exception! try { methodWriter0.visitTypeInsn(2, (String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 30 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test030() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3333); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 3333, "sJY{`lWJ7'fRJ;\"", "}nj@|h~X$S@!Z", "sJY{`lWJ7'fRJ;\"", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitParameterAnnotation(3333, (String) null, true); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 31 /*Coverage entropy=1.0239287996389363 */ @Test(timeout = 4000) public void test031() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "H!h\"-dZC;R}", (String[]) null, false, true); // Undeclared exception! try { methodWriter0.visitMultiANewArrayInsn("", 2); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 32 /*Coverage entropy=0.3250829733914482 */ @Test(timeout = 4000) public void test032() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[4]; stringArray0[0] = "i* ,/O><W?/P<`!SU,Qv"; stringArray0[1] = "i* ,/O><W?/P<`!SU,Qv"; stringArray0[2] = "i* ,/O><W?/P<`!SU,Qv"; stringArray0[3] = "i* ,/O><W?/P<`!SU,Qv"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-783), "i* ,/O><W?/P<`!SU,Qv", "Z)'hb#w", "i* ,/O><W?/P<`!SU,Qv", stringArray0, false, false); // Undeclared exception! try { methodWriter0.visitMultiANewArrayInsn((String) null, 2); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 33 /*Coverage entropy=1.0893096789558299 */ @Test(timeout = 4000) public void test033() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); // Undeclared exception! try { methodWriter0.visitMethodInsn(2, "D4{Tz{H4$R \f", "R#^9g2(=E}yz7Sh\"2+", "D4{Tz{H4$R \f"); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 34 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test034() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3340); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-12), "sJY{`lWJ7'fRJ;\"", "sJY{`lWJ7'fRJ;\"", "sJY{`lWJ7'fRJ;\"", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitMethodInsn((-873), "sJY{`lWJ7'fRJ;\"", (String) null, "<init>"); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 35 /*Coverage entropy=0.5297061990576545 */ @Test(timeout = 4000) public void test035() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", stringArray0, false, false); Label label0 = new Label(); int[] intArray0 = new int[1]; Label[] labelArray0 = new Label[2]; labelArray0[0] = label0; // Undeclared exception! try { methodWriter0.visitLookupSwitchInsn(label0, intArray0, labelArray0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 1 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 36 /*Coverage entropy=1.0852280400722045 */ @Test(timeout = 4000) public void test036() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "-5", "zoh:q=W.3)1/3sS", "RR)JN|I1='r", (String[]) null, true, false); Label label0 = new Label(); // Undeclared exception! try { methodWriter0.visitLocalVariable("RR)JN|I1='r", "", "CYeZbkD>tljgUWi", label0, label0, 1048575); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 37 /*Coverage entropy=1.0239287996389363 */ @Test(timeout = 4000) public void test037() throws Throwable { ClassWriter classWriter0 = new ClassWriter((-4)); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "7}<j$.;1?", "9o)VXVr3jH*rdo;", "sJY{`$WJ7J;\"", (String[]) null, false, true); Label label0 = new Label(); // Undeclared exception! try { methodWriter0.visitLocalVariable("7}<j$.;1?", "7}<j$.;1?", "9o)VXVr3jH*rdo;", label0, (Label) null, 1); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 38 /*Coverage entropy=0.5297061990576545 */ @Test(timeout = 4000) public void test038() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", stringArray0, false, false); // Undeclared exception! try { methodWriter0.visitLineNumber(2, (Label) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 39 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test039() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3333); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-12), "sJY{`lWJ7'fRJ;\"", "}nj@|h~X$S@!Z", "sJY{`lWJ7'fRJ;\"", (String[]) null, false, false); Label label0 = new Label(); // Undeclared exception! try { methodWriter0.visitLdcInsn(label0); fail("Expecting exception: IllegalArgumentException"); } catch(IllegalArgumentException e) { // // value L10 // verifyException("org.objectweb.asm.jip.ClassWriter", e); } } /** //Test case number: 40 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test040() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3340); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-12), "sJY{`lWJ7'fRJ;\"", "sJY{`lWJ7'fRJ;\"", "sJY{`lWJ7'fRJ;\"", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitLabel((Label) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 41 /*Coverage entropy=1.0717300941124526 */ @Test(timeout = 4000) public void test041() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectWeb.asm.j3p.MethodWriter", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); Label label0 = new Label(); // Undeclared exception! try { methodWriter0.visitJumpInsn(395, label0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 395 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 42 /*Coverage entropy=1.0239287996389363 */ @Test(timeout = 4000) public void test042() throws Throwable { ClassWriter classWriter0 = new ClassWriter(8); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "7}<j$.;1?", "9o)VXVr3jH*rdo;", "sJY{`$WJ7J;\"", (String[]) null, false, true); // Undeclared exception! try { methodWriter0.visitIntInsn(2562, (-1169)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 43 /*Coverage entropy=1.0239287996389363 */ @Test(timeout = 4000) public void test043() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048566); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-534), "AnnotationDefault", "9o)VXVr3jH*rdo;", "AnnotationDefault", (String[]) null, false, true); // Undeclared exception! try { methodWriter0.visitIntInsn(54, (-534)); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -534 // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 44 /*Coverage entropy=1.0437570363314084 */ @Test(timeout = 4000) public void test044() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); // Undeclared exception! try { methodWriter0.visitInsn(1048575); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 1048575 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 45 /*Coverage entropy=1.0239287996389363 */ @Test(timeout = 4000) public void test045() throws Throwable { ClassWriter classWriter0 = new ClassWriter((-4)); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "7}<j$.;1?", "9o)VXVr3jH*rdo;", "sJY{`$WJ7J;\"", (String[]) null, false, true); // Undeclared exception! try { methodWriter0.visitIincInsn((-4), 2); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // -4 // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 46 /*Coverage entropy=0.9957374991778267 */ @Test(timeout = 4000) public void test046() throws Throwable { ClassWriter classWriter0 = new ClassWriter(8); String[] stringArray0 = new String[7]; stringArray0[0] = "sJY{$J7;\""; stringArray0[1] = "sJY{$J7;\""; stringArray0[2] = "sJY{$J7;\""; stringArray0[3] = "sJY{$J7;\""; stringArray0[4] = "sJY{$J7;\""; stringArray0[5] = "sJY{$J7;\""; stringArray0[6] = "sJY{$J7;\""; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 8, "sJY{$J7;\"", "sJY{$J7;\"", "sJY{$J7;\"", stringArray0, false, false); Object[] objectArray0 = new Object[4]; objectArray0[0] = (Object) "sJY{$J7;\""; objectArray0[1] = (Object) "sJY{$J7;\""; objectArray0[2] = (Object) classWriter0; // Undeclared exception! try { methodWriter0.visitFrame(1, 45, objectArray0, 251, objectArray0); fail("Expecting exception: ClassCastException"); } catch(ClassCastException e) { // // org.objectweb.asm.jip.ClassWriter cannot be cast to org.objectweb.asm.jip.Label // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 47 /*Coverage entropy=1.0437570363314084 */ @Test(timeout = 4000) public void test047() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048566); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-862), "CodUe", "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", (String[]) null, true, true); // Undeclared exception! try { methodWriter0.visitFieldInsn((-862), "", "Deprecated", ""); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 48 /*Coverage entropy=0.37677016125643675 */ @Test(timeout = 4000) public void test048() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!SU,Qv", "i* O><W?/P<`!SU,Qv", "i* O><W?/P<`!SU,Qv", stringArray0, false, false); // Undeclared exception! try { methodWriter0.visitFieldInsn(4, "WYe?&D~Uqp", ";p#6aTx,,Eom", (String) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 49 /*Coverage entropy=0.37677016125643675 */ @Test(timeout = 4000) public void test049() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<a`!FSUQv", "X", "i* O><W?/P<a`!FSUQv", stringArray0, false, false); // Undeclared exception! try { methodWriter0.visitAttribute((Attribute) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 50 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test050() throws Throwable { byte[] byteArray0 = new byte[5]; // Undeclared exception! try { MethodWriter.readUnsignedShort(byteArray0, 2325); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 2325 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 51 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test051() throws Throwable { byte[] byteArray0 = new byte[1]; // Undeclared exception! try { MethodWriter.readShort(byteArray0, (byte)0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 1 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 52 /*Coverage entropy=0.8082699580001821 */ @Test(timeout = 4000) public void test052() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); String[] stringArray0 = new String[6]; stringArray0[0] = "7HM\""; stringArray0[1] = "V#Xy"; stringArray0[2] = "V#Xy"; stringArray0[3] = "j3%7eM"; stringArray0[4] = "V#Xy"; stringArray0[5] = "V#Xy"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "StackMap", "<{uX$s4:)R{/=h._", "7HM\"", stringArray0, false, true); ByteVector byteVector0 = new ByteVector(); byteVector0.length = (-2379); // Undeclared exception! try { methodWriter0.put(byteVector0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 53 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test053() throws Throwable { Label label0 = new Label(); // Undeclared exception! try { MethodWriter.getNewOffset((int[]) null, (int[]) null, label0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 54 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test054() throws Throwable { // Undeclared exception! try { MethodWriter.getNewOffset((int[]) null, (int[]) null, 172, (-2643)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 55 /*Coverage entropy=1.5538843584684239 */ @Test(timeout = 4000) public void test055() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.ojectw}.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); Label label0 = new Label(); Label[] labelArray0 = new Label[7]; labelArray0[0] = label0; labelArray0[1] = label0; labelArray0[2] = label0; labelArray0[3] = label0; labelArray0[4] = label0; labelArray0[5] = label0; labelArray0[6] = label0; methodWriter0.visitTableSwitchInsn(2, 712, label0, labelArray0); methodWriter0.visitLabel(label0); } /** //Test case number: 56 /*Coverage entropy=1.1611208182831163 */ @Test(timeout = 4000) public void test056() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, true); methodWriter0.visitIntInsn(2, 1048575); Label label0 = new Label(); methodWriter0.visitLabel(label0); } /** //Test case number: 57 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test057() throws Throwable { Label label0 = new Label(); int[] intArray0 = new int[2]; MethodWriter.getNewOffset(intArray0, intArray0, label0); MethodWriter.getNewOffset(intArray0, intArray0, label0); assertEquals(2, intArray0.length); } /** //Test case number: 58 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test058() throws Throwable { int[] intArray0 = new int[3]; intArray0[0] = 83; int int0 = MethodWriter.getNewOffset(intArray0, intArray0, 83, 0); assertEquals((-166), int0); } /** //Test case number: 59 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test059() throws Throwable { int[] intArray0 = new int[4]; intArray0[1] = 57; int int0 = MethodWriter.getNewOffset(intArray0, intArray0, 7, 292552704); assertEquals(292552754, int0); } /** //Test case number: 60 /*Coverage entropy=0.34883209584303193 */ @Test(timeout = 4000) public void test060() throws Throwable { Label label0 = new Label(); int[] intArray0 = new int[2]; intArray0[0] = 404; MethodWriter.getNewOffset(intArray0, intArray0, label0); assertEquals(2, intArray0.length); } /** //Test case number: 61 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test061() throws Throwable { int[] intArray0 = new int[2]; int int0 = MethodWriter.getNewOffset(intArray0, intArray0, 7, 7); assertEquals(0, int0); } /** //Test case number: 62 /*Coverage entropy=0.8595318558172851 */ @Test(timeout = 4000) public void test062() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!SU,Qv", "i* O><W?/P<`!SU,Qv", "i* O><W?/P<`!SU,Qv", stringArray0, false, false); classWriter0.version = 711; methodWriter0.visitInsn(322); methodWriter0.visitFrame(2, 1, stringArray0, 2, stringArray0); ByteVector byteVector0 = new ByteVector(); methodWriter0.put(byteVector0); } /** //Test case number: 63 /*Coverage entropy=0.8595318558172851 */ @Test(timeout = 4000) public void test063() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<a`!FSUQv", "i* O><W?/P<a`!FSUQv", "i* O><W?/P<a`!FSUQv", stringArray0, false, false); methodWriter0.visitInsn(2); methodWriter0.visitFrame(943, (-660), stringArray0, 1024, stringArray0); ByteVector byteVector0 = new ByteVector(); methodWriter0.put(byteVector0); } /** //Test case number: 64 /*Coverage entropy=0.8385831894192632 */ @Test(timeout = 4000) public void test064() throws Throwable { ClassWriter classWriter0 = new ClassWriter(749); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", stringArray0, false, false); Label label0 = new Label(); methodWriter0.visitVarInsn(127, (-1731255850)); methodWriter0.visitLineNumber(1, label0); ByteVector byteVector0 = new ByteVector(); methodWriter0.put(byteVector0); } /** //Test case number: 65 /*Coverage entropy=0.728530236250064 */ @Test(timeout = 4000) public void test065() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "org.objectweb.asm.jip.MethodWriter", (String[]) null, false, false); methodWriter0.visitMultiANewArrayInsn("org.objectweb.asm.jip.MethodWriter", 2); Label label0 = new Label(); methodWriter0.visitLocalVariable("zoh:q=W.3)1/3sS", "<init>", "StackMap", label0, label0, 451); ByteVector byteVector0 = new ByteVector(22); methodWriter0.put(byteVector0); } /** //Test case number: 66 /*Coverage entropy=0.9496794169036827 */ @Test(timeout = 4000) public void test066() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "Code", "9o)VXVr3jH*rdo;", "Deprecated", (String[]) null, true, true); Attribute attribute0 = new Attribute(""); methodWriter0.visitAttribute(attribute0); ByteVector byteVector0 = new ByteVector(); // Undeclared exception! try { methodWriter0.put(byteVector0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.Attribute", e); } } /** //Test case number: 67 /*Coverage entropy=0.9783820614581062 */ @Test(timeout = 4000) public void test067() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); methodWriter0.visitAnnotationDefault(); ByteVector byteVector0 = new ByteVector(247); methodWriter0.put(byteVector0); } /** //Test case number: 68 /*Coverage entropy=0.8757787022914669 */ @Test(timeout = 4000) public void test068() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 74, "XOOH[}4f.kY;~", "zoh:q=W.3)1/3sS", (String) null, (String[]) null, true, true); ByteVector byteVector0 = new ByteVector(); methodWriter0.put(byteVector0); } /** //Test case number: 69 /*Coverage entropy=0.5779217946828968 */ @Test(timeout = 4000) public void test069() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[4]; stringArray0[0] = "i* ,/O><W?/P<`!SU,Qv"; stringArray0[1] = "i* ,/O><W?/P<`!SU,Qv"; stringArray0[2] = "i* ,/O><W?/P<`!SU,Qv"; stringArray0[3] = "i* ,/O><W?/P<`!SU,Qv"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "i* ,/O><W?/P<`!SU,Qv", "i* ,/O><W?/P<`!SU,Qv", "i* ,/O><W?/P<`!SU,Qv", stringArray0, false, false); ByteVector byteVector0 = new ByteVector(); methodWriter0.put(byteVector0); } /** //Test case number: 70 /*Coverage entropy=1.0223031288781026 */ @Test(timeout = 4000) public void test070() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); methodWriter0.visitFieldInsn(6, "Lo;Y", "FD5!1=^-LiyXa\"", "9o)VXVr3jH*rdo;"); ByteVector byteVector0 = classWriter0.pool; methodWriter0.put(byteVector0); } /** //Test case number: 71 /*Coverage entropy=0.8981370031878679 */ @Test(timeout = 4000) public void test071() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "B>P1sO4", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); MethodWriter methodWriter1 = classWriter0.firstMethod; methodWriter1.classReaderOffset = 1443168256; ByteVector byteVector0 = new ByteVector(); // Undeclared exception! try { methodWriter1.put(byteVector0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 72 /*Coverage entropy=0.6474466390346325 */ @Test(timeout = 4000) public void test072() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 711, "j3%eM", "j3%eM", (String) null, stringArray0, false, false); int int0 = methodWriter0.getSize(); assertEquals(8, int0); } /** //Test case number: 73 /*Coverage entropy=0.6693279632926454 */ @Test(timeout = 4000) public void test073() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3126); String[] stringArray0 = new String[1]; stringArray0[0] = "-Se9`Q+i'bu_"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-536), "B-r4-GX5X", "-Se9`Q+i'bu_", "B-r4-GX5X", stringArray0, false, false); classWriter0.visit(1088, 3126, ",", "-Se9`Q+i'bu_", "char", stringArray0); int int0 = methodWriter0.getSize(); assertEquals(32, int0); } /** //Test case number: 74 /*Coverage entropy=0.6693279632926454 */ @Test(timeout = 4000) public void test074() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3126); String[] stringArray0 = new String[1]; stringArray0[0] = "-Se9`Q+i'bu_"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-536), "B-r4-GX5X", "-Se9`Q+i'bu_", "B-r4-GX5X", stringArray0, false, false); int int0 = methodWriter0.getSize(); assertEquals(38, int0); } /** //Test case number: 75 /*Coverage entropy=1.0889979745227922 */ @Test(timeout = 4000) public void test075() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!SU,Qv", "i* O><W?/P<`!SU,Qv", "i* O><W?/P<`!SU,Qv", stringArray0, false, false); classWriter0.version = 711; methodWriter0.visitInsn(322); methodWriter0.visitFrame(2, 1, stringArray0, 2, stringArray0); int int0 = methodWriter0.getSize(); assertEquals(46, int0); } /** //Test case number: 76 /*Coverage entropy=1.0889979745227922 */ @Test(timeout = 4000) public void test076() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!SU,Qv", "i* O><W?/P<`!SU,Qv", "i* O><W?/P<`!SU,Qv", stringArray0, false, false); methodWriter0.visitInsn(322); methodWriter0.visitFrame(2, 1, stringArray0, 2, stringArray0); int int0 = methodWriter0.getSize(); assertEquals(46, int0); } /** //Test case number: 77 /*Coverage entropy=1.0403827810064956 */ @Test(timeout = 4000) public void test077() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "sJY{`lWJ7'fRJ;\"", "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", (String[]) null, false, false); methodWriter0.visitVarInsn(1, 1048575); Label label0 = new Label(); methodWriter0.visitLineNumber((-1731255850), label0); int int0 = methodWriter0.getSize(); assertEquals(50, int0); } /** //Test case number: 78 /*Coverage entropy=1.0280893773288982 */ @Test(timeout = 4000) public void test078() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<a`!FSUQv", "i* O><W?/P<a`!FSUQv", "i* O><W?/P<a`!FSUQv", stringArray0, false, false); Label label0 = new Label(); methodWriter0.visitLocalVariable("i* O><W?/P<a`!FSUQv", "`", "i* O><W?/P<a`!FSUQv", label0, label0, 4); methodWriter0.visitInsn(2); int int0 = methodWriter0.getSize(); assertEquals(71, int0); } /** //Test case number: 79 /*Coverage entropy=0.8981370031878679 */ @Test(timeout = 4000) public void test079() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "B>P1sO4", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); MethodWriter methodWriter1 = classWriter0.firstMethod; methodWriter1.classReaderOffset = 1443168256; int int0 = methodWriter1.getSize(); assertEquals(6, int0); } /** //Test case number: 80 /*Coverage entropy=0.9957374991778267 */ @Test(timeout = 4000) public void test080() throws Throwable { ClassWriter classWriter0 = new ClassWriter(8); String[] stringArray0 = new String[7]; stringArray0[0] = "sJY{$J7;\""; stringArray0[1] = "sJY{$J7;\""; stringArray0[2] = "sJY{$J7;\""; stringArray0[3] = "sJY{$J7;\""; stringArray0[4] = "sJY{$J7;\""; stringArray0[5] = "sJY{$J7;\""; stringArray0[6] = "sJY{$J7;\""; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 8, "sJY{$J7;\"", "sJY{$J7;\"", "sJY{$J7;\"", stringArray0, false, false); Object[] objectArray0 = new Object[4]; // Undeclared exception! try { methodWriter0.visitFrame(1, 45, objectArray0, 251, objectArray0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 81 /*Coverage entropy=1.438446269922414 */ @Test(timeout = 4000) public void test081() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); Label label0 = new Label(); methodWriter0.visitLabel(label0); methodWriter0.visitJumpInsn((byte)90, label0); methodWriter0.visitMaxs(167, 2); } /** //Test case number: 82 /*Coverage entropy=1.4166810979529996 */ @Test(timeout = 4000) public void test082() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); methodWriter0.visitIntInsn(2, 1048575); Label label0 = new Label(); methodWriter0.visitLabel(label0); methodWriter0.visitMaxs(167, 2); } /** //Test case number: 83 /*Coverage entropy=0.5623351446188083 */ @Test(timeout = 4000) public void test083() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3333); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-12), "sJY{`lWJ7'fRJ;\"", "}nj@|h~X$S@!Z", "sJY{`lWJ7'fRJ;\"", (String[]) null, false, false); methodWriter0.visitMaxs(3333, 1); } /** //Test case number: 84 /*Coverage entropy=1.0437570363314084 */ @Test(timeout = 4000) public void test084() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048566); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "CodUe", "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", (String[]) null, true, true); // Undeclared exception! try { methodWriter0.visitMaxs(1225, 1225); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 15 // verifyException("org.objectweb.asm.jip.Type", e); } } /** //Test case number: 85 /*Coverage entropy=0.5297061990576545 */ @Test(timeout = 4000) public void test085() throws Throwable { ClassWriter classWriter0 = new ClassWriter(749); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", stringArray0, false, false); Label label0 = new Label(); methodWriter0.visitLineNumber(1598, label0); methodWriter0.visitLineNumber(1, label0); } /** //Test case number: 86 /*Coverage entropy=1.087074155537762 */ @Test(timeout = 4000) public void test086() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.Meth.dWriter", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); Label label0 = new Label(); methodWriter0.visitLocalVariable("", "2/Gh>OJI)\"QLx", "@", label0, label0, 253); } /** //Test case number: 87 /*Coverage entropy=0.6901856760188042 */ @Test(timeout = 4000) public void test087() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<a`!FSUQv", "X", "i* O><W?/P<a`!FSUQv", stringArray0, false, false); Label label0 = new Label(); methodWriter0.visitLocalVariable("X", "ConstantValue", "#d7%Q", label0, label0, 1); methodWriter0.visitLocalVariable("i* O><W?/P<a`!FSUQv", "`", "i* O><W?/P<a`!FSUQv", label0, label0, 4); } /** //Test case number: 88 /*Coverage entropy=1.080527626604172 */ @Test(timeout = 4000) public void test088() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "org.objectweb.asm.jip.ClassWriter", (String[]) null, false, true); Label label0 = new Label(); methodWriter0.visitLocalVariable("Deprecated", "Deprecated", "java/lang/Class", label0, label0, (-940)); } /** //Test case number: 89 /*Coverage entropy=1.1237577486092754 */ @Test(timeout = 4000) public void test089() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048566); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "CodUe", "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", (String[]) null, true, true); Label label0 = new Label(); methodWriter0.visitLocalVariable("CodUe", "java/lang/Throwable", (String) null, label0, label0, (-890)); methodWriter0.visitInsn(1); ByteVector byteVector0 = new ByteVector(1048566); methodWriter0.put(byteVector0); } /** //Test case number: 90 /*Coverage entropy=0.5297061990576545 */ @Test(timeout = 4000) public void test090() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<a`!FSUQv", "X", "i* O><W?/P<a`!FSUQv", stringArray0, false, false); Label label0 = new Label(); methodWriter0.visitTryCatchBlock(label0, label0, label0, "X"); } /** //Test case number: 91 /*Coverage entropy=0.6554817739013927 */ @Test(timeout = 4000) public void test091() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!SU,Qv", "i* O><W?/P<`!SU,Qv", "i* O><W?/P<`!SU,Qv", stringArray0, false, false); Label label0 = new Label(); methodWriter0.visitTryCatchBlock(label0, label0, label0, (String) null); methodWriter0.visitTryCatchBlock(label0, label0, label0, "i* O><W?/P<`!SU,Qv"); } /** //Test case number: 92 /*Coverage entropy=0.5297061990576545 */ @Test(timeout = 4000) public void test092() throws Throwable { ClassWriter classWriter0 = new ClassWriter(749); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", stringArray0, false, false); Label label0 = new Label(); Label[] labelArray0 = new Label[1]; // Undeclared exception! try { methodWriter0.visitLookupSwitchInsn(label0, (int[]) null, labelArray0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 93 /*Coverage entropy=0.6001660731596457 */ @Test(timeout = 4000) public void test093() throws Throwable { ClassWriter classWriter0 = new ClassWriter((-2611)); String[] stringArray0 = new String[1]; stringArray0[0] = "i* ?/I><W?/P<`!SU,Qv"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-2611), "i* ?/I><W?/P<`!SU,Qv", "i* ?/I><W?/P<`!SU,Qv", "i* ?/I><W?/P<`!SU,Qv", stringArray0, false, false); Label label0 = new Label(); int[] intArray0 = new int[2]; Label[] labelArray0 = new Label[0]; methodWriter0.visitLookupSwitchInsn(label0, intArray0, labelArray0); assertEquals(2, intArray0.length); } /** //Test case number: 94 /*Coverage entropy=0.992281974852574 */ @Test(timeout = 4000) public void test094() throws Throwable { ClassWriter classWriter0 = new ClassWriter(248); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 26, "4,aowZ{szKS?", "9o)VXVr3jH*rdo;", (String) null, (String[]) null, true, false); Label label0 = new Label(); Label[] labelArray0 = new Label[1]; // Undeclared exception! try { methodWriter0.visitTableSwitchInsn(2, 711, label0, labelArray0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 95 /*Coverage entropy=1.080527626604172 */ @Test(timeout = 4000) public void test095() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "7}<j$.;1?", "9o)VXVr3jH*rdo;", "7}<j$.;1?", (String[]) null, false, true); methodWriter0.visitIincInsn(2, (-1312)); } /** //Test case number: 96 /*Coverage entropy=1.0720433435750707 */ @Test(timeout = 4000) public void test096() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "org.objectweb.asm.jip.ClassWriter", (String[]) null, false, true); methodWriter0.visitIincInsn(737, (-128)); } /** //Test case number: 97 /*Coverage entropy=1.087074155537762 */ @Test(timeout = 4000) public void test097() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); methodWriter0.visitIincInsn(2, 22); } /** //Test case number: 98 /*Coverage entropy=1.2869339397166673 */ @Test(timeout = 4000) public void test098() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); methodWriter0.visitMultiANewArrayInsn("org.objectweb.asm.jip.MethodWriter", 2); methodWriter0.visitLdcInsn("org.objectweb.asm.jip.MethodWriter"); } /** //Test case number: 99 /*Coverage entropy=1.080527626604172 */ @Test(timeout = 4000) public void test099() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-899), "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "Deprecated", (String[]) null, true, false); methodWriter0.visitLdcInsn(classWriter0.COMPUTE_MAXS); assertEquals(1, ClassWriter.COMPUTE_MAXS); } /** //Test case number: 100 /*Coverage entropy=1.0720433435750707 */ @Test(timeout = 4000) public void test100() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048559); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "sJY{`lWJ7'fRJ;\"", "9o)VXV)^bH*rdo;", "o;:*U$;mV;aQe[#9w", (String[]) null, false, true); methodWriter0.visitLdcInsn("9o)VXV)^bH*rdo;"); } /** //Test case number: 101 /*Coverage entropy=0.6554817739013927 */ @Test(timeout = 4000) public void test101() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<a`!FSUQv", "i* O><W?/P<a`!FSUQv", "i* O><W?/P<a`!FSUQv", stringArray0, false, false); methodWriter0.visitLdcInsn(1); } /** //Test case number: 102 /*Coverage entropy=0.6108643020548935 */ @Test(timeout = 4000) public void test102() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<a`!FSUQv", "X", "i* O><W?/P<a`!FSUQv", stringArray0, false, false); Label label0 = new Label(); methodWriter0.visitLabel(label0); } /** //Test case number: 103 /*Coverage entropy=1.1889247904866966 */ @Test(timeout = 4000) public void test103() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048566); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "CodUe", "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", (String[]) null, true, true); Label label0 = new Label(); methodWriter0.visitLabel(label0); methodWriter0.visitIincInsn(2, 185); methodWriter0.visitLabel(label0); } /** //Test case number: 104 /*Coverage entropy=1.2087598339150845 */ @Test(timeout = 4000) public void test104() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048566); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", (String[]) null, true, true); Label label0 = new Label(); methodWriter0.visitLabel(label0); methodWriter0.visitJumpInsn(166, label0); } /** //Test case number: 105 /*Coverage entropy=1.2312356911067468 */ @Test(timeout = 4000) public void test105() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", (String[]) null, true, false); Label label0 = new Label(); methodWriter0.visitJumpInsn(2, label0); } /** //Test case number: 106 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test106() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3340); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-12), "sJY{`lWJ7'fRJ;\"", "sJY{`lWJ7'fRJ;\"", "sJY{`lWJ7'fRJ;\"", (String[]) null, false, false); Label label0 = new Label(); methodWriter0.visitJumpInsn((-12), label0); } /** //Test case number: 107 /*Coverage entropy=1.0594782926538544 */ @Test(timeout = 4000) public void test107() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "B>P1sO4", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); methodWriter0.visitMethodInsn(247, "Mr@B'SC@", "B>P1sO4", "zoh:q=W.3)1/3sS"); } /** //Test case number: 108 /*Coverage entropy=0.6791932659915256 */ @Test(timeout = 4000) public void test108() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", stringArray0, false, false); methodWriter0.visitMethodInsn((-899), "sJY{`lWJ7'fRJ;\"", "sJY{`lWJ7'fRJ;\"", "1HdOrL|t_4/toWC1%$K"); } /** //Test case number: 109 /*Coverage entropy=1.0795295733255184 */ @Test(timeout = 4000) public void test109() throws Throwable { ClassWriter classWriter0 = new ClassWriter((-4)); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "7}<j$.;1?", "9o)VXVr3jH*rdo;", "sJY{`$WJ7J;\"", (String[]) null, false, true); methodWriter0.visitMethodInsn(2, "Ljava/lang/Synthetic;", "sJY{`$WJ7J;\"", "Ljava/lang/Synthetic;"); } /** //Test case number: 110 /*Coverage entropy=1.0710185424099148 */ @Test(timeout = 4000) public void test110() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "B>P1sO4", "zoh:q=W.3)1/3sS", "RR)JN|I1='r", (String[]) null, true, false); methodWriter0.visitFieldInsn(178, "RA'R~yHC/\"#2X", "RA'R~yHC/\"#2X", "RR)JN|I1='r"); } /** //Test case number: 111 /*Coverage entropy=1.0437570363314084 */ @Test(timeout = 4000) public void test111() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); methodWriter0.visitTypeInsn(90, "zoh:q=W.3)1/3sS"); } /** //Test case number: 112 /*Coverage entropy=0.9701157839869381 */ @Test(timeout = 4000) public void test112() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048559); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "sJY{`lWJ7'fRJ;\"", "9o)VXV)^bH*rdo;", "o;:*U$;mV;aQe[#9w", (String[]) null, false, true); methodWriter0.visitTypeInsn(2, "sJY{`lWJ7'fRJ;\""); } /** //Test case number: 113 /*Coverage entropy=0.37677016125643675 */ @Test(timeout = 4000) public void test113() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<a`!FSUQv", "X", "i* O><W?/P<a`!FSUQv", stringArray0, false, false); methodWriter0.visitTypeInsn(711, ""); } /** //Test case number: 114 /*Coverage entropy=0.6931471805599453 */ @Test(timeout = 4000) public void test114() throws Throwable { ClassWriter classWriter0 = new ClassWriter(65535); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "InnerClasses", "InnerClasses", "InnerClasses", stringArray0, false, false); methodWriter0.visitVarInsn(169, (-283)); } /** //Test case number: 115 /*Coverage entropy=1.003659491091816 */ @Test(timeout = 4000) public void test115() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "B>P1sO4", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); methodWriter0.visitVarInsn(57, 2063); } /** //Test case number: 116 /*Coverage entropy=1.0465634069578553 */ @Test(timeout = 4000) public void test116() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); methodWriter0.visitVarInsn(24, 24); } /** //Test case number: 117 /*Coverage entropy=1.070235949193081 */ @Test(timeout = 4000) public void test117() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048596); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "sJY{`lWJ7'fRJ;\"", "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", (String[]) null, false, true); methodWriter0.visitVarInsn(22, (-904)); } /** //Test case number: 118 /*Coverage entropy=1.3003524627599985 */ @Test(timeout = 4000) public void test118() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "B>P1sO4", "zoh:q=W.3)1/3sS", "RR)JN|I1='r", (String[]) null, true, false); methodWriter0.visitVarInsn(166, (-3946)); methodWriter0.visitLdcInsn(classWriter0.COMPUTE_MAXS); assertEquals(2, ClassWriter.COMPUTE_FRAMES); } /** //Test case number: 119 /*Coverage entropy=1.003659491091816 */ @Test(timeout = 4000) public void test119() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "Code", "9o)VXVr3jH*rdo;", "Code", (String[]) null, true, false); methodWriter0.visitVarInsn(5, 2); } /** //Test case number: 120 /*Coverage entropy=1.3546053317232447 */ @Test(timeout = 4000) public void test120() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); methodWriter0.visitFieldInsn(6, "Lo;Y", "FD5!1=^-LiyXa\"", "9o)VXVr3jH*rdo;"); methodWriter0.visitIntInsn(737, 16777216); } /** //Test case number: 121 /*Coverage entropy=0.5623351446188083 */ @Test(timeout = 4000) public void test121() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3333); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-12), "sJY{`lWJ7'fRJ;\"", "}nj@|h~X$S@!Z", "sJY{`lWJ7'fRJ;\"", (String[]) null, false, false); methodWriter0.visitIntInsn(24, 377); } /** //Test case number: 122 /*Coverage entropy=1.2394967485779314 */ @Test(timeout = 4000) public void test122() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); methodWriter0.visitInsn(172); } /** //Test case number: 123 /*Coverage entropy=1.0893096789558299 */ @Test(timeout = 4000) public void test123() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "o'Y", (String[]) null, true, false); methodWriter0.visitInsn(179); } /** //Test case number: 124 /*Coverage entropy=1.0852280400722045 */ @Test(timeout = 4000) public void test124() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "Code", "9o)VXVr3jH*rdo;", "Code", (String[]) null, true, false); methodWriter0.visitInsn(1); } /** //Test case number: 125 /*Coverage entropy=1.0437570363314084 */ @Test(timeout = 4000) public void test125() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "Deprecated", (String[]) null, true, true); // Undeclared exception! try { methodWriter0.visitInsn((-890)); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 126 /*Coverage entropy=0.8468143807325634 */ @Test(timeout = 4000) public void test126() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[4]; stringArray0[0] = "i* ,/O><W?/P<`!SU,Qv"; stringArray0[1] = "i* ,/O><W?/P<`!SU,Qv"; stringArray0[2] = "i* ,/O><W?/P<`!SU,Qv"; stringArray0[3] = "i* ,/O><W?/P<`!SU,Qv"; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "i* ,/O><W?/P<`!SU,Qv", "i* ,/O><W?/P<`!SU,Qv", "i* ,/O><W?/P<`!SU,Qv", stringArray0, false, false); methodWriter0.visitFrame(1, 2, stringArray0, (-392), stringArray0); assertEquals(4, stringArray0.length); } /** //Test case number: 127 /*Coverage entropy=1.0594782926538544 */ @Test(timeout = 4000) public void test127() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); // Undeclared exception! try { methodWriter0.visitFrame((byte)0, (byte)90, (Object[]) null, 25165824, (Object[]) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 128 /*Coverage entropy=0.6774944044487072 */ @Test(timeout = 4000) public void test128() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><?/P<`!SU,Qv", "i* O><?/P<`!SU,Qv", "i* O><?/P<`!SU,Qv", stringArray0, false, false); // Undeclared exception! try { methodWriter0.visitFrame(1, 322, stringArray0, 1, stringArray0); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 0 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 129 /*Coverage entropy=1.0465634069578553 */ @Test(timeout = 4000) public void test129() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "zoh:q=W.3)1/3sS", (String[]) null, true, false); // Undeclared exception! try { methodWriter0.visitFrame((byte)0, (byte)0, (Object[]) null, 25165824, (Object[]) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 130 /*Coverage entropy=0.8277381569989198 */ @Test(timeout = 4000) public void test130() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "sJY{`lWJ7'fRJ;\"", "sJY{`lWJ7'fRJ;\"", "o;:*U$;mV;aQe[#9w", (String[]) null, false, false); Object[] objectArray0 = new Object[1]; methodWriter0.visitFrame(966, (-1074), (Object[]) null, 1, objectArray0); methodWriter0.visitFieldInsn((-1074), "<init>", "[42{w[O/\"!1tBpF4m)3", "H&Gs"); methodWriter0.visitFrame((-1146), 1, objectArray0, (-1886060193), objectArray0); assertEquals(1, objectArray0.length); } /** //Test case number: 131 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test131() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "sJY{`lWJ7'fRJ;\"", "sJY{`lWJ7'fRJ;\"", "o;:*U$;mV;aQe[#9w", (String[]) null, false, false); Object[] objectArray0 = new Object[1]; methodWriter0.visitFrame(966, (-1074), (Object[]) null, 1, objectArray0); // Undeclared exception! try { methodWriter0.visitFrame((-1146), 1, objectArray0, (-1886060193), objectArray0); fail("Expecting exception: IllegalStateException"); } catch(IllegalStateException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 132 /*Coverage entropy=1.245016889252439 */ @Test(timeout = 4000) public void test132() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "B>P1sO4", "zoh:q=W.3)1/3sS", "RR)JN|I1='r", (String[]) null, true, false); // Undeclared exception! try { methodWriter0.visitFrame((-1), (-3534), (Object[]) null, (-3559), (Object[]) null); fail("Expecting exception: NegativeArraySizeException"); } catch(NegativeArraySizeException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 133 /*Coverage entropy=0.8981370031878679 */ @Test(timeout = 4000) public void test133() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048559); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2, "sJY{`lWJ7'fRJ;\"", "9o)VXV)^bH*rdo;", "o;:*U$;mV;aQe[#9w", (String[]) null, true, true); methodWriter0.visitFrame(1048559, 1048559, (Object[]) null, 1, (Object[]) null); } /** //Test case number: 134 /*Coverage entropy=0.6615632381579821 */ @Test(timeout = 4000) public void test134() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1328, "j3%eM", "j3%eM", "j3%eM", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitFrame(4, 131072, (Object[]) null, 1328, (Object[]) null); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 135 /*Coverage entropy=0.7732196077242826 */ @Test(timeout = 4000) public void test135() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3333); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-12), "sJY{`lWJ7'fRJ;\"", "}nj@|h~X$S@!Z", "sJY{`lWJ7'fRJ;\"", (String[]) null, false, false); Attribute attribute0 = new Attribute("sJY{`lWJ7'fRJ;\""); methodWriter0.visitAttribute(attribute0); // Undeclared exception! try { methodWriter0.getSize(); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.Attribute", e); } } /** //Test case number: 136 /*Coverage entropy=1.0239287996389363 */ @Test(timeout = 4000) public void test136() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "org.objectweb.asm.jip.ClassWriter", (String[]) null, false, true); // Undeclared exception! try { methodWriter0.visitParameterAnnotation((-1894), "A5", true); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 15 // verifyException("org.objectweb.asm.jip.Type", e); } } /** //Test case number: 137 /*Coverage entropy=0.6365141682948128 */ @Test(timeout = 4000) public void test137() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "EFFFFFFFFGGFFFGGFFFEEFGFGFEEEEEEEEEEEEEEEEEEEEDEDEDDDDDCDCDEEEEEEEEEEEEEEEEEEEEBABABBBBDCFFFGGGEDCDCDCDCDCDCDCDCDCDCEEEEDDDDDDDCDCDCEFEFDDEEFFDEDEEEBDDBBDDDDDDCCCCCCCCEFEDDDCDCDEEEEEEEEEEFEEEEEEDDEEDDEE", (String[]) null, false, false); // Undeclared exception! try { methodWriter0.visitParameterAnnotation(2, "EFFFFFFFFGGFFFGGFFFEEFGFGFEEEEEEEEEEEEEEEEEEEEDEDEDDDDDCDCDEEEEEEEEEEEEEEEEEEEEBABABBBBDCFFFGGGEDCDCDCDCDCDCDCDCDCDCEEEEDDDDDDDCDCDCEFEFDDEEFFDEDEEEBDDBBDDDDDDCCCCCCCCEFEDDDCDCDEEEEEEEEEEFEEEEEEDDEEDDEE", false); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 15 // verifyException("org.objectweb.asm.jip.Type", e); } } /** //Test case number: 138 /*Coverage entropy=0.8981370031878679 */ @Test(timeout = 4000) public void test138() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048566); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", (String[]) null, true, true); AnnotationVisitor annotationVisitor0 = methodWriter0.visitAnnotation("9o)VXVr3jH*rdo;", true); assertNotNull(annotationVisitor0); } /** //Test case number: 139 /*Coverage entropy=0.7909873504355756 */ @Test(timeout = 4000) public void test139() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "9o)VXVr3jH*rdo;", "zoh:q=W.3)1/3sS", "org.objectweb.asm.jip.MethodWriter", (String[]) null, false, false); methodWriter0.visitAnnotation("sJY{`lWJ7'fRJ;\"", false); int int0 = methodWriter0.getSize(); assertEquals(28, int0); } /** //Test case number: 140 /*Coverage entropy=1.0239287996389363 */ @Test(timeout = 4000) public void test140() throws Throwable { ClassWriter classWriter0 = new ClassWriter((-98)); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 2217, "2`-_\"2~K4=0k,?*=", "9o)VXVr3jH*rdo;", "7}<j$.;1?", (String[]) null, false, true); Label label0 = new Label(); // Undeclared exception! try { methodWriter0.visitJumpInsn(2217, label0); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.Frame", e); } } /** //Test case number: 141 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test141() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048559); MethodWriter methodWriter0 = null; try { methodWriter0 = new MethodWriter(classWriter0, 2, "<init>", "<init>", "AAAAAAAAAAAAAAAABCKLLDDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAADDDDDEEEEEEEEEEEEEEEEEEEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAIIIIIIIIIIIIIIIIDNOAAAAAAGGGGGGGHHFBFAAFFAAQPIIJJIIIIIIIIIIIIIIIIII", (String[]) null, true, true); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 142 /*Coverage entropy=0.8981370031878679 */ @Test(timeout = 4000) public void test142() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048575); MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "org.objectweb.asm.jip.MethodWriter", "zoh:q=W.3)1/3sS", "Lo;Y", (String[]) null, true, false); AnnotationVisitor annotationVisitor0 = methodWriter0.visitParameterAnnotation(179, "Ljava/lang/Synthetic;", true); assertNotNull(annotationVisitor0); } /** //Test case number: 143 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test143() throws Throwable { ClassWriter classWriter0 = new ClassWriter(50331648); String[] stringArray0 = new String[1]; MethodWriter methodWriter0 = null; try { methodWriter0 = new MethodWriter(classWriter0, 2, "int", "int", "w^_P%?6-.h1+TZN", stringArray0, false, true); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // } } /** //Test case number: 144 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test144() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", stringArray0, false, false); MethodWriter methodWriter1 = null; try { methodWriter1 = new MethodWriter(classWriter0, 3230, "7}<j$.;1?", "i* O><W?/P<`!FSUQv", "7}<j$.;1?", stringArray0, false, true); fail("Expecting exception: StringIndexOutOfBoundsException"); } catch(StringIndexOutOfBoundsException e) { } } /** //Test case number: 145 /*Coverage entropy=0.410116318288409 */ @Test(timeout = 4000) public void test145() throws Throwable { ClassWriter classWriter0 = new ClassWriter(3333); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-12), "sJY{`lWJ7'fRJ;\"", "}nj@|h~X$S@!Z", "sJY{`lWJ7'fRJ;\"", (String[]) null, false, false); methodWriter0.visitEnd(); } /** //Test case number: 146 /*Coverage entropy=0.8080599286573673 */ @Test(timeout = 4000) public void test146() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", "i* O><W?/P<`!FSUQv", stringArray0, false, false); methodWriter0.visitAnnotationDefault(); int int0 = methodWriter0.getSize(); assertEquals(22, int0); } /** //Test case number: 147 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test147() throws Throwable { // Undeclared exception! try { MethodWriter.readInt((byte[]) null, 103); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 148 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test148() throws Throwable { // Undeclared exception! try { MethodWriter.readShort((byte[]) null, 60); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 149 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test149() throws Throwable { byte[] byteArray0 = new byte[4]; // Undeclared exception! try { MethodWriter.writeShort(byteArray0, (byte)22, (byte) (-20)); fail("Expecting exception: ArrayIndexOutOfBoundsException"); } catch(ArrayIndexOutOfBoundsException e) { // // 22 // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 150 /*Coverage entropy=0.37677016125643675 */ @Test(timeout = 4000) public void test150() throws Throwable { ClassWriter classWriter0 = new ClassWriter(711); String[] stringArray0 = new String[0]; MethodWriter methodWriter0 = new MethodWriter(classWriter0, 1, "i* O><W?/P<a`!FSUQv", "X", "i* O><W?/P<a`!FSUQv", stringArray0, false, false); methodWriter0.visitCode(); } /** //Test case number: 151 /*Coverage entropy=-0.0 */ @Test(timeout = 4000) public void test151() throws Throwable { // Undeclared exception! try { MethodWriter.readUnsignedShort((byte[]) null, 1048575); fail("Expecting exception: NullPointerException"); } catch(NullPointerException e) { // // no message in exception (getMessage() returned null) // verifyException("org.objectweb.asm.jip.MethodWriter", e); } } /** //Test case number: 152 /*Coverage entropy=1.6323441007173467 */ @Test(timeout = 4000) public void test152() throws Throwable { ClassWriter classWriter0 = new ClassWriter(1048566); MethodWriter methodWriter0 = new MethodWriter(classWriter0, (-890), "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", "9o)VXVr3jH*rdo;", (String[]) null, true, true); Label label0 = new Label(); methodWriter0.visitJumpInsn(166, label0); int[] intArray0 = new int[4]; Label[] labelArray0 = new Label[0]; methodWriter0.visitLookupSwitchInsn(label0, intArray0, labelArray0); assertEquals(4, intArray0.length); } }
35.991443
344
0.63869
8bdaf86e9df0f585d587ade6ee41d2dc0f75dd27
89
package com.a6raywa1cher.db_rgr.lib; public record Pair<L, R>( L left, R right ) { }
9.888889
36
0.674157
3ca67477a051d06edc200c73154f62b8d0f0213c
3,423
package ru.job4j.find; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; /** * Path filters. * Хранилище различных фильтров для поиска файла. * * @author Alexander Yakovlev (sanyakovlev@yandex.ru) * @since 22.02.2019 */ public final class PathFilters { private final Map<String, Function<String, Predicate<Path>>> pathFilters; /** * Дополнительный конструктор содержащий по умолчанию несколько фильтров: * Ключ: "m" соответствует фильтру, * который использует "glob" паттерн для поиска файла. * Ключ: "f" соответствует фильтру, * который проверяет на полное совпадение имя файла. * Ключ: "r" соответствует фильтру, * который использует регулярное выражение для поиска. */ public PathFilters() { this(Map.ofEntries( Map.entry( "m", (Function<String, Predicate<Path>>) searchString -> new Predicate<>() { private final PathMatcher matcher = FileSystems .getDefault() .getPathMatcher("glob:" + searchString); @Override public boolean test(final Path path) { System.out.println(path); return this.matcher.matches(path); } } ), Map.entry( "f", (Function<String, Predicate<Path>>) searchString -> (Predicate<Path>) path -> path.endsWith(searchString) ), Map.entry( "r", (Function<String, Predicate<Path>>) searchString -> new Predicate<>() { private final PathMatcher matcher = FileSystems .getDefault() .getPathMatcher("regex:" + searchString); @Override public boolean test(final Path path) { return this.matcher.matches(path); } } ) )); } public PathFilters( final Map<String, Function<String, Predicate<Path>>> pathFilters) { this.pathFilters = pathFilters; } /** * Возвращает фильтр для поиска файла. * @param key ключ для выбора определенного фильтра. * @param searchString строка, необходимая фильтру для поиска * определенного файла. * @return фильтр для поиска файла. */ public final Predicate<Path> pathFilter(final String key, final String searchString) { final Optional<Function<String, Predicate<Path>>> optFilterBuilder = Optional.ofNullable(this.pathFilters.get(key)); if (optFilterBuilder.isEmpty()) { throw new IllegalArgumentException(String.format( "Filter for key: %s missing.", key )); } return optFilterBuilder.get().apply(searchString); } }
37.615385
95
0.517382
2a844e85bed1d4a7fa64e326ab0c38ee9c1a1059
1,952
package com.example.base.controller; import java.util.List; import java.util.Optional; import org.springframework.graphql.data.method.annotation.Argument; import org.springframework.graphql.data.method.annotation.MutationMapping; import org.springframework.graphql.data.method.annotation.QueryMapping; import org.springframework.graphql.data.method.annotation.SchemaMapping; import org.springframework.stereotype.Controller; import com.example.base.entity.Article; import com.example.base.entity.Category; import com.example.base.repository.ArticleRepository; import com.example.base.repository.CategoryRepository; @Controller public class BlogController { private final ArticleRepository articleRepository; private final CategoryRepository categoryRepository; public BlogController(ArticleRepository articleRepository, CategoryRepository categoryRepository) { this.articleRepository = articleRepository; this.categoryRepository = categoryRepository; } @QueryMapping public Optional<Article> article(@Argument Integer id) { return articleRepository.findById(id); } @QueryMapping public List<Article> articles() { return articleRepository.findAll(); } @QueryMapping public List<Category> categories() { return categoryRepository.findAll(); } @SchemaMapping public Category category(Article article) { return article.getCategory(); } @MutationMapping public Category createCategory(@Argument String name) { Category category = new Category(); category.setName(name); return categoryRepository.save(category); } @MutationMapping public Optional<Article> createArticle(@Argument String title, @Argument String content, @Argument Integer categoryId) { return categoryRepository.findById(categoryId).map(category -> { Article article = new Article(); article.setTitle(title); article.setContent(content); article.setCategory(category); return articleRepository.save(article); }); } }
29.134328
100
0.801742
ee98c0b435e7460cbdc03db95a23f6cc047a2761
1,434
/** * */ package org.minnal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>Bootstrap is the entry point to minnal and is the main class. The main method loads the container, initializes and starts the container. * It also registers a shutdown hook for gracefully shutting down the container. To stop the minnal server, use SIGTERM the running process</p> * * @author ganeshs * */ public class Bootstrap { private static final Logger logger = LoggerFactory.getLogger(Bootstrap.class); public static void main(String[] args) { try { final Class<?> containerClass = Thread.currentThread().getContextClassLoader().loadClass("org.minnal.core.Container"); final Object container = args != null && args.length > 0 ? containerClass.getConstructor(String.class).newInstance(args[0]) : containerClass.newInstance(); containerClass.getMethod("init").invoke(container); containerClass.getMethod("start").invoke(container); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { logger.info("Shutdown hook triggered. Stopping the container"); containerClass.getMethod("stop").invoke(container); } catch (Exception e) { logger.error("Failed while stopping the container", e); } } }); } catch (Exception e) { logger.error("Failed while starting the container", e); System.exit(1); } } }
31.173913
144
0.700837
12ad20092f15f0dab1dc1eca455a3cdad56e5fae
1,618
// // Copyright (c) 2010, Brian Frank and Andy Frank // Licensed under the Academic Free License version 3.0 // // History: // 12 Feb 10 Brian Frank Creation // package fan.concurrent; import java.util.concurrent.atomic.AtomicLong; public final class AtomicIntPeer { public static AtomicIntPeer make(AtomicInt self) { return new AtomicIntPeer(); } public final long val(AtomicInt self) { return val.get(); } public final void val(AtomicInt self, long v) { val.set(v); } public final long getAndSet(AtomicInt self, long v) { return val.getAndSet(v); } public final boolean compareAndSet(AtomicInt self, long expect, long update) { return val.compareAndSet(expect, update); } public final long getAndIncrement(AtomicInt self) { return val.getAndIncrement(); } public final long getAndDecrement(AtomicInt self) { return val.getAndDecrement(); } public final long getAndAdd(AtomicInt self, long delta) { return val.getAndAdd(delta); } public final long incrementAndGet(AtomicInt self) { return val.incrementAndGet(); } public final long decrementAndGet(AtomicInt self) { return val.decrementAndGet(); } public final long addAndGet(AtomicInt self, long delta) { return val.addAndGet(delta); } public final void increment(AtomicInt self) { val.incrementAndGet(); } public final void decrement(AtomicInt self) { val.decrementAndGet(); } public final void add(AtomicInt self, long delta) { val.addAndGet(delta); } private final AtomicLong val = new AtomicLong(); }
18.813953
78
0.692831
e446435244e157967f66b96e07c7a12a0adf631a
1,155
package paulevs.bnb.item; import net.minecraft.block.BlockBase; import net.minecraft.entity.EntityBase; import net.minecraft.entity.Living; import net.minecraft.item.ItemBase; import net.minecraft.item.ItemInstance; import paulevs.bnb.item.material.NetherToolMaterial; public class NetherSwordItem extends NetherToolItem { public NetherSwordItem(String name, int id, NetherToolMaterial material) { super(name, id, material); } @Override public boolean isEffectiveOn(BlockBase tile) { return ItemBase.ironSword.isEffectiveOn(tile); } @Override public boolean postHit(ItemInstance arg, Living damageSource, Living damageTarget) { arg.applyDamage(1, damageTarget); return true; } @Override public boolean postMine(ItemInstance item, int i, int j, int k, int i1, Living damageTarget) { item.applyDamage(2, damageTarget); return true; } @Override public float getStrengthOnBlock(ItemInstance item, BlockBase tile) { return ItemBase.ironSword.getStrengthOnBlock(item, tile); } @Override public int method_447(EntityBase entity) { return material.getAttackDamage() * 2 + 4; } }
27.5
96
0.748918
cd6b87772d7c0f955f1abf3c99461dfb76633eff
451
package com.bugsnag.mazerunner.scenarios; import com.bugsnag.Bugsnag; /** * Sends a handled exception to Bugsnag, which does not include session data. */ public class ProjectPackageScenario extends Scenario { public ProjectPackageScenario(Bugsnag bugsnag) { super(bugsnag); } @Override public void run() { bugsnag.setProjectPackages("com.bugsnag.mazerunner"); bugsnag.notify(generateException()); } }
22.55
77
0.7051
baba650b5786d0e089af66d4172b9907079696f1
2,925
package net.minecraft.world.level.levelgen.synth; import it.unimi.dsi.fastutil.ints.IntRBTreeSet; import it.unimi.dsi.fastutil.ints.IntSortedSet; import java.util.List; import net.minecraft.world.level.levelgen.LegacyRandomSource; import net.minecraft.world.level.levelgen.RandomSource; import net.minecraft.world.level.levelgen.WorldgenRandom; public class PerlinSimplexNoise { private final SimplexNoise[] noiseLevels; private final double highestFreqValueFactor; private final double highestFreqInputFactor; public PerlinSimplexNoise(RandomSource p_164393_, List<Integer> p_164394_) { this(p_164393_, new IntRBTreeSet(p_164394_)); } private PerlinSimplexNoise(RandomSource p_164390_, IntSortedSet p_164391_) { if (p_164391_.isEmpty()) { throw new IllegalArgumentException("Need some octaves!"); } else { int i = -p_164391_.firstInt(); int j = p_164391_.lastInt(); int k = i + j + 1; if (k < 1) { throw new IllegalArgumentException("Total number of octaves needs to be >= 1"); } else { SimplexNoise simplexnoise = new SimplexNoise(p_164390_); int l = j; this.noiseLevels = new SimplexNoise[k]; if (j >= 0 && j < k && p_164391_.contains(0)) { this.noiseLevels[j] = simplexnoise; } for(int i1 = j + 1; i1 < k; ++i1) { if (i1 >= 0 && p_164391_.contains(l - i1)) { this.noiseLevels[i1] = new SimplexNoise(p_164390_); } else { p_164390_.consumeCount(262); } } if (j > 0) { long k1 = (long)(simplexnoise.getValue(simplexnoise.xo, simplexnoise.yo, simplexnoise.zo) * (double)9.223372E18F); RandomSource randomsource = new WorldgenRandom(new LegacyRandomSource(k1)); for(int j1 = l - 1; j1 >= 0; --j1) { if (j1 < k && p_164391_.contains(l - j1)) { this.noiseLevels[j1] = new SimplexNoise(randomsource); } else { randomsource.consumeCount(262); } } } this.highestFreqInputFactor = Math.pow(2.0D, (double)j); this.highestFreqValueFactor = 1.0D / (Math.pow(2.0D, (double)k) - 1.0D); } } } public double getValue(double p_75450_, double p_75451_, boolean p_75452_) { double d0 = 0.0D; double d1 = this.highestFreqInputFactor; double d2 = this.highestFreqValueFactor; for(SimplexNoise simplexnoise : this.noiseLevels) { if (simplexnoise != null) { d0 += simplexnoise.getValue(p_75450_ * d1 + (p_75452_ ? simplexnoise.xo : 0.0D), p_75451_ * d1 + (p_75452_ ? simplexnoise.yo : 0.0D)) * d2; } d1 /= 2.0D; d2 *= 2.0D; } return d0; } }
37.025316
151
0.586325
f47bf6247e74c4144cdff46cc6ce0a075fe0be24
594
public class Peninsular { static String critical = "L1HpBv5EXwvHtQM"; private java.lang.String isletIdentify; private int numeralFarms; public Peninsular(String viequesDistinguish, int totalGranger) { this.isletIdentify = viequesDistinguish; this.numeralFarms = totalGranger; } public synchronized void early() { String trammel = "y6KEy"; { int i = 0; while (i < numeralFarms) { { { new java.lang.Thread(new Plantation(isletIdentify + "_Farmer" + (i + 1))).start(); } } i++; } } } }
22
94
0.599327