text
stringlengths
7
1.01M
package com.example.fw; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import com.example.tests.ContactData; import com.example.utils.SortedListOf; public class PhoneHelper extends WebDriverHelperBase { protected PhoneHelper(ApplicationManager manager) { super(manager); } private SortedListOf<ContactData> phones; private SortedListOf<ContactData> cachedContacts; public SortedListOf<ContactData> getPhones() { if (phones == null) { rebuildPhonesCache(); } return phones; } private void rebuildPhonesCache() { manager.navigateTo().printPhones(); phones = new SortedListOf<ContactData>(); List<WebElement> cells = driver.findElements(By.tagName("td")); for (WebElement cell : cells) { String data = cell.getText(); ContactData contact = new ContactData() .withName(findNameAndLastName(data, "name")) .withLastname(findNameAndLastName(data, "lastName")) .withHome(findPhonesOfContact(data, "home")) .withMobile(findPhonesOfContact(data, "mobile")) .withWork(findPhonesOfContact(data, "work")) .withBday(findBday(data)).withBmonth(findBmonth(data)) .withByear(findByear(data)) .withPhone2(findPhonesOfContact(data, "phone2")); phones.add(contact); } } public SortedListOf<ContactData> getContacts() { if (cachedContacts == null) { rebuildContactsCache(); } return cachedContacts; } private void rebuildContactsCache() { cachedContacts = new SortedListOf<ContactData>(); manager.navigateTo().mainPage(); List<WebElement> allRows = driver.findElements(By .xpath("//tr[@name='entry']")); for (WebElement row : allRows) { row.findElement(By.xpath("td[7]/a")).click(); System.out.println(driver.findElement(By.tagName("h1")).getText()); if (driver.findElement(By.tagName("h1")).getText().equalsIgnoreCase("Edit / add address book entry")){ System.out.println("conditions are true"); ContactData contact = new ContactData(); contact.withName(driver.findElement(By.name("firstname")).getAttribute("value")) .withLastname(driver.findElement(By.name("lastname")).getAttribute("value")) .withHome(driver.findElement(By.name("home")).getAttribute("value")) .withMobile(driver.findElement(By.name("mobile")).getAttribute("value")) .withWork(driver.findElement(By.name("work")).getAttribute("value")) .withBday(driver.findElement(By.name("bday")).getAttribute("value")) .withBmonth(driver.findElement(By.name("bmonth")).getAttribute("value")) .withByear(driver.findElement(By.name("byear")).getAttribute("value")) .withPhone2(driver.findElement(By.name("phone2")).getAttribute("value")); cachedContacts.add(contact); } } } private ContactData getContact(){ ContactData contact = new ContactData(); return contact; } //-------------------------------------------------------------------------------------- private String find(String data, String regex) { String result = ""; Pattern pattern; Matcher matcher; pattern = Pattern.compile(regex); matcher = pattern.matcher(data); if (matcher.find()) { return result = matcher.group(); } return result; } private String findNameAndLastName(String data, String tag) { String str = find(data, "[ a-zA-z0-9]+:|:"); switch (tag) { case "name": str = find(str, "\\w+ "); break; case "lastName": str = find(str, "\\w+:"); break; default: break; } if (str != "") { str = str.substring(0, str.length() - 1); } return str; } private String findPhonesOfContact(String data, String tag) { String regex; switch (tag) { case "home": regex = "H: \\d+"; break; case "mobile": regex = "M: \\d+"; break; case "work": regex = "W: \\d+"; break; case "phone2": regex = "P: \\d+"; break; default: regex = ""; break; } String str = find(data, regex); if (str != "") { str = str.substring(3); } return str; } private String findBday(String data) { String str = find(data, "\\d+\\."); if (str != "") { str = str.substring(0, (str.length() - 1)); } return str; } private String findBmonth(String data) { String str = find(data, "Birthday:[ .a-zA-z0-9]+"); str = find(str, " [a-zA-Z]+"); if (str != "") { str = str.substring(1); } return str; } private String findByear(String data) { String str = find(data, "Birthday:[ .a-zA-z0-9]+"); str = find(str, "\\d+$"); return str; } public boolean compareContacts(List<ContactData> contactsList, List<ContactData> phonesList) { if (contactsList.size() == phonesList.size()) { for (int i = 0; i < contactsList.size(); i++) { if (contactsList.get(i).equals(phonesList.get(i))) { // System.out.println(i + "are equals"); } else return false; } // System.out.println(contactsList.size()); // System.out.println(phonesList.size()); } else return false; return true; } }
// Targeted by JavaCPP version 1.5.7: DO NOT EDIT THIS FILE package org.bytedeco.tensorflow; import org.bytedeco.tensorflow.Allocator; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.tensorflow.global.tensorflow.*; /** An array of Tensors of given size. * * Write data via Write and read via Read or Pack. * * Arguments: * * scope: A Scope object * * size: The size of the array. * * dtype: The type of the elements on the tensor_array. * * Optional attributes (see {@code Attrs}): * * element_shape: The expected shape of an element, if known. Used to * validate the shapes of TensorArray elements. If this shape is not * fully specified, gathering zero-size TensorArrays is an error. * * dynamic_size: A boolean that determines whether writes to the TensorArray * are allowed to grow the size. By default, this is not allowed. * * clear_after_read: If true (default), Tensors in the TensorArray are cleared * after being read. This disables multiple read semantics but allows early * release of memory. * * identical_element_shapes: If true (default is false), then all * elements in the TensorArray will be expected to have have identical shapes. * This allows certain behaviors, like dynamically checking for * consistent shapes on write, and being able to fill in properly * shaped zero tensors on stack -- even if the element_shape attribute * is not fully defined. * * tensor_array_name: Overrides the name used for the temporary tensor_array * resource. Default value is the name of the 'TensorArray' op (which * is guaranteed unique). * * Returns: * * {@code Output} handle: The handle to the TensorArray. * * {@code Output} flow: A scalar used to control gradient flow. */ @Namespace("tensorflow::ops") @NoOffset @Properties(inherit = org.bytedeco.tensorflow.presets.tensorflow.class) public class TensorArray extends Pointer { static { Loader.load(); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public TensorArray(Pointer p) { super(p); } /** Optional attribute setters for TensorArray */ public static class Attrs extends Pointer { static { Loader.load(); } /** Default native constructor. */ public Attrs() { super((Pointer)null); allocate(); } /** Native array allocator. Access with {@link Pointer#position(long)}. */ public Attrs(long size) { super((Pointer)null); allocateArray(size); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public Attrs(Pointer p) { super(p); } private native void allocate(); private native void allocateArray(long size); @Override public Attrs position(long position) { return (Attrs)super.position(position); } @Override public Attrs getPointer(long i) { return new Attrs((Pointer)this).offsetAddress(i); } /** The expected shape of an element, if known. Used to * validate the shapes of TensorArray elements. If this shape is not * fully specified, gathering zero-size TensorArrays is an error. * * Defaults to <unknown> */ /// public native @ByVal Attrs ElementShape(@ByVal PartialTensorShape x); /** A boolean that determines whether writes to the TensorArray * are allowed to grow the size. By default, this is not allowed. * * Defaults to false */ /// public native @ByVal Attrs DynamicSize(@Cast("bool") boolean x); /** If true (default), Tensors in the TensorArray are cleared * after being read. This disables multiple read semantics but allows early * release of memory. * * Defaults to true */ /// public native @ByVal Attrs ClearAfterRead(@Cast("bool") boolean x); /** If true (default is false), then all * elements in the TensorArray will be expected to have have identical shapes. * This allows certain behaviors, like dynamically checking for * consistent shapes on write, and being able to fill in properly * shaped zero tensors on stack -- even if the element_shape attribute * is not fully defined. * * Defaults to false */ /// public native @ByVal Attrs IdenticalElementShapes(@Cast("bool") boolean x); /** Overrides the name used for the temporary tensor_array * resource. Default value is the name of the 'TensorArray' op (which * is guaranteed unique). * * Defaults to "" */ public native @ByVal Attrs TensorArrayName(@StringPiece BytePointer x); public native @ByVal Attrs TensorArrayName(@StringPiece String x); public native @ByRef PartialTensorShape element_shape_(); public native Attrs element_shape_(PartialTensorShape setter); public native @Cast("bool") boolean dynamic_size_(); public native Attrs dynamic_size_(boolean setter); public native @Cast("bool") boolean clear_after_read_(); public native Attrs clear_after_read_(boolean setter); public native @Cast("bool") boolean identical_element_shapes_(); public native Attrs identical_element_shapes_(boolean setter); public native @StringPiece BytePointer tensor_array_name_(); public native Attrs tensor_array_name_(BytePointer setter); } public TensorArray(@Const @ByRef Scope scope, @ByVal Input size, @Cast("tensorflow::DataType") int dtype) { super((Pointer)null); allocate(scope, size, dtype); } private native void allocate(@Const @ByRef Scope scope, @ByVal Input size, @Cast("tensorflow::DataType") int dtype); public TensorArray(@Const @ByRef Scope scope, @ByVal Input size, @Cast("tensorflow::DataType") int dtype, @Const @ByRef Attrs attrs) { super((Pointer)null); allocate(scope, size, dtype, attrs); } private native void allocate(@Const @ByRef Scope scope, @ByVal Input size, @Cast("tensorflow::DataType") int dtype, @Const @ByRef Attrs attrs); public static native @ByVal Attrs ElementShape(@ByVal PartialTensorShape x); public static native @ByVal Attrs DynamicSize(@Cast("bool") boolean x); public static native @ByVal Attrs ClearAfterRead(@Cast("bool") boolean x); public static native @ByVal Attrs IdenticalElementShapes(@Cast("bool") boolean x); public static native @ByVal Attrs TensorArrayName(@StringPiece BytePointer x); public static native @ByVal Attrs TensorArrayName(@StringPiece String x); public native @ByRef Operation operation(); public native TensorArray operation(Operation setter); public native @ByRef Output handle(); public native TensorArray handle(Output setter); public native @ByRef Output flow(); public native TensorArray flow(Output setter); }
package org.kodejava.example.jpa; import org.kodejava.example.jpa.entity.Artist; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class GetEntityIdDemo { public static final String PERSISTENCE_UNIT_NAME = "music"; public static void main(String[] args) { EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME); EntityManager manager = factory.createEntityManager(); // Get object identifier of an exists entity. Artist artist = manager.find(Artist.class, 1L); if (artist != null) { Object identifier = factory.getPersistenceUnitUtil().getIdentifier(artist); System.out.println("Identifier = " + identifier); } // Get object identifier of a newly inserted entity. Artist newArtist = new Artist(); newArtist.setName("Bon Jovi"); manager.getTransaction().begin(); manager.persist(newArtist); manager.getTransaction().commit(); Object identifier = factory.getPersistenceUnitUtil().getIdentifier(newArtist); System.out.println("Identifier = " + identifier); } }
/* * Copyright (C) 2015-2017 Level Software 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 io.levelsoftware.carculator.ui.quotelist; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import io.levelsoftware.carculator.R; import io.levelsoftware.carculator.model.quote.Quote; import io.levelsoftware.carculator.sync.vehicle.VehicleIntentService; import io.levelsoftware.carculator.ui.quoteform.QuoteFormActivity; import io.levelsoftware.carculator.ui.vehiclelist.VehicleListActivity; import timber.log.Timber; public class QuoteListActivity extends AppCompatActivity implements QuoteListFragment.QuoteListOnScrollListener, ViewPager.OnPageChangeListener { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.view_pager) ViewPager viewPager; @BindView(R.id.tab_layout) TabLayout tabLayout; @BindView(R.id.fab) FloatingActionButton fab; private BroadcastReceiver clickReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_quote_list); ButterKnife.bind(this); setSupportActionBar(toolbar); if(getSupportActionBar() != null) { getSupportActionBar().setDisplayShowTitleEnabled(false); } setupSync(); setupTabs(); setupFab(); } @Override protected void onStart() { super.onStart(); bindClickReceiver(); } @Override protected void onStop() { super.onStop(); unBindClickReceiver(); } private void setupSync() { Timber.d("Starting immediate synchronization of vehicle data..."); VehicleIntentService.start(this); // Timber.d("Scheduling future syncronization of vehicle data..."); // FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this)); // // Job vehicleSyncJob = dispatcher.newJobBuilder() // .setService(VehicleJobService.class) // .setTag(getString(R.string.job_sync_vehicle)) // .setRecurring(true) // .setLifetime(Lifetime.FOREVER) // .setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL) // .setReplaceCurrent(true) // .setTrigger(Trigger.executionWindow(10, 20)) // .setConstraints(Constraint.ON_ANY_NETWORK) // .build(); // // dispatcher.mustSchedule(vehicleSyncJob); } private void setupTabs() { // Restore fragments using tags assigned by the viewpager QuoteListFragment loanFragment = (QuoteListFragment) getSupportFragmentManager() .findFragmentByTag("android:switcher:" + R.id.view_pager + ":0"); QuoteListFragment leaseFragment = (QuoteListFragment) getSupportFragmentManager() .findFragmentByTag("android:switcher:" + R.id.view_pager + ":1"); if(loanFragment == null) { Bundle loanArgs = new Bundle(); loanArgs.putString(getString(R.string.intent_key_quote_type), getString(R.string.quote_type_loan)); loanFragment = QuoteListFragment.newInstance(loanArgs); } if(leaseFragment == null) { Bundle leaseArgs = new Bundle(); leaseArgs.putString(getString(R.string.intent_key_quote_type), getString(R.string.quote_type_lease)); leaseFragment = QuoteListFragment.newInstance(leaseArgs); } ArrayList<Fragment> fragments = new ArrayList<>(); fragments.add(loanFragment); fragments.add(leaseFragment); QuoteListPagerAdapter pagerAdapter = new QuoteListPagerAdapter(getSupportFragmentManager(), this, fragments); viewPager.setAdapter(pagerAdapter); viewPager.addOnPageChangeListener(this); tabLayout.setupWithViewPager(viewPager); } private void setupFab() { fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(getQuoteTypeForTabPosition().equals(getString(R.string.quote_type_loan))) { Intent intent = new Intent(QuoteListActivity.this, VehicleListActivity.class); intent.putExtra(getString(R.string.intent_key_quote_type), getQuoteTypeForTabPosition()); startActivity(intent); } else { Toast.makeText(QuoteListActivity.this, R.string.leasing_coming_soon, Toast.LENGTH_LONG).show(); } } }); } private void bindClickReceiver() { clickReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Quote quote = intent.getParcelableExtra(getString(R.string.intent_key_quote)); Intent quoteIntent = new Intent(QuoteListActivity.this, QuoteFormActivity.class); quoteIntent.putExtra(getString(R.string.intent_key_quote), quote); startActivity(quoteIntent); } }; LocalBroadcastManager.getInstance(this).registerReceiver(clickReceiver, new IntentFilter(getString(R.string.broadcast_click_quote))); } private void unBindClickReceiver() { LocalBroadcastManager.getInstance(this).unregisterReceiver(clickReceiver); } private String getQuoteTypeForTabPosition() { int tabIndex = viewPager.getCurrentItem(); switch (tabIndex) { case 0: return getString(R.string.quote_type_loan); case 1: return getString(R.string.quote_type_lease); } return null; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_quote_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void quoteListScrolled(int dx, int dy) { if (dy > 0) { if (fab.isShown()) { fab.hide(); } } if (dy < 0) { if (!fab.isShown()) { fab.show(); } } } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {} @Override public void onPageSelected(int position) { // Show the fab if it is hidden when we switch tabs if(!fab.isShown()) { fab.show(); } } @Override public void onPageScrollStateChanged(int state) {} }
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2019 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.pnc.indyrepositorymanager.fixture; import org.commonjava.indy.core.expire.ScheduleManager; import org.commonjava.indy.inject.TestData; import org.commonjava.indy.model.core.io.IndyObjectMapper; import org.commonjava.maven.galley.auth.AttributePasswordManager; import org.commonjava.maven.galley.spi.auth.PasswordManager; import org.commonjava.maven.galley.transport.htcli.Http; import org.commonjava.maven.galley.transport.htcli.HttpImpl; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Default; import javax.enterprise.inject.Produces; @ApplicationScoped public class Producer { private IndyObjectMapper objectMapper; private ScheduleManager scheduleManager; private Http http; public Producer() { objectMapper = new IndyObjectMapper(true); PasswordManager passman = new AttributePasswordManager(); http = new HttpImpl(passman); scheduleManager = new ScheduleManager(); } // @Produces // @Default public ScheduleManager getScheduleManager() { return scheduleManager; } // @Produces // @Default public Http getHttp() { return http; } @Produces @Default @TestData public IndyObjectMapper getObjectMapper() { return objectMapper; } }
package com.atguigu.gulimall.ware.service.impl; import com.alibaba.fastjson.TypeReference; import com.atguigu.common.utils.R; import com.atguigu.gulimall.ware.feign.MemberFeignService; import com.atguigu.gulimall.ware.vo.FareVo; import com.atguigu.gulimall.ware.vo.MemberAddressVo; import org.aspectj.weaver.ast.Or; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.Map; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.atguigu.common.utils.PageUtils; import com.atguigu.common.utils.Query; import com.atguigu.gulimall.ware.dao.WareInfoDao; import com.atguigu.gulimall.ware.entity.WareInfoEntity; import com.atguigu.gulimall.ware.service.WareInfoService; import org.springframework.util.StringUtils; @Service("wareInfoService") public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService { @Autowired MemberFeignService memberFeignService; @Override public PageUtils queryPage(Map<String, Object> params) { QueryWrapper<WareInfoEntity> wareInfoEntityQueryWrapper = new QueryWrapper<>(); String key = (String) params.get("key"); if(!StringUtils.isEmpty(key)){ wareInfoEntityQueryWrapper.eq("id",key).or().like("name",key).or().like("address",key).or().like("areacode",key); } IPage<WareInfoEntity> page = this.page( new Query<WareInfoEntity>().getPage(params), wareInfoEntityQueryWrapper ); return new PageUtils(page); } @Override public FareVo getFare(Long addrId) { FareVo fareVo = new FareVo(); R r = memberFeignService.addrInfo(addrId); MemberAddressVo data = r.getData("memberReceiveAddress",new TypeReference<MemberAddressVo>() { }); if (data!=null){ String phone = data.getPhone(); String s = phone.substring(phone.length() - 1, phone.length()); BigDecimal bigDecimal = new BigDecimal(s); fareVo.setAddress(data); fareVo.setFare(bigDecimal); return fareVo; } return null; } }
// // MessagePack for Java // // Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // 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.msgpack.unpacker; import java.io.IOException; import java.io.EOFException; import java.io.InputStream; import java.math.BigInteger; import org.msgpack.io.Input; import org.msgpack.io.StreamInput; import org.msgpack.io.BufferReferer; import org.msgpack.MessagePack; import org.msgpack.MessageTypeException; import org.msgpack.packer.Unconverter; import org.msgpack.type.ValueType; public class MessagePackUnpacker extends AbstractUnpacker { private static final byte REQUIRE_TO_READ_HEAD = (byte) 0xc6; protected final Input in; private final UnpackerStack stack = new UnpackerStack(); private byte headByte = REQUIRE_TO_READ_HEAD; private byte[] raw; private int rawFilled; private final IntAccept intAccept = new IntAccept(); private final LongAccept longAccept = new LongAccept(); private final BigIntegerAccept bigIntegerAccept = new BigIntegerAccept(); private final DoubleAccept doubleAccept = new DoubleAccept(); private final ByteArrayAccept byteArrayAccept = new ByteArrayAccept(); private final StringAccept stringAccept = new StringAccept(); private final ArrayAccept arrayAccept = new ArrayAccept(); private final MapAccept mapAccept = new MapAccept(); private final ValueAccept valueAccept = new ValueAccept(); private final SkipAccept skipAccept = new SkipAccept(); public MessagePackUnpacker(MessagePack msgpack, InputStream stream) { this(msgpack, new StreamInput(stream)); } protected MessagePackUnpacker(MessagePack msgpack, Input in) { super(msgpack); this.in = in; } private byte getHeadByte() throws IOException { byte b = headByte; if (b == REQUIRE_TO_READ_HEAD) { b = headByte = in.readByte(); } return b; } final void readOne(Accept a) throws IOException { stack.checkCount(); if (readOneWithoutStack(a)) { stack.reduceCount(); } } final boolean readOneWithoutStack(Accept a) throws IOException { if (raw != null) { readRawBodyCont(); a.acceptRaw(raw); raw = null; headByte = REQUIRE_TO_READ_HEAD; return true; } final int b = (int) getHeadByte(); if ((b & 0x80) == 0) { // Positive Fixnum // System.out.println("positive fixnum "+b); a.acceptInteger(b); headByte = REQUIRE_TO_READ_HEAD; return true; } if ((b & 0xe0) == 0xe0) { // Negative Fixnum // System.out.println("negative fixnum "+b); a.acceptInteger(b); headByte = REQUIRE_TO_READ_HEAD; return true; } if ((b & 0xe0) == 0xa0) { // FixRaw int count = b & 0x1f; if (count == 0) { a.acceptEmptyRaw(); headByte = REQUIRE_TO_READ_HEAD; return true; } if (!tryReferRawBody(a, count)) { readRawBody(count); a.acceptRaw(raw); raw = null; } headByte = REQUIRE_TO_READ_HEAD; return true; } if ((b & 0xf0) == 0x90) { // FixArray int count = b & 0x0f; // System.out.println("fixarray count:"+count); a.acceptArray(count); stack.reduceCount(); stack.pushArray(count); headByte = REQUIRE_TO_READ_HEAD; return false; } if ((b & 0xf0) == 0x80) { // FixMap int count = b & 0x0f; // System.out.println("fixmap count:"+count/2); a.acceptMap(count); stack.reduceCount(); stack.pushMap(count); headByte = REQUIRE_TO_READ_HEAD; return false; } return readOneWithoutStackLarge(a, b); } private boolean readOneWithoutStackLarge(Accept a, final int b) throws IOException { switch (b & 0xff) { case 0xc0: // nil a.acceptNil(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xc2: // false a.acceptBoolean(false); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xc3: // true a.acceptBoolean(true); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xca: // float a.acceptFloat(in.getFloat()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xcb: // double a.acceptDouble(in.getDouble()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xcc: // unsigned int 8 a.acceptUnsignedInteger(in.getByte()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xcd: // unsigned int 16 a.acceptUnsignedInteger(in.getShort()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xce: // unsigned int 32 a.acceptUnsignedInteger(in.getInt()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xcf: // unsigned int 64 a.acceptUnsignedInteger(in.getLong()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xd0: // signed int 8 a.acceptInteger(in.getByte()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xd1: // signed int 16 a.acceptInteger(in.getShort()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xd2: // signed int 32 a.acceptInteger(in.getInt()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xd3: // signed int 64 a.acceptInteger(in.getLong()); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; case 0xda: // raw 16 { int count = in.getShort() & 0xffff; if (count == 0) { a.acceptEmptyRaw(); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; } if (count >= rawSizeLimit) { String reason = String.format( "Size of raw (%d) over limit at %d", new Object[] { count, rawSizeLimit }); throw new SizeLimitException(reason); } in.advance(); if (!tryReferRawBody(a, count)) { readRawBody(count); a.acceptRaw(raw); raw = null; } headByte = REQUIRE_TO_READ_HEAD; return true; } case 0xdb: // raw 32 { int count = in.getInt(); if (count == 0) { a.acceptEmptyRaw(); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return true; } if (count < 0 || count >= rawSizeLimit) { String reason = String.format( "Size of raw (%d) over limit at %d", new Object[] { count, rawSizeLimit }); throw new SizeLimitException(reason); } in.advance(); if (!tryReferRawBody(a, count)) { readRawBody(count); a.acceptRaw(raw); raw = null; } headByte = REQUIRE_TO_READ_HEAD; return true; } case 0xdc: // array 16 { int count = in.getShort() & 0xffff; if (count >= arraySizeLimit) { String reason = String.format( "Size of array (%d) over limit at %d", new Object[] { count, arraySizeLimit }); throw new SizeLimitException(reason); } a.acceptArray(count); stack.reduceCount(); stack.pushArray(count); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return false; } case 0xdd: // array 32 { int count = in.getInt(); if (count < 0 || count >= arraySizeLimit) { String reason = String.format( "Size of array (%d) over limit at %d", new Object[] { count, arraySizeLimit }); throw new SizeLimitException(reason); } a.acceptArray(count); stack.reduceCount(); stack.pushArray(count); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return false; } case 0xde: // map 16 { int count = in.getShort() & 0xffff; if (count >= mapSizeLimit) { String reason = String.format( "Size of map (%d) over limit at %d", new Object[] { count, mapSizeLimit }); throw new SizeLimitException(reason); } a.acceptMap(count); stack.reduceCount(); stack.pushMap(count); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return false; } case 0xdf: // map 32 { int count = in.getInt(); if (count < 0 || count >= mapSizeLimit) { String reason = String.format( "Size of map (%d) over limit at %d", new Object[] { count, mapSizeLimit }); throw new SizeLimitException(reason); } a.acceptMap(count); stack.reduceCount(); stack.pushMap(count); in.advance(); headByte = REQUIRE_TO_READ_HEAD; return false; } default: // System.out.println("unknown b "+(b&0xff)); // headByte = CS_INVALID headByte = REQUIRE_TO_READ_HEAD; throw new IOException("Invalid byte: " + b); // TODO error FormatException } } private boolean tryReferRawBody(BufferReferer referer, int size) throws IOException { return in.tryRefer(referer, size); } private void readRawBody(int size) throws IOException { raw = new byte[size]; rawFilled = 0; readRawBodyCont(); } private void readRawBodyCont() throws IOException { int len = in.read(raw, rawFilled, raw.length - rawFilled); rawFilled += len; if (rawFilled < raw.length) { throw new EOFException(); } } @Override protected boolean tryReadNil() throws IOException { stack.checkCount(); int b = getHeadByte() & 0xff; if (b == 0xc0) { // nil is read stack.reduceCount(); headByte = REQUIRE_TO_READ_HEAD; return true; } // not nil return false; } @Override public boolean trySkipNil() throws IOException { if (stack.getDepth() > 0 && stack.getTopCount() <= 0) { // end of array or map return true; } int b = getHeadByte() & 0xff; if (b == 0xc0) { // nil is skipped stack.reduceCount(); headByte = REQUIRE_TO_READ_HEAD; return true; } // not nil return false; } @Override public void readNil() throws IOException { // optimized not to allocate nilAccept stack.checkCount(); int b = getHeadByte() & 0xff; if (b == 0xc0) { stack.reduceCount(); headByte = REQUIRE_TO_READ_HEAD; return; } throw new MessageTypeException("Expected nil but got not nil value"); } @Override public boolean readBoolean() throws IOException { // optimized not to allocate booleanAccept stack.checkCount(); int b = getHeadByte() & 0xff; if (b == 0xc2) { stack.reduceCount(); headByte = REQUIRE_TO_READ_HEAD; return false; } else if (b == 0xc3) { stack.reduceCount(); headByte = REQUIRE_TO_READ_HEAD; return true; } throw new MessageTypeException( "Expected Boolean but got not boolean value"); } @Override public byte readByte() throws IOException { // optimized not to allocate byteAccept stack.checkCount(); readOneWithoutStack(intAccept); int value = intAccept.value; if (value < (int) Byte.MIN_VALUE || value > (int) Byte.MAX_VALUE) { throw new MessageTypeException(); // TODO message } stack.reduceCount(); return (byte) value; } @Override public short readShort() throws IOException { // optimized not to allocate shortAccept stack.checkCount(); readOneWithoutStack(intAccept); int value = intAccept.value; if (value < (int) Short.MIN_VALUE || value > (int) Short.MAX_VALUE) { throw new MessageTypeException(); // TODO message } stack.reduceCount(); return (short) value; } @Override public int readInt() throws IOException { readOne(intAccept); return intAccept.value; } @Override public long readLong() throws IOException { readOne(longAccept); return longAccept.value; } @Override public BigInteger readBigInteger() throws IOException { readOne(bigIntegerAccept); return bigIntegerAccept.value; } @Override public float readFloat() throws IOException { readOne(doubleAccept); return (float) doubleAccept.value; } @Override public double readDouble() throws IOException { readOne(doubleAccept); return doubleAccept.value; } @Override public byte[] readByteArray() throws IOException { readOne(byteArrayAccept); return byteArrayAccept.value; } @Override public String readString() throws IOException { readOne(stringAccept); return stringAccept.value; } @Override public int readArrayBegin() throws IOException { readOne(arrayAccept); return arrayAccept.size; } @Override public void readArrayEnd(boolean check) throws IOException { if (!stack.topIsArray()) { throw new MessageTypeException( "readArrayEnd() is called but readArrayBegin() is not called"); } int remain = stack.getTopCount(); if (remain > 0) { if (check) { throw new MessageTypeException( "readArrayEnd(check=true) is called but the array is not end"); } for (int i = 0; i < remain; i++) { skip(); } } stack.pop(); } @Override public int readMapBegin() throws IOException { readOne(mapAccept); return mapAccept.size; } @Override public void readMapEnd(boolean check) throws IOException { if (!stack.topIsMap()) { throw new MessageTypeException( "readMapEnd() is called but readMapBegin() is not called"); } int remain = stack.getTopCount(); if (remain > 0) { if (check) { throw new MessageTypeException( "readMapEnd(check=true) is called but the map is not end"); } for (int i = 0; i < remain; i++) { skip(); } } stack.pop(); } @Override protected void readValue(Unconverter uc) throws IOException { if (uc.getResult() != null) { uc.resetResult(); } valueAccept.setUnconverter(uc); stack.checkCount(); if (readOneWithoutStack(valueAccept)) { stack.reduceCount(); if (uc.getResult() != null) { return; } } while (true) { while (stack.getTopCount() == 0) { if (stack.topIsArray()) { uc.writeArrayEnd(true); stack.pop(); // stack.reduceCount(); } else if (stack.topIsMap()) { uc.writeMapEnd(true); stack.pop(); // stack.reduceCount(); } else { throw new RuntimeException("invalid stack"); // FIXME error? } if (uc.getResult() != null) { return; } } readOne(valueAccept); } } @Override public void skip() throws IOException { stack.checkCount(); if (readOneWithoutStack(skipAccept)) { stack.reduceCount(); return; } int targetDepth = stack.getDepth() - 1; while (true) { while (stack.getTopCount() == 0) { stack.pop(); if (stack.getDepth() <= targetDepth) { return; } } readOne(skipAccept); } } public ValueType getNextType() throws IOException { final int b = (int) getHeadByte(); if ((b & 0x80) == 0) { // Positive Fixnum return ValueType.INTEGER; } if ((b & 0xe0) == 0xe0) { // Negative Fixnum return ValueType.INTEGER; } if ((b & 0xe0) == 0xa0) { // FixRaw return ValueType.RAW; } if ((b & 0xf0) == 0x90) { // FixArray return ValueType.ARRAY; } if ((b & 0xf0) == 0x80) { // FixMap return ValueType.MAP; } switch (b & 0xff) { case 0xc0: // nil return ValueType.NIL; case 0xc2: // false case 0xc3: // true return ValueType.BOOLEAN; case 0xca: // float case 0xcb: // double return ValueType.FLOAT; case 0xcc: // unsigned int 8 case 0xcd: // unsigned int 16 case 0xce: // unsigned int 32 case 0xcf: // unsigned int 64 case 0xd0: // signed int 8 case 0xd1: // signed int 16 case 0xd2: // signed int 32 case 0xd3: // signed int 64 return ValueType.INTEGER; case 0xda: // raw 16 case 0xdb: // raw 32 return ValueType.RAW; case 0xdc: // array 16 case 0xdd: // array 32 return ValueType.ARRAY; case 0xde: // map 16 case 0xdf: // map 32 return ValueType.MAP; default: throw new IOException("Invalid byte: " + b); // TODO error FormatException } } public void reset() { raw = null; stack.clear(); } public void close() throws IOException { in.close(); } @Override public int getReadByteCount() { return in.getReadByteCount(); } @Override public void resetReadByteCount() { in.resetReadByteCount(); } }
package io.tarantool.driver.core; import io.tarantool.driver.api.TarantoolClient; import io.tarantool.driver.api.TarantoolClientConfigurator; import io.tarantool.driver.api.TarantoolResult; import io.tarantool.driver.api.proxy.ProxyOperationsMappingConfig; import io.tarantool.driver.api.retry.RequestRetryPolicyFactory; import io.tarantool.driver.api.retry.TarantoolRequestRetryPolicies; import io.tarantool.driver.api.tuple.TarantoolTuple; import io.tarantool.driver.utils.Assert; import java.util.function.Predicate; import java.util.function.UnaryOperator; import static io.tarantool.driver.api.retry.TarantoolRequestRetryPolicies.retryNetworkErrors; /** * Tarantool client configurator implementation. * * @author Oleg Kuznetsov */ public class TarantoolClientConfiguratorImpl<SELF extends TarantoolClientConfigurator<SELF>> implements TarantoolClientConfigurator<SELF> { private final TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> client; protected RequestRetryPolicyFactory retryPolicyFactory; protected ProxyOperationsMappingConfig mappingConfig; public TarantoolClientConfiguratorImpl(TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> client) { this.client = client; } protected TarantoolClientConfiguratorImpl() { this.client = null; } @Override public SELF withProxyMethodMapping() { return withProxyMethodMapping(UnaryOperator.identity()); } @Override public SELF withProxyMethodMapping( UnaryOperator<ProxyOperationsMappingConfig.Builder> builder) { this.mappingConfig = builder.apply(ProxyOperationsMappingConfig.builder()).build(); return getSelf(); } @Override public SELF withRetryingByNumberOfAttempts(int numberOfAttempts) { return withRetryingByNumberOfAttempts(numberOfAttempts, UnaryOperator.identity()); } @Override public SELF withRetryingByNumberOfAttempts( int numberOfAttempts, UnaryOperator<TarantoolRequestRetryPolicies .AttemptsBoundRetryPolicyFactory.Builder<Predicate<Throwable>>> policy) { return withRetryingByNumberOfAttempts(numberOfAttempts, retryNetworkErrors(), policy); } @Override public <T extends Predicate<Throwable>> SELF withRetryingByNumberOfAttempts( int numberOfAttempts, T exceptionsCheck, UnaryOperator<TarantoolRequestRetryPolicies.AttemptsBoundRetryPolicyFactory.Builder<T>> policy) { return withRetrying(policy.apply(TarantoolRequestRetryPolicies.AttemptsBoundRetryPolicyFactory .builder(numberOfAttempts, exceptionsCheck)).build()); } @Override public SELF withRetryingIndefinitely(UnaryOperator<TarantoolRequestRetryPolicies .InfiniteRetryPolicyFactory.Builder<Predicate<Throwable>>> policy) { return withRetryingIndefinitely(retryNetworkErrors(), policy); } @Override public <T extends Predicate<Throwable>> SELF withRetryingIndefinitely( T callback, UnaryOperator<TarantoolRequestRetryPolicies.InfiniteRetryPolicyFactory.Builder<T>> policy) { return withRetrying(policy.apply(TarantoolRequestRetryPolicies.InfiniteRetryPolicyFactory.builder(callback)) .build()); } @Override public SELF withRetrying(RequestRetryPolicyFactory factory) { this.retryPolicyFactory = factory; return getSelf(); } @Override public TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> build() { return decorate(this.client); } /** * Decorates provided client by user specified parameters. * * @param client Tarantool client for decorating * @return decorated client or the same client * if parameters for decorating in {@link TarantoolClientConfigurator} have not been provided */ protected TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> decorate(TarantoolClient<TarantoolTuple, TarantoolResult<TarantoolTuple>> client) { Assert.notNull(client, "Tarantool client must not be null!"); if (this.mappingConfig != null) { client = new ProxyTarantoolTupleClient(client, this.mappingConfig); } if (this.retryPolicyFactory != null) { client = new RetryingTarantoolTupleClient(client, this.retryPolicyFactory); } return client; } @SuppressWarnings("unchecked") private SELF getSelf() { return (SELF) this; } }
/* * GeoServer-Manager - Simple Manager Library for GeoServer * * Copyright (C) 2007,2012 GeoSolutions S.A.S. * http://www.geo-solutions.it * * 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 it.geosolutions.geoserver.rest.encoder.datastore; import it.geosolutions.geoserver.rest.decoder.RESTDataStore; /** * Encoder for an {@value #TYPE} datastore. * * @author Gianni Barrotta * @author Oscar Fonts */ public class GSOracleNGDatastoreEncoder extends GSAbstractDatastoreEncoder { static final String TYPE = "Oracle NG"; static final String DEFAULT_DB_TYPE = "oracle"; static final int DEFAULT_MIN_CONNECTIONS = 1; static final int DEFAULT_MAX_CONNECTIONS = 10; static final int DEFAULT_FETCH_SIZE = 1000; static final int DEFAULT_CONNECTION_TIMEOUT = 20; static final boolean DEFAULT_LOOSE_BBOX = true; static final boolean DEFAULT_METADATA_BBOX = false; static final boolean DEFAULT_PREPARED_STATEMENTS = true; static final int DEFAULT_MAX_OPEN_PREPARED_STATEMENTS = 50; static final boolean DEFAULT_ESTIMATED_EXTENDS = true; static final boolean DEFAULT_VALIDATE_CONNECTIONS = true; static final boolean DEFAULT_TEST_WHILE_IDLE = true; static final int DEFAULT_BATCH_INSERT_SIZE = 1; static final int DEFAULT_EVICTOR_RUN_PERIODICITY = 300; static final int DEFAULT_MAX_CONNECTION_IDLE_TIME = 300; static final int DEFAULT_EVICTOR_TESTS_PER_RUN = 3; /** * Create an {@value #TYPE} datastore with default connection parameters, given a store name, and a database name. * * @param name * datastore name * @param database * database name */ public GSOracleNGDatastoreEncoder(String name, String database) { super(name); // Set mandatory parameter setType(TYPE); setDatabaseType(DEFAULT_DB_TYPE); setDatabase(database); // Set default values setMinConnections(DEFAULT_MIN_CONNECTIONS); setMaxConnections(DEFAULT_MAX_CONNECTIONS); setFetchSize(DEFAULT_FETCH_SIZE); setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT); setLooseBBox(DEFAULT_LOOSE_BBOX); setMetadataBbox(DEFAULT_METADATA_BBOX); setPreparedStatements(DEFAULT_PREPARED_STATEMENTS); setMaxOpenPreparedStatements(DEFAULT_MAX_OPEN_PREPARED_STATEMENTS); setEstimatedExtends(DEFAULT_ESTIMATED_EXTENDS); setBatchInsertSize(DEFAULT_BATCH_INSERT_SIZE); setValidateConnections(DEFAULT_VALIDATE_CONNECTIONS); setTestWhileIdle(DEFAULT_TEST_WHILE_IDLE); setEvictorRunPeriodicity(DEFAULT_EVICTOR_RUN_PERIODICITY); setMaxConnectionIdleTime(DEFAULT_MAX_CONNECTION_IDLE_TIME); setEvictorTestsPerRun(DEFAULT_EVICTOR_TESTS_PER_RUN); } /** * Create an {@value #TYPE} datastore encoder from an existing store read from server. * * @param store * The existing store. * @throws IllegalArgumentException * if store type or mandatory parameters are not valid */ public GSOracleNGDatastoreEncoder(RESTDataStore store) { super(store); // Check mandatory parameter validity ensureValidDatabase(store.getConnectionParameters().get("database")); } public void setHost(String host) { connectionParameters.set("host", host); } public void setPort(int port) { connectionParameters.set("port", Integer.toString(port)); } public void setNamespace(String namespace) { connectionParameters.set("namespace", namespace); } public void setDatabase(String database) { connectionParameters.set("database", database); } public void setSchema(String schema) { connectionParameters.set("schema", schema); } public void setUser(String user) { connectionParameters.set("user", user); } public void setPassword(String password) { connectionParameters.set("passwd", password); } public void setDatabaseType(String dbtype) { connectionParameters.set("dbtype", dbtype); } public void setJndiReferenceName(String jndiReferenceName) { connectionParameters.set("jndiReferenceName", jndiReferenceName); } public void setExposePrimaryKeys(boolean exposePrimaryKeys) { connectionParameters.set("Expose primary keys", Boolean.toString(exposePrimaryKeys)); } public void setMaxConnections(int maxConnections) { connectionParameters.set("max connections", Integer.toString(maxConnections)); } public void setMinConnections(int minConnections) { connectionParameters.set("min connections", Integer.toString(minConnections)); } public void setFetchSize(int fetchSize) { connectionParameters.set("fetch size", Integer.toString(fetchSize)); } public void setConnectionTimeout(int seconds) { connectionParameters.set("Connection timeout", Integer.toString(seconds)); } public void setValidateConnections(boolean validateConnections) { connectionParameters.set("validate connections", Boolean.toString(validateConnections)); } public void setPrimaryKeyMetadataTable(String primaryKeyMetadataTable) { connectionParameters.set("Primary key metadata table", primaryKeyMetadataTable); } public void setLooseBBox(boolean looseBBox) { connectionParameters.set("Loose bbox", Boolean.toString(looseBBox)); } public void setMetadataBbox(boolean metadataBbox) { connectionParameters.set("Metadata bbox", Boolean.toString(metadataBbox)); } public void setPreparedStatements(boolean preparedStatements) { connectionParameters.set("preparedStatements", Boolean.toString(preparedStatements)); } public void setMaxOpenPreparedStatements(int maxOpenPreparedStatements) { connectionParameters.set("Max open prepared statements", Integer.toString(maxOpenPreparedStatements)); } public void setEstimatedExtends(boolean estimatedExtends) { connectionParameters.set("Estimated extends", Boolean.toString(estimatedExtends)); } public void setTestWhileIdle(boolean testWhileIdle) { connectionParameters.set("Test while idle", Boolean.toString(testWhileIdle)); } public void setBatchInsertSize(int batchInsertSize) { connectionParameters.set("Batch insert size", Integer.toString(batchInsertSize)); } public void setEvictorRunPeriodicity(int evictorRunPeriodicity) { connectionParameters.set("Evictor run periodicity", Integer.toString(evictorRunPeriodicity)); } public void setMaxConnectionIdleTime(int maxConnectionIdleTime) { connectionParameters.set("Max connection idle time", Integer.toString(maxConnectionIdleTime)); } public void setEvictorTestsPerRun(int evictorTestsPerRun) { connectionParameters.set("Evictor tests per run", Integer.toString(evictorTestsPerRun)); } /** * Check database validity. * * @param database * the database name * @throws IllegalArgumentException * if database is null or empty */ private static void ensureValidDatabase(String database) { if (database == null || database.length() == 0) { throw new IllegalArgumentException("Oracle store database cannot be null or empty"); } } /** * @return {@value #TYPE} */ protected String getValidType() { return TYPE; } }
/** * Copyright (c) 2011, Jordi Cortadella * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package interp; import parser.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.io.*; /** Class that implements the interpreter of the language. */ public class Interp { /** Memory of the virtual machine. */ private Stack Stack; /** * Map between function names (keys) and ASTs (values). * Each entry of the map stores the root of the AST * correponding to the function. */ private HashMap<String,AslTree> FuncName2Tree; /** Standard input of the interpreter (System.in). */ private Scanner stdin; /** * Stores the line number of the current statement. * The line number is used to report runtime errors. */ private int linenumber = -1; /** File to write the trace of function calls. */ private PrintWriter trace = null; /** Nested levels of function calls. */ private int function_nesting = -1; /** * Constructor of the interpreter. It prepares the main * data structures for the execution of the main program. */ public Interp(AslTree T, String tracefile) { assert T != null; MapFunctions(T); // Creates the table to map function names into AST nodes PreProcessAST(T); // Some internal pre-processing ot the AST Stack = new Stack(); // Creates the memory of the virtual machine // Initializes the standard input of the program stdin = new Scanner (new BufferedReader(new InputStreamReader(System.in))); if (tracefile != null) { try { trace = new PrintWriter(new FileWriter(tracefile)); } catch (IOException e) { System.err.println(e); System.exit(1); } } function_nesting = -1; } /** Runs the program by calling the main function without parameters. */ public void Run() { executeFunction ("main", null); } /** Returns the contents of the stack trace */ public String getStackTrace() { return Stack.getStackTrace(lineNumber()); } /** Returns a summarized contents of the stack trace */ public String getStackTrace(int nitems) { return Stack.getStackTrace(lineNumber(), nitems); } /** * Gathers information from the AST and creates the map from * function names to the corresponding AST nodes. */ private void MapFunctions(AslTree T) { assert T != null && T.getType() == AslLexer.LIST_FUNCTIONS; FuncName2Tree = new HashMap<String,AslTree> (); int n = T.getChildCount(); for (int i = 0; i < n; ++i) { AslTree f = T.getChild(i); assert f.getType() == AslLexer.FUNC; String fname = f.getChild(0).getText(); if (FuncName2Tree.containsKey(fname)) { throw new RuntimeException("Multiple definitions of function " + fname); } FuncName2Tree.put(fname, f); } } /** * Performs some pre-processing on the AST. Basically, it * calculates the value of the literals and stores a simpler * representation. See AslTree.java for details. */ private void PreProcessAST(AslTree T) { if (T == null) return; switch(T.getType()) { case AslLexer.INT: T.setIntValue(); break; case AslLexer.STRING: T.setStringValue(); break; case AslLexer.BOOLEAN: T.setBooleanValue(); break; default: break; } int n = T.getChildCount(); for (int i = 0; i < n; ++i) PreProcessAST(T.getChild(i)); } /** * Gets the current line number. In case of a runtime error, * it returns the line number of the statement causing the * error. */ public int lineNumber() { return linenumber; } /** Defines the current line number associated to an AST node. */ private void setLineNumber(AslTree t) { linenumber = t.getLine();} /** Defines the current line number with a specific value */ private void setLineNumber(int l) { linenumber = l;} /** * Executes a function. * @param funcname The name of the function. * @param args The AST node representing the list of arguments of the caller. * @return The data returned by the function. */ private Data executeFunction (String funcname, AslTree args) { // Get the AST of the function AslTree f = FuncName2Tree.get(funcname); if (f == null) throw new RuntimeException(" function " + funcname + " not declared"); // Gather the list of arguments of the caller. This function // performs all the checks required for the compatibility of // parameters. ArrayList<Data> Arg_values = listArguments(f, args); // Dumps trace information (function call and arguments) if (trace != null) traceFunctionCall(f, Arg_values); // List of parameters of the callee AslTree p = f.getChild(1); int nparam = p.getChildCount(); // Number of parameters // Create the activation record in memory Stack.pushActivationRecord(funcname, lineNumber()); // Track line number setLineNumber(f); // Copy the parameters to the current activation record for (int i = 0; i < nparam; ++i) { String param_name = p.getChild(i).getText(); Stack.defineVariable(param_name, Arg_values.get(i)); } // Execute the instructions Data result = executeListInstructions (f.getChild(2)); // If the result is null, then the function returns void if (result == null) result = new Data(); // Dumps trace information if (trace != null) traceReturn(f, result, Arg_values); // Destroy the activation record Stack.popActivationRecord(); return result; } /** * Executes a block of instructions. The block is terminated * as soon as an instruction returns a non-null result. * Non-null results are only returned by "return" statements. * @param t The AST of the block of instructions. * @return The data returned by the instructions (null if no return * statement has been executed). */ private Data executeListInstructions (AslTree t) { assert t != null; Data result = null; int ninstr = t.getChildCount(); for (int i = 0; i < ninstr; ++i) { result = executeInstruction (t.getChild(i)); if (result != null) return result; } return null; } /** * Executes an instruction. * Non-null results are only returned by "return" statements. * @param t The AST of the instruction. * @return The data returned by the instruction. The data will be * non-null only if a return statement is executed or a block * of instructions executing a return. */ private Data executeInstruction (AslTree t) { assert t != null; setLineNumber(t); Data value; // The returned value // A big switch for all type of instructions switch (t.getType()) { // Assignment case AslLexer.ASSIGN: value = evaluateExpression(t.getChild(1)); Stack.defineVariable (t.getChild(0).getText(), value); return null; // If-then-else case AslLexer.IF: value = evaluateExpression(t.getChild(0)); checkBoolean(value); if (value.getBooleanValue()) return executeListInstructions(t.getChild(1)); // Is there else statement ? if (t.getChildCount() == 3) return executeListInstructions(t.getChild(2)); return null; // While case AslLexer.WHILE: while (true) { value = evaluateExpression(t.getChild(0)); checkBoolean(value); if (!value.getBooleanValue()) return null; Data r = executeListInstructions(t.getChild(1)); if (r != null) return r; } // Return case AslLexer.RETURN: if (t.getChildCount() != 0) { return evaluateExpression(t.getChild(0)); } return new Data(); // No expression: returns void data // Read statement: reads a variable and raises an exception // in case of a format error. case AslLexer.READ: String token = null; Data val = new Data(0);; try { token = stdin.next(); val.setValue(Integer.parseInt(token)); } catch (NumberFormatException ex) { throw new RuntimeException ("Format error when reading a number: " + token); } Stack.defineVariable (t.getChild(0).getText(), val); return null; // Write statement: it can write an expression or a string. case AslLexer.WRITE: AslTree v = t.getChild(0); // Special case for strings if (v.getType() == AslLexer.STRING) { System.out.format(v.getStringValue()); return null; } // Write an expression System.out.print(evaluateExpression(v).toString()); return null; // Function call case AslLexer.FUNCALL: executeFunction(t.getChild(0).getText(), t.getChild(1)); return null; default: assert false; // Should never happen } // All possible instructions should have been treated. assert false; return null; } /** * Evaluates the expression represented in the AST t. * @param t The AST of the expression * @return The value of the expression. */ private Data evaluateExpression(AslTree t) { assert t != null; int previous_line = lineNumber(); setLineNumber(t); int type = t.getType(); Data value = null; // Atoms switch (type) { // A variable case AslLexer.ID: value = new Data(Stack.getVariable(t.getText())); break; // An integer literal case AslLexer.INT: value = new Data(t.getIntValue()); break; // A Boolean literal case AslLexer.BOOLEAN: value = new Data(t.getBooleanValue()); break; // A function call. Checks that the function returns a result. case AslLexer.FUNCALL: value = executeFunction(t.getChild(0).getText(), t.getChild(1)); assert value != null; if (value.isVoid()) { throw new RuntimeException ("function expected to return a value"); } break; default: break; } // Retrieve the original line and return if (value != null) { setLineNumber(previous_line); return value; } // Unary operators value = evaluateExpression(t.getChild(0)); if (t.getChildCount() == 1) { switch (type) { case AslLexer.PLUS: checkInteger(value); break; case AslLexer.MINUS: checkInteger(value); value.setValue(-value.getIntegerValue()); break; case AslLexer.NOT: checkBoolean(value); value.setValue(!value.getBooleanValue()); break; default: assert false; // Should never happen } setLineNumber(previous_line); return value; } // Two operands Data value2; switch (type) { // Relational operators case AslLexer.EQUAL: case AslLexer.NOT_EQUAL: case AslLexer.LT: case AslLexer.LE: case AslLexer.GT: case AslLexer.GE: value2 = evaluateExpression(t.getChild(1)); if (value.getType() != value2.getType()) { throw new RuntimeException ("Incompatible types in relational expression"); } value = value.evaluateRelational(type, value2); break; // Arithmetic operators case AslLexer.PLUS: case AslLexer.MINUS: case AslLexer.MUL: case AslLexer.DIV: case AslLexer.MOD: value2 = evaluateExpression(t.getChild(1)); checkInteger(value); checkInteger(value2); value.evaluateArithmetic(type, value2); break; // Boolean operators case AslLexer.AND: case AslLexer.OR: // The first operand is evaluated, but the second // is deferred (lazy, short-circuit evaluation). checkBoolean(value); value = evaluateBoolean(type, value, t.getChild(1)); break; default: assert false; // Should never happen } setLineNumber(previous_line); return value; } /** * Evaluation of Boolean expressions. This function implements * a short-circuit evaluation. The second operand is still a tree * and is only evaluated if the value of the expression cannot be * determined by the first operand. * @param type Type of operator (token). * @param v First operand. * @param t AST node of the second operand. * @return An Boolean data with the value of the expression. */ private Data evaluateBoolean (int type, Data v, AslTree t) { // Boolean evaluation with short-circuit switch (type) { case AslLexer.AND: // Short circuit if v is false if (!v.getBooleanValue()) return v; break; case AslLexer.OR: // Short circuit if v is true if (v.getBooleanValue()) return v; break; default: assert false; } // Return the value of the second expression v = evaluateExpression(t); checkBoolean(v); return v; } /** Checks that the data is Boolean and raises an exception if it is not. */ private void checkBoolean (Data b) { if (!b.isBoolean()) { throw new RuntimeException ("Expecting Boolean expression"); } } /** Checks that the data is integer and raises an exception if it is not. */ private void checkInteger (Data b) { if (!b.isInteger()) { throw new RuntimeException ("Expecting numerical expression"); } } /** * Gathers the list of arguments of a function call. It also checks * that the arguments are compatible with the parameters. In particular, * it checks that the number of parameters is the same and that no * expressions are passed as parametres by reference. * @param AstF The AST of the callee. * @param args The AST of the list of arguments passed by the caller. * @return The list of evaluated arguments. */ private ArrayList<Data> listArguments (AslTree AstF, AslTree args) { if (args != null) setLineNumber(args); AslTree pars = AstF.getChild(1); // Parameters of the function // Create the list of parameters ArrayList<Data> Params = new ArrayList<Data> (); int n = pars.getChildCount(); // Check that the number of parameters is the same int nargs = (args == null) ? 0 : args.getChildCount(); if (n != nargs) { throw new RuntimeException ("Incorrect number of parameters calling function " + AstF.getChild(0).getText()); } // Checks the compatibility of the parameters passed by // reference and calculates the values and references of // the parameters. for (int i = 0; i < n; ++i) { AslTree p = pars.getChild(i); // Parameters of the callee AslTree a = args.getChild(i); // Arguments passed by the caller setLineNumber(a); if (p.getType() == AslLexer.PVALUE) { // Pass by value: evaluate the expression Params.add(i,evaluateExpression(a)); } else { // Pass by reference: check that it is a variable if (a.getType() != AslLexer.ID) { throw new RuntimeException("Wrong argument for pass by reference"); } // Find the variable and pass the reference Data v = Stack.getVariable(a.getText()); Params.add(i,v); } } return Params; } /** * Writes trace information of a function call in the trace file. * The information is the name of the function, the value of the * parameters and the line number where the function call is produced. * @param f AST of the function * @param arg_values Values of the parameters passed to the function */ private void traceFunctionCall(AslTree f, ArrayList<Data> arg_values) { function_nesting++; AslTree params = f.getChild(1); int nargs = params.getChildCount(); for (int i=0; i < function_nesting; ++i) trace.print("| "); // Print function name and parameters trace.print(f.getChild(0) + "("); for (int i = 0; i < nargs; ++i) { if (i > 0) trace.print(", "); AslTree p = params.getChild(i); if (p.getType() == AslLexer.PREF) trace.print("&"); trace.print(p.getText() + "=" + arg_values.get(i)); } trace.print(") "); if (function_nesting == 0) trace.println("<entry point>"); else trace.println("<line " + lineNumber() + ">"); } /** * Writes the trace information about the return of a function. * The information is the value of the returned value and of the * variables passed by reference. It also reports the line number * of the return. * @param f AST of the function * @param result The value of the result * @param arg_values The value of the parameters passed to the function */ private void traceReturn(AslTree f, Data result, ArrayList<Data> arg_values) { for (int i=0; i < function_nesting; ++i) trace.print("| "); function_nesting--; trace.print("return"); if (!result.isVoid()) trace.print(" " + result); // Print the value of arguments passed by reference AslTree params = f.getChild(1); int nargs = params.getChildCount(); for (int i = 0; i < nargs; ++i) { AslTree p = params.getChild(i); if (p.getType() == AslLexer.PVALUE) continue; trace.print(", &" + p.getText() + "=" + arg_values.get(i)); } trace.println(" <line " + lineNumber() + ">"); if (function_nesting < 0) trace.close(); } }
/* * Copyright 2016-2020 The jetcd 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 io.etcd.jetcd.auth; import io.etcd.jetcd.AbstractResponse; import io.etcd.jetcd.ByteSequence; import io.etcd.jetcd.api.Auth; /** * AuthRoleRevokePermissionResponse returned by {@link Auth#roleRevokePermission(ByteSequence, * ByteSequence, ByteSequence)} contains a header. */ public class AuthRoleRevokePermissionResponse extends AbstractResponse<io.etcd.jetcd.api.AuthRoleRevokePermissionResponse> { public AuthRoleRevokePermissionResponse(io.etcd.jetcd.api.AuthRoleRevokePermissionResponse response) { super(response, response.getHeader()); } }
/* * Copyright (c) 2017 Haulmont * * 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.company.library.web.town; import com.haulmont.cuba.gui.components.AbstractEditor; import com.company.library.entity.Town; public class TownEdit extends AbstractEditor<Town> { }
package com.sergey.prykhodko.parser.domain; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import javax.persistence.*; @Data @ToString @EqualsAndHashCode @Entity(name = "transaction") public class Transaction { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String place; private Long amount; @Enumerated(value = EnumType.STRING) private Currency currency; private String card; @ManyToOne @JoinColumn(name = "clientId") private Client client; }
package module350packageJava0; import java.lang.Integer; public class Foo6 { Integer int0; Integer int1; public void foo0() { new module350packageJava0.Foo5().foo6(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } public void foo5() { foo4(); } public void foo6() { foo5(); } }
package io.improbable.keanu.vertices; import io.improbable.keanu.tensor.bool.BooleanTensor; import io.improbable.keanu.tensor.dbl.DoubleTensor; import io.improbable.keanu.testcategory.Slow; import io.improbable.keanu.vertices.bool.probabilistic.BernoulliVertex; import io.improbable.keanu.vertices.dbl.KeanuRandom; import io.improbable.keanu.vertices.dbl.probabilistic.GaussianVertex; import io.improbable.keanu.vertices.generic.nonprobabilistic.operators.binary.BinaryOpLambda; import lombok.extern.slf4j.Slf4j; import org.apache.commons.math3.stat.descriptive.SummaryStatistics; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; @Slf4j public class BinaryOpVertexTest { private KeanuRandom random; @Before public void setup() { this.random = new KeanuRandom(1); } @Category(Slow.class) @Test public void canSampleFromTwoParents() { BernoulliVertex bernoulliVertex = new BernoulliVertex(0.5); GaussianVertex gaussianVertex = new GaussianVertex(0.0, 1.0); BinaryOpLambda<BooleanTensor, DoubleTensor, DoubleTensor> custom = new BinaryOpLambda<>( bernoulliVertex, gaussianVertex, (BooleanTensor f, DoubleTensor g) -> f.doubleWhere(g, DoubleTensor.scalar(0.0)) ); int N = 1000000; List<Double> samples = new ArrayList<>(); for (int i = 0; i < N; i++) { samples.add(custom.sample(random).scalar()); } SummaryStatistics stats = new SummaryStatistics(); samples.forEach(stats::addValue); double mean = stats.getMean(); double sd = stats.getStandardDeviation(); log.info("Mean: " + mean); log.info("SD: " + sd); assertEquals(0.0, mean, 0.01); assertEquals(0.707, sd, 0.01); } }
/* * Copyright The OpenTelemetry 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 io.opentelemetry.instrumentation.auto.opentelemetryapi.context.propagation; import application.io.grpc.Context; import application.io.opentelemetry.context.propagation.ContextPropagators; import application.io.opentelemetry.context.propagation.HttpTextFormat; import io.opentelemetry.OpenTelemetry; import io.opentelemetry.instrumentation.auto.api.ContextStore; public class ApplicationContextPropagators implements ContextPropagators { private final ApplicationHttpTextFormat applicationHttpTextFormat; public ApplicationContextPropagators(ContextStore<Context, io.grpc.Context> contextStore) { applicationHttpTextFormat = new ApplicationHttpTextFormat( OpenTelemetry.getPropagators().getHttpTextFormat(), contextStore); } @Override public HttpTextFormat getHttpTextFormat() { return applicationHttpTextFormat; } }
package com.publiccms.logic.service.sys; import java.util.List; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.publiccms.common.base.BaseService; import com.publiccms.common.handler.PageHandler; import com.publiccms.common.tools.CommonUtils; import com.publiccms.entities.sys.SysRoleModule; import com.publiccms.entities.sys.SysRoleModuleId; import com.publiccms.logic.dao.sys.SysRoleModuleDao; /** * * SysRoleModuleService * */ @Service @Transactional public class SysRoleModuleService extends BaseService<SysRoleModule> { /** * @param roleId * @param moduleId * @param pageIndex * @param pageSize * @return */ @Transactional(readOnly = true) public PageHandler getPage(Integer roleId, Integer moduleId, Integer pageIndex, Integer pageSize) { return dao.getPage(roleId, moduleId, pageIndex, pageSize); } /** * @param roleId * @param moduleIds */ public void updateRoleModules(Integer roleId, Integer[] moduleIds) { if (CommonUtils.notEmpty(roleId)) { @SuppressWarnings("unchecked") List<SysRoleModule> list = (List<SysRoleModule>) getPage(roleId, null, null, null).getList(); for (SysRoleModule roleModule : list) { if (ArrayUtils.contains(moduleIds, roleModule.getId().getModuleId())) { moduleIds = ArrayUtils.removeElement(moduleIds, roleModule.getId().getModuleId()); } else { delete(roleModule.getId()); } } if (CommonUtils.notEmpty(moduleIds)) { for (int moduleId : moduleIds) { save(new SysRoleModule(new SysRoleModuleId(roleId, moduleId))); } } } } /** * @param roleIds * @param moduleIds * @return */ @Transactional(readOnly = true) public List<SysRoleModule> getEntitys(Integer[] roleIds, Integer[] moduleIds) { return dao.getEntitys(roleIds, moduleIds); } /** * @param roleIds * @param moduleId * @return */ @Transactional(readOnly = true) public SysRoleModule getEntity(Integer[] roleIds, Integer moduleId) { return dao.getEntity(roleIds, moduleId); } /** * @param roleId * @return */ public int deleteByRoleId(Integer roleId) { return dao.deleteByRoleId(roleId); } /** * @param moduleId * @return */ public int deleteByModuleId(Integer moduleId) { return dao.deleteByModuleId(moduleId); } @Autowired private SysRoleModuleDao dao; }
//Constants Defined Here public interface IConst { //FinalEmployeeFH main int min_age_to_pay_tax = 18; //CEmployee1 double basicSal_DA_mul_Metro = 0.5; double basicSal_DA_mul_N_Metro = 0.4; double rent_mul = 0.1; double standard_deduction_Salaried_Pensioner_limit = 40000; // CEmployee2 double loss_From_House_Property_lim = 200000; double intrest_home_improvement_loan_lim = 30000; double exception_Home_Loan_Intrest_lim = 200000; //CEmployee3 double deduction_Sec_80C_lim = 150000; double deduction_Sec_80CCD_NPS_lim = 50000; double deduction_Sec_80CCG_lim = 50000; //CEmployee4 double medical_insurance_80D_self_lim = 50000; double medical_insurance_80D_parents_self = 50000; double medical_treatment_handicapped_dependent_lim = 125000; double expenditure_select_medical_treatment_lim = 100000; double for_rent_NO_HRA_component_lim = 60000; double for_physically_disabled_assasse_lim = 125000; double TTA80_lim = 50000; //CEmployee5 double tax_rebate_lim = 350000; double tax_rebate_amt = 2500; double tax_surcharge_lim = 5000000; double tax_surcharge_percent_coeff = 0.1; double edn_cess_and_health_cess_percent_coeff = 0.04; }
package org.springframework.boot.actuate.autoconfigure.info; import org.junit.Test; import org.springframework.boot.actuate.info.InfoEndpoint; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link InfoEndpointAutoConfiguration}. * * @author Phillip Webb */ public class InfoEndpointAutoConfigurationTests { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration( AutoConfigurations.of(InfoEndpointAutoConfiguration.class)); @Test public void runShouldHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.shutdown.enabled:true") .run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class)); } @Test public void runShouldHaveEndpointBeanEvenIfDefaultIsDisabled() { // FIXME this.contextRunner.withPropertyValues("management.endpoint.default.enabled:false") .run((context) -> assertThat(context).hasSingleBean(InfoEndpoint.class)); } @Test public void runWhenEnabledPropertyIsFalseShouldNotHaveEndpointBean() { this.contextRunner.withPropertyValues("management.endpoint.info.enabled:false") .run((context) -> assertThat(context) .doesNotHaveBean(InfoEndpoint.class)); } }
package com.clouddev.androidgenerator.writer; import java.io.File; import com.clouddev.androidgenerator.model.Database; public class DatabaseHelperWriter extends ParentWriter { public DatabaseHelperWriter(Database database) { super(database); } @Override protected String getTemplate() { String template = "DatabaseHelper.java.ftl"; System.out.println("Reading template from file : "+template); return template; } @Override protected String getOutputFile() { String output = database.getPackageName().replace('.', File.separatorChar)+ File.separator+DATA_PATH+ File.separator+database.getClassName()+"DatabaseHelper"+FILE_EXTENSION; System.out.println("Output file to : "+output); return output; } }
/* * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.eagle.app.proxy.exception; public class StreamProxyException extends Exception { public StreamProxyException() { super(); } public StreamProxyException(String message) { super(message); } public StreamProxyException(String message, Throwable cause) { super(message, cause); } public StreamProxyException(Throwable cause) { super(cause); } protected StreamProxyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
/* * Copyright 1999-2019 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.csp.sentinel.adapter.spring.webflux; import java.util.Optional; import com.alibaba.csp.sentinel.EntryType; import com.alibaba.csp.sentinel.ResourceTypeConstants; import com.alibaba.csp.sentinel.adapter.reactor.ContextConfig; import com.alibaba.csp.sentinel.adapter.reactor.EntryConfig; import com.alibaba.csp.sentinel.adapter.reactor.SentinelReactorTransformer; import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.WebFluxCallbackManager; import com.alibaba.csp.sentinel.util.StringUtil; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebFilter; import org.springframework.web.server.WebFilterChain; import reactor.core.publisher.Mono; /** * @author Eric Zhao * @since 1.5.0 */ public class SentinelWebFluxFilter implements WebFilter { public static final String SENTINEL_SPRING_WEBFLUX_CONTEXT_NAME = "sentinel_spring_webflux_context"; @Override public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { // Maybe we can get the URL pattern elsewhere via: // exchange.getAttributeOrDefault(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, path) String path = exchange.getRequest().getPath().value(); String finalPath = WebFluxCallbackManager.getUrlCleaner().apply(exchange, path); if (StringUtil.isEmpty(finalPath)) { return chain.filter(exchange); } return chain.filter(exchange) .transform(buildSentinelTransformer(exchange, finalPath)); } private SentinelReactorTransformer<Void> buildSentinelTransformer(ServerWebExchange exchange, String finalPath) { String origin = Optional.ofNullable(WebFluxCallbackManager.getRequestOriginParser()) .map(f -> f.apply(exchange)) .orElse(EMPTY_ORIGIN); return new SentinelReactorTransformer<>(new EntryConfig(finalPath, ResourceTypeConstants.COMMON_WEB, EntryType.IN, new ContextConfig(getContextName(exchange), origin))); } protected String getContextName(ServerWebExchange exchange){ return SENTINEL_SPRING_WEBFLUX_CONTEXT_NAME; } private static final String EMPTY_ORIGIN = ""; }
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.processor.intercept; import org.apache.camel.builder.RouteBuilder; public class InterceptFromWithPredicateAndProceedRouteTest extends InterceptFromRouteTestSupport { @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { interceptFrom().when(header("foo").isEqualTo("bar")).to("mock:b"); from("direct:start").to("mock:a"); } }; } @Override protected void prepareMatchingTest() { a.expectedMessageCount(1); b.expectedMessageCount(1); } @Override protected void prepareNonMatchingTest() { a.expectedMessageCount(1); b.expectedMessageCount(0); } }
/* * Copyright 2013-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.netflix.ribbon.apache; import java.io.ByteArrayInputStream; import java.net.URI; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.entity.BasicHttpEntity; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; /** * @author Spencer Gibb */ public class RibbonApacheHttpResponseTests { @Test public void testNullEntity() throws Exception { StatusLine statusLine = mock(StatusLine.class); given(statusLine.getStatusCode()).willReturn(204); HttpResponse response = mock(HttpResponse.class); given(response.getStatusLine()).willReturn(statusLine); RibbonApacheHttpResponse httpResponse = new RibbonApacheHttpResponse(response, URI.create("http://example.com")); assertThat(httpResponse.isSuccess()).isTrue(); assertThat(httpResponse.hasPayload()).isFalse(); assertThat(httpResponse.getPayload()).isNull(); assertThat(httpResponse.getInputStream()).isNull(); } @Test public void testNotNullEntity() throws Exception { StatusLine statusLine = mock(StatusLine.class); given(statusLine.getStatusCode()).willReturn(204); HttpResponse response = mock(HttpResponse.class); given(response.getStatusLine()).willReturn(statusLine); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(new byte[0])); given(response.getEntity()).willReturn(entity); RibbonApacheHttpResponse httpResponse = new RibbonApacheHttpResponse(response, URI.create("http://example.com")); assertThat(httpResponse.isSuccess()).isTrue(); assertThat(httpResponse.hasPayload()).isTrue(); assertThat(httpResponse.getPayload()).isNotNull(); assertThat(httpResponse.getInputStream()).isNotNull(); } }
package com.fjun.androidjavaweatherlabapp.Yr; import org.simpleframework.xml.core.Persister; import org.simpleframework.xml.strategy.TreeStrategy; import org.simpleframework.xml.strategy.Type; import org.simpleframework.xml.strategy.Value; import org.simpleframework.xml.stream.NodeMap; import java.util.Map; import javax.inject.Inject; import retrofit2.Retrofit; import retrofit2.converter.simplexml.SimpleXmlConverterFactory; /** * Create retrofit service for YR. */ public class YrRetrofit { @Inject YrRetrofit() { } public YrWeatherService createYrWeatherService() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(YrWeatherService.BASE_URL) .addConverterFactory(SimpleXmlConverterFactory.createNonStrict(new Persister(new TreeStrategyWithoutClass()))) .build(); return retrofit.create(YrWeatherService.class); } // Ignore class attributes in xml, and use own named classes instead. private class TreeStrategyWithoutClass extends TreeStrategy { @Override public Value read(Type type, NodeMap node, Map map) { return null; } } }
/* * Copyright (C) 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.iot.smcp; import java.util.concurrent.ScheduledExecutorService; import java.util.logging.Logger; @SuppressWarnings("ConstantConditions") class FakeExecutorTestBase extends ExecutorTestBase { private static final boolean DEBUG = false; private static final Logger LOGGER = Logger.getLogger(ExecutorTestBase.class.getCanonicalName()); public ScheduledExecutorService createNewScheduledExecutorService() { return new FakeScheduledExecutorService() { @Override public void execute(Runnable command) { super.execute( () -> { try { command.run(); } catch (Throwable x) { LOGGER.info("Caught throwable: " + x); x.printStackTrace(); mThrowable = x; } }); } }; } public long nanoTime() { return ((FakeScheduledExecutorService) mOriginalExecutor).nanoTime(); } public void tick(int durationInMs) throws Exception { if (DEBUG) LOGGER.info("tick(" + durationInMs + ") ENTER"); super.tick(1); ((FakeScheduledExecutorService) mOriginalExecutor).tick(durationInMs); super.tick(1); if (DEBUG) LOGGER.info("tick(" + durationInMs + ") EXIT"); } }
/* 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.camunda.bpm.engine.impl.persistence.entity; import org.camunda.bpm.engine.impl.context.Context; import org.camunda.bpm.engine.impl.core.variable.scope.AbstractVariableScope; import org.camunda.bpm.engine.impl.core.variable.scope.VariableInstanceLifecycleListener; import org.camunda.bpm.engine.impl.history.HistoryLevel; import org.camunda.bpm.engine.impl.history.event.HistoryEvent; import org.camunda.bpm.engine.impl.history.event.HistoryEventProcessor; import org.camunda.bpm.engine.impl.history.event.HistoryEventTypes; import org.camunda.bpm.engine.impl.history.handler.HistoryEventHandler; import org.camunda.bpm.engine.impl.history.producer.HistoryEventProducer; /** * @author Thorben Lindhauer * */ public class VariableInstanceHistoryListener implements VariableInstanceLifecycleListener<VariableInstanceEntity> { public static final VariableInstanceHistoryListener INSTANCE = new VariableInstanceHistoryListener(); @Override public void onCreate(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) { if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_CREATE, variableInstance)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricVariableCreateEvt(variableInstance, sourceScope); } }); } } @Override public void onDelete(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) { if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_DELETE, variableInstance)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricVariableDeleteEvt(variableInstance, sourceScope); } }); } } @Override public void onUpdate(final VariableInstanceEntity variableInstance, final AbstractVariableScope sourceScope) { if (getHistoryLevel().isHistoryEventProduced(HistoryEventTypes.VARIABLE_INSTANCE_UPDATE, variableInstance)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createHistoricVariableUpdateEvt(variableInstance, sourceScope); } }); } } protected HistoryLevel getHistoryLevel() { return Context.getProcessEngineConfiguration().getHistoryLevel(); } }
/* * This software is licensed under the Apache 2 license, quoted below. * * Copyright (c) 1999-2021, Algorithmx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.algorithmx.rulii.annotation; import org.algorithmx.rulii.bind.match.BindingMatchingStrategy; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation to specify which type of Matching strategy to use. * * @author Max Arulananthan * @since 1.0 */ @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Match { /** * Determines the Binding strategy to use (during parameter matching). * * @return Binding Strategy to use. Defaults to MATCH_BY_NAME. */ Class<? extends BindingMatchingStrategy> using(); }
package com.slack.api.bolt.request.builtin; import com.slack.api.app_backend.views.payload.ViewSubmissionPayload; import com.slack.api.bolt.context.builtin.ViewSubmissionContext; import com.slack.api.bolt.request.Request; import com.slack.api.bolt.request.RequestHeaders; import com.slack.api.bolt.request.RequestType; import com.slack.api.util.json.GsonFactory; import lombok.ToString; @ToString(callSuper = true) public class ViewSubmissionRequest extends Request<ViewSubmissionContext> { private final String requestBody; private final RequestHeaders headers; private final ViewSubmissionPayload payload; public ViewSubmissionRequest( String requestBody, String payloadBody, RequestHeaders headers) { this.requestBody = requestBody; this.headers = headers; this.payload = GsonFactory.createSnakeCase().fromJson(payloadBody, ViewSubmissionPayload.class); getContext().setEnterpriseId(payload.getTeam().getEnterpriseId()); getContext().setTeamId(payload.getTeam().getId()); getContext().setRequestUserId(payload.getUser().getId()); getContext().setResponseUrls(payload.getResponseUrls()); } private ViewSubmissionContext context = new ViewSubmissionContext(); @Override public ViewSubmissionContext getContext() { return context; } @Override public RequestType getRequestType() { return RequestType.ViewSubmission; } @Override public String getRequestBodyAsString() { return requestBody; } @Override public RequestHeaders getHeaders() { return this.headers; } @Override public String getResponseUrl() { if (payload.getResponseUrls() == null || payload.getResponseUrls().size() == 0) { return null; } else { int numOfResponseUrls = payload.getResponseUrls().size(); if (numOfResponseUrls > 1) { // NOTE: As of March 2020, response_url_enabled field can be used on a single block element in a view. // That said, the payload can have multiple URLs here. The warning message is just for possible changes in the future. String warnMessage = "You have " + numOfResponseUrls + " `response_url`s in the payload. " + "ViewSubmissionRequest#getResponseUrl() always returns the first one."; getContext().getLogger().warn(warnMessage); } return payload.getResponseUrls().get(0).getResponseUrl(); } } public ViewSubmissionPayload getPayload() { return payload; } }
/** * Copyright (C) 2014-2018 LinkedIn Corp. (pinot-core@linkedin.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.thirdeye.detection.finetune; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Iterables; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import com.linkedin.thirdeye.datalayer.bao.DatasetConfigManager; import com.linkedin.thirdeye.datalayer.bao.EventManager; import com.linkedin.thirdeye.datalayer.bao.MergedAnomalyResultManager; import com.linkedin.thirdeye.datalayer.bao.MetricConfigManager; import com.linkedin.thirdeye.datalayer.dto.DetectionConfigDTO; import com.linkedin.thirdeye.datalayer.dto.MergedAnomalyResultDTO; import com.linkedin.thirdeye.datasource.DAORegistry; import com.linkedin.thirdeye.datasource.ThirdEyeCacheRegistry; import com.linkedin.thirdeye.datasource.loader.AggregationLoader; import com.linkedin.thirdeye.datasource.loader.DefaultAggregationLoader; import com.linkedin.thirdeye.datasource.loader.DefaultTimeSeriesLoader; import com.linkedin.thirdeye.datasource.loader.TimeSeriesLoader; import com.linkedin.thirdeye.detection.spi.model.AnomalySlice; import com.linkedin.thirdeye.detection.DataProvider; import com.linkedin.thirdeye.detection.DefaultDataProvider; import com.linkedin.thirdeye.detection.DetectionPipeline; import com.linkedin.thirdeye.detection.DetectionPipelineLoader; import com.linkedin.thirdeye.detection.DetectionPipelineResult; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GridSearchTuningAlgorithm implements TuningAlgorithm { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final Logger LOG = LoggerFactory.getLogger(GridSearchTuningAlgorithm.class); private final String jsonProperties; private final LinkedHashMap<String, List<Number>> parameters; private final DetectionPipelineLoader loader; private final DataProvider provider; private final MergedAnomalyResultManager anomalyDAO; private Map<DetectionConfigDTO, Double> scores; private Map<DetectionConfigDTO, DetectionPipelineResult> results; private ScoreFunction scoreFunction; /** * Instantiates a new Grid search tuning algorithm. * * @param jsonProperties the json properties for detection config * @param parameters the parameters to tune. LinkedHashMap from json path to values to try * */ public GridSearchTuningAlgorithm(String jsonProperties, LinkedHashMap<String, List<Number>> parameters) { this.jsonProperties = jsonProperties; this.parameters = parameters; this.loader = new DetectionPipelineLoader(); MetricConfigManager metricDAO = DAORegistry.getInstance().getMetricConfigDAO(); DatasetConfigManager datasetDAO = DAORegistry.getInstance().getDatasetConfigDAO(); EventManager eventDAO = DAORegistry.getInstance().getEventDAO(); this.anomalyDAO = DAORegistry.getInstance().getMergedAnomalyResultDAO(); TimeSeriesLoader timeseriesLoader = new DefaultTimeSeriesLoader(metricDAO, datasetDAO, ThirdEyeCacheRegistry.getInstance().getQueryCache()); AggregationLoader aggregationLoader = new DefaultAggregationLoader(metricDAO, datasetDAO, ThirdEyeCacheRegistry.getInstance().getQueryCache(), ThirdEyeCacheRegistry.getInstance().getDatasetMaxDataTimeCache()); this.provider = new DefaultDataProvider(metricDAO, datasetDAO, eventDAO, anomalyDAO, timeseriesLoader, aggregationLoader, loader); this.scores = new HashMap<>(); this.results = new LinkedHashMap<>(); this.scoreFunction = new TimeBucketF1ScoreFunction(); } /** * Fit into a time range and evaluate the best config. * * @param slice anomaly slice * @throws Exception the exception */ @Override public void fit(AnomalySlice slice, long configId) throws Exception { Collection<MergedAnomalyResultDTO> testAnomalies = this.provider.fetchAnomalies(Collections.singletonList(slice), configId).get(slice); fit(slice, new HashMap<String, Number>(), testAnomalies); } /** * Fit into a time range and evaluate the best config recursively. * */ private void fit(AnomalySlice slice, Map<String, Number> currentParameters, Collection<MergedAnomalyResultDTO> testAnomalies) throws Exception { if (currentParameters.size() == this.parameters.size()) { DetectionConfigDTO config = makeConfigFromParameters(currentParameters); DetectionPipeline pipeline = this.loader.from(this.provider, config, slice.getStart(), slice.getEnd()); DetectionPipelineResult result = pipeline.run(); this.results.put(config, result); // calculate score this.scores.put(config, this.scoreFunction.calculateScore(result, testAnomalies)); LOG.info("Score for detection config {} is {}", OBJECT_MAPPER.writeValueAsString(config), this.scores.get(config)); return; } String path = Iterables.get(this.parameters.keySet(), currentParameters.size()); List<Number> values = this.parameters.get(path); for (Number value : values) { currentParameters.put(path, value); fit(slice, currentParameters, testAnomalies); currentParameters.remove(path); } } private DetectionConfigDTO makeConfigFromParameters(Map<String, Number> currentParameters) throws IOException { DocumentContext jsonContext = JsonPath.parse(this.jsonProperties); // Replace parameters using json path for (Map.Entry<String, Number> entry : currentParameters.entrySet()) { String path = entry.getKey(); Number value = entry.getValue(); jsonContext.set(path, value); } Map<String, Object> properties = OBJECT_MAPPER.readValue(jsonContext.jsonString(), Map.class); DetectionConfigDTO config = new DetectionConfigDTO(); config.setId(Long.MAX_VALUE); config.setName("preview"); config.setProperties(properties); return config; } /** * Get the best detection config detection config in this grid search. * * @return the detection config dto */ @Override public DetectionConfigDTO bestDetectionConfig() { // returns the detection config with the highest score double maxVal = -1; DetectionConfigDTO bestConfig = null; for (Map.Entry<DetectionConfigDTO, Double> entry : this.scores.entrySet()) { if (entry.getValue() > maxVal) { bestConfig = entry.getKey(); maxVal = entry.getValue(); } } if (bestConfig != null) { try { LOG.info("Best detection config found is {} with score {}", OBJECT_MAPPER.writeValueAsString(bestConfig), this.scores.get(bestConfig)); } catch (JsonProcessingException e) { LOG.error("error processing json config", e); } return bestConfig; } // if no scores is available, compare the number of anomalies detected by each config. if (!this.results.isEmpty()) { int maxNumberOfAnomalies = 0; bestConfig = (DetectionConfigDTO) results.keySet().toArray()[0]; for (Map.Entry<DetectionConfigDTO, DetectionPipelineResult> entry : results.entrySet()) { if (entry.getValue().getAnomalies().size() > maxNumberOfAnomalies) { bestConfig = entry.getKey(); maxNumberOfAnomalies = entry.getValue().getAnomalies().size(); } } } return bestConfig; } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services // // Microsoft Cognitive Services (formerly Project Oxford) GitHub: // https://github.com/Microsoft/Cognitive-Face-Android // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // package com.microsoft.projectoxford.face.common; import java.util.UUID; public class ClientError { public String code; public String message; public UUID requestId; }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/video/transcoder/v1beta1/services.proto package com.google.cloud.video.transcoder.v1beta1; public interface GetJobRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.video.transcoder.v1beta1.GetJobRequest) com.google.protobuf.MessageOrBuilder { /** * <pre> * Required. The name of the job to retrieve. * Format: `projects/{project}/locations/{location}/jobs/{job}` * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The name. */ java.lang.String getName(); /** * <pre> * Required. The name of the job to retrieve. * Format: `projects/{project}/locations/{location}/jobs/{job}` * </pre> * * <code>string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }</code> * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); }
package org.openxsp.java.session; /** * Created by Frank Schulze on 23.05.14. * frank.schulze at fokus.fraunhofer.de */ public enum SessionControlMessageHeaderElement { IMS_CONTEXT }
interface Bar { boolean ABC = 2; } class BarImpl implements Bar { { boolean a = A<caret>zzz; } }
package com.cy.pj.sys.pojo; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class SysRole implements Serializable { private static final long serialVersionUID = -8557710039441592130L; private Integer id; private String name; private String note; @JsonFormat(pattern = "yyyy/MM/dd HH:mm",timezone = "GMT+8") private Date createdTime; @JsonFormat(pattern = "yyyy/MM/dd HH:mm",timezone = "GMT+8") private Date modifiedTime; private String createdUser; private String modifiedUser; }
package org.smartregister.domain; import com.google.gson.annotations.SerializedName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.joda.time.DateTime; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; @ToString @Data public class Task implements Serializable { private static final long serialVersionUID = -9118755114172291102L; public enum TaskStatus { @SerializedName("Draft") DRAFT, @SerializedName("Ready") READY, @SerializedName("Cancelled") CANCELLED, @SerializedName("In Progress") IN_PROGRESS, @SerializedName("Completed") COMPLETED, @SerializedName("Failed") FAILED, @SerializedName("Archived") ARCHIVED; private static final Map<String, TaskStatus> lookup = new HashMap<String, TaskStatus>(); static { lookup.put("Draft", TaskStatus.DRAFT); lookup.put("Ready", TaskStatus.READY); lookup.put("Cancelled", TaskStatus.CANCELLED); lookup.put("In Progress", TaskStatus.IN_PROGRESS); lookup.put("Completed", TaskStatus.COMPLETED); lookup.put("Failed", TaskStatus.FAILED); lookup.put("Archived", TaskStatus.ARCHIVED); } public static TaskStatus get(String algorithm) { return lookup.get(algorithm); } } public enum TaskPriority { @SerializedName("stat") STAT, @SerializedName("asap") ASAP, @SerializedName("urgent") URGENT, @SerializedName("routine") ROUTINE; public static TaskPriority get(String priority) { if (priority == null) throw new IllegalArgumentException("Value is required"); switch (priority) { case "routine": return ROUTINE; case "urgent": return URGENT; case "asap": return ASAP; case "stat": return STAT; default: throw new IllegalArgumentException("Not a valid Task priority"); } } } public static final String[] INACTIVE_TASK_STATUS = new String[] { TaskStatus.CANCELLED.name(), TaskStatus.ARCHIVED.name() }; private String identifier; private String planIdentifier; private String groupIdentifier; private TaskStatus status; private String businessStatus; private TaskPriority priority; private String code; private String description; private String focus; @SerializedName("for") private String forEntity; private Period executionPeriod; private DateTime authoredOn; private DateTime lastModified; private String owner; @SerializedName("note") private List<Note> notes; private long serverVersion; private String reasonReference; private String location; private String requester; private String syncStatus; private String structureId; private Long rowid; private Restriction restriction; public Long getServerVersion() { return serverVersion; } public void setServerVersion(Long serverVersion) { this.serverVersion = serverVersion; } @Data @NoArgsConstructor @AllArgsConstructor public static class Restriction { private int repetitions; private Period period; } }
/** * 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.openejb.jee; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * web-facesconfig_2_0.xsd * * <p>Java class for faces-configType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="faces-configType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice maxOccurs="unbounded" minOccurs="0"> * &lt;element name="application" type="{http://java.sun.com/xml/ns/javaee}faces-config-applicationType"/> * &lt;element name="ordering" type="{http://java.sun.com/xml/ns/javaee}faces-config-orderingType"/> * &lt;element name="absolute-ordering" type="{http://java.sun.com/xml/ns/javaee}faces-config-absoluteOrderingType" minOccurs="0"/> * &lt;element name="factory" type="{http://java.sun.com/xml/ns/javaee}faces-config-factoryType"/> * &lt;element name="component" type="{http://java.sun.com/xml/ns/javaee}faces-config-componentType"/> * &lt;element name="converter" type="{http://java.sun.com/xml/ns/javaee}faces-config-converterType"/> * &lt;element name="managed-bean" type="{http://java.sun.com/xml/ns/javaee}faces-config-managed-beanType"/> * &lt;element name="name" type="{http://java.sun.com/xml/ns/javaee}java-identifierType" minOccurs="0"/> * &lt;element name="navigation-rule" type="{http://java.sun.com/xml/ns/javaee}faces-config-navigation-ruleType"/> * &lt;element name="referenced-bean" type="{http://java.sun.com/xml/ns/javaee}faces-config-referenced-beanType"/> * &lt;element name="render-kit" type="{http://java.sun.com/xml/ns/javaee}faces-config-render-kitType"/> * &lt;element name="lifecycle" type="{http://java.sun.com/xml/ns/javaee}faces-config-lifecycleType"/> * &lt;element name="validator" type="{http://java.sun.com/xml/ns/javaee}faces-config-validatorType"/> * &lt;element name="behavior" type="{http://java.sun.com/xml/ns/javaee}faces-config-behaviorType"/> * &lt;element name="faces-config-extension" type="{http://java.sun.com/xml/ns/javaee}faces-config-extensionType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/choice> * &lt;attribute name="metadata-complete" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;attribute name="id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;attribute name="version" use="required" type="{http://java.sun.com/xml/ns/javaee}faces-config-versionType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> 59 * * */ @XmlRootElement(name = "faces-config") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "faces-configType", propOrder = { "application", "ordering", "absoluteOrdering", "factory", "component", "converter", "managedBean", "name", "navigationRule", "referencedBean", "renderKit", "lifecycle", "validator", "behavior", "facesConfigExtension", "flowDefinitions", "protectedViews" }) public class FacesConfig { protected List<FacesApplication> application; protected List<FacesOrdering> ordering; @XmlElement(name = "absolute-ordering") protected List<FacesAbsoluteOrdering> absoluteOrdering; protected List<FacesFactory> factory; protected List<FacesComponent> component; protected List<FacesConverter> converter; @XmlElement(name = "managed-bean") protected List<FacesManagedBean> managedBean; protected List<String> name; @XmlElement(name = "navigation-rule") protected List<FacesNavigationRule> navigationRule; @XmlElement(name = "referenced-bean") protected List<FacesReferencedBean> referencedBean; @XmlElement(name = "render-kit") protected List<FacesRenderKit> renderKit; protected List<FacesLifecycle> lifecycle; protected List<FacesValidator> validator; protected List<FacesBehavior> behavior; @XmlElement(name = "faces-config-extension") protected List<FacesExtension> facesConfigExtension; @XmlElement(name = "flow-definition") protected List<FacesConfigFlowDefinition> flowDefinitions; @XmlElement(name = "protected-views") protected List<FacesConfigProtectedViews> protectedViews; @XmlAttribute @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected java.lang.String id; @XmlAttribute(required = true) protected java.lang.String version; @XmlAttribute(name = "metadata-complete") protected Boolean metadataComplete; /** * Gets the value of the application property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the application property. * * <p> * For example, to add a new item, do as follows: * <pre> * getApplication().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesApplication } * * */ public List<FacesApplication> getApplication() { if (application == null) { application = new ArrayList<FacesApplication>(); } return this.application; } public List<FacesConfigFlowDefinition> getFlowDefinitions() { if (flowDefinitions == null) { flowDefinitions = new ArrayList<FacesConfigFlowDefinition>(); } return flowDefinitions; } public List<FacesConfigProtectedViews> getProtectedViews() { if (protectedViews == null) { protectedViews = new ArrayList<FacesConfigProtectedViews>(); } return protectedViews; } public List<FacesOrdering> getOrdering() { if (ordering == null) { ordering = new ArrayList<FacesOrdering>(); } return ordering; } public List<FacesAbsoluteOrdering> getAbsoluteOrdering() { if (absoluteOrdering == null) { absoluteOrdering = new ArrayList<FacesAbsoluteOrdering>(); } return absoluteOrdering; } /** * Gets the value of the factory property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the factory property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFactory().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesFactory } * * */ public List<FacesFactory> getFactory() { if (factory == null) { factory = new ArrayList<FacesFactory>(); } return this.factory; } /** * Gets the value of the component property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the component property. * * <p> * For example, to add a new item, do as follows: * <pre> * getComponent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesComponent } * * */ public List<FacesComponent> getComponent() { if (component == null) { component = new ArrayList<FacesComponent>(); } return this.component; } /** * Gets the value of the converter property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the converter property. * * <p> * For example, to add a new item, do as follows: * <pre> * getConverter().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesConverter } * * */ public List<FacesConverter> getConverter() { if (converter == null) { converter = new ArrayList<FacesConverter>(); } return this.converter; } /** * Gets the value of the managedBean property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the managedBean property. * * <p> * For example, to add a new item, do as follows: * <pre> * getManagedBean().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesManagedBean } * * */ public List<FacesManagedBean> getManagedBean() { if (managedBean == null) { managedBean = new ArrayList<FacesManagedBean>(); } return this.managedBean; } public List<String> getName() { if (name == null) { name = new ArrayList<String>(); } return name; } /** * Gets the value of the navigationRule property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the navigationRule property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNavigationRule().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesNavigationRule } * * */ public List<FacesNavigationRule> getNavigationRule() { if (navigationRule == null) { navigationRule = new ArrayList<FacesNavigationRule>(); } return this.navigationRule; } /** * Gets the value of the referencedBean property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the referencedBean property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReferencedBean().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesReferencedBean } * * */ public List<FacesReferencedBean> getReferencedBean() { if (referencedBean == null) { referencedBean = new ArrayList<FacesReferencedBean>(); } return this.referencedBean; } /** * Gets the value of the renderKit property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the renderKit property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRenderKit().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesRenderKit } * * */ public List<FacesRenderKit> getRenderKit() { if (renderKit == null) { renderKit = new ArrayList<FacesRenderKit>(); } return this.renderKit; } /** * Gets the value of the lifecycle property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the lifecycle property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLifecycle().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesLifecycle } * * */ public List<FacesLifecycle> getLifecycle() { if (lifecycle == null) { lifecycle = new ArrayList<FacesLifecycle>(); } return this.lifecycle; } /** * Gets the value of the validator property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the validator property. * * <p> * For example, to add a new item, do as follows: * <pre> * getValidator().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesValidator } * * */ public List<FacesValidator> getValidator() { if (validator == null) { validator = new ArrayList<FacesValidator>(); } return this.validator; } public List<FacesBehavior> getBehavior() { if (behavior == null) { behavior = new ArrayList<FacesBehavior>(); } return behavior; } /** * Gets the value of the facesConfigExtension property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the facesConfigExtension property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFacesConfigExtension().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FacesExtension } * * */ public List<FacesExtension> getFacesConfigExtension() { if (facesConfigExtension == null) { facesConfigExtension = new ArrayList<FacesExtension>(); } return this.facesConfigExtension; } /** * Gets the value of the id property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setId(java.lang.String value) { this.id = value; } /** * Gets the value of the version property. * * @return * possible object is * {@link java.lang.String } * */ public java.lang.String getVersion() { return version; } /** * Sets the value of the version property. * * @param value * allowed object is * {@link java.lang.String } * */ public void setVersion(java.lang.String value) { this.version = value; } public Boolean isMetadataComplete() { return metadataComplete != null && metadataComplete; } public void setMetadataComplete(Boolean value) { this.metadataComplete = value; } }
/** * Copyright 2005-2019 Riverside Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.phenix.pct; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.testng.Assert; import org.testng.annotations.Test; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.google.common.io.LineProcessor; import com.phenix.pct.RCodeInfo.InvalidRCodeException; /** * Class for testing PCTCompileExt task * * @author <a href="mailto:g.querret+PCT@gmail.com">Gilles QUERRET</a> */ public class PCTCompileExtTest extends BuildFileTestNg { private static final String BASEDIR = "PCTCompileExt/"; @Test(groups = {"v10"}) public void test2() { configureProject(BASEDIR + "test2/build.xml"); executeTarget("test"); } @Test(groups = {"v10"}) public void test3() { configureProject(BASEDIR + "test3/build.xml"); executeTarget("test"); File f = new File(BASEDIR + "test3/build/test.r"); assertTrue(f.exists()); } @Test(groups = {"v10"}) public void test3bis() { configureProject(BASEDIR + "test3bis/build.xml"); expectBuildException("test", "Compilation should fail"); File f = new File(BASEDIR + "test3bis/build/test.r"); assertFalse(f.exists()); } @Test(groups = {"v10"}) public void test4() { configureProject(BASEDIR + "test4/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test4/build/test.r"); File f2 = new File(BASEDIR + "test4/build2/test.r"); assertTrue(f1.exists()); assertTrue(f2.exists()); assertTrue(f2.length() < f1.length()); } @Test(groups = {"v10"}) public void test5() { configureProject(BASEDIR + "test5/build.xml"); executeTarget("test"); File f = new File(BASEDIR + "test5/build/wizz~~'~.r"); assertTrue(f.exists()); } @Test(groups = {"v10"}) public void test6() { configureProject(BASEDIR + "test6/build.xml"); executeTarget("test1"); File f = new File(BASEDIR + "test6/build/test.r"); long mod = f.lastModified(); executeTarget("test2"); assertTrue(mod == f.lastModified()); } @Test(groups = {"v10"}) public void test7() { configureProject(BASEDIR + "test7/build.xml"); executeTarget("test1"); File f = new File(BASEDIR + "test7/build/test.r"); long mod = f.lastModified(); executeTarget("test2"); assertTrue(mod < f.lastModified()); } @Test(groups = {"v10"}) public void test8() { configureProject(BASEDIR + "test8/build.xml"); executeTarget("test1"); File f = new File(BASEDIR + "test8/build/test.r"); long mod = f.lastModified(); executeTarget("test2"); assertTrue(mod < f.lastModified()); } @Test(groups = {"v10"}) public void test9() { configureProject(BASEDIR + "test9/build.xml"); executeTarget("test1"); File f = new File(BASEDIR + "test9/build/test.r"); long mod = f.lastModified(); executeTarget("test2"); assertTrue(mod < f.lastModified()); } @Test(groups = {"v10"}) public void test10() { configureProject(BASEDIR + "test10/build.xml"); executeTarget("test1"); File f = new File(BASEDIR + "test10/build/test.r"); long mod = f.lastModified(); executeTarget("test2"); assertTrue(mod < f.lastModified()); } @Test(groups = {"v10"}) public void test11() { configureProject(BASEDIR + "test11/build.xml"); expectBuildException("test", "Second task should not be launched"); File f = new File(BASEDIR + "test11/build/test2.r"); assertFalse(f.exists()); executeTarget("test2"); File f2 = new File(BASEDIR + "test11/build2/test2.r"); assertTrue(f2.exists()); executeTarget("test3"); assertTrue(new File(BASEDIR + "test11/build3/test0.r").exists()); assertFalse(new File(BASEDIR + "test11/build3/test1.r").exists()); assertTrue(new File(BASEDIR + "test11/build3/test2.r").exists()); executeTarget("test4"); assertTrue(new File(BASEDIR + "test11/build4/test0.r").exists()); assertFalse(new File(BASEDIR + "test11/build4/test1.r").exists()); assertFalse(new File(BASEDIR + "test11/build4/test2.r").exists()); } @Test(groups = {"v10"}) public void test12() { configureProject(BASEDIR + "test12/build.xml"); expectBuildException("test1", "File with underscore"); File f = new File(BASEDIR + "test12/build/test.r"); assertFalse(f.exists()); executeTarget("test2"); assertTrue(f.exists()); } @Test(groups = {"v10"}) public void test13() { configureProject(BASEDIR + "test13/build.xml"); executeTarget("test1"); File f = new File(BASEDIR + "test13/build/test.r"); long mod = f.lastModified(); executeTarget("test2"); assertTrue(mod < f.lastModified()); } @Test(groups = {"v10"}) public void test14() { configureProject(BASEDIR + "test14/build.xml"); executeTarget("base"); executeTarget("test1"); File f1 = new File(BASEDIR + "test14/build/test.r"); File f2 = new File(BASEDIR + "test14/build/test2.r"); File f3 = new File(BASEDIR + "test14/build/test3.r"); assertTrue(f1.exists()); assertTrue(f2.exists()); assertTrue(f3.exists()); long mod1 = f1.lastModified(); long mod2 = f2.lastModified(); long mod3 = f3.lastModified(); executeTarget("update"); executeTarget("test2"); assertTrue(mod1 < f1.lastModified()); assertTrue(mod2 < f2.lastModified()); assertTrue(mod3 < f3.lastModified()); } @Test(groups = {"v10"}) public void test15() { configureProject(BASEDIR + "test15/build.xml"); executeTarget("base"); executeTarget("test1"); File f = new File(BASEDIR + "test15/build/test.r"); assertTrue(f.exists()); long mod = f.lastModified(); executeTarget("test2"); assertTrue(mod == f.lastModified()); } @Test(groups = {"v10"}) public void test16() { configureProject(BASEDIR + "test16/build.xml"); executeTarget("xcode"); File f1 = new File(BASEDIR + "test16/src/xcode1/test.p"); assertTrue(f1.exists()); File f1bis = new File(BASEDIR + "test16/src/xcode2/test.p"); assertTrue(f1bis.exists()); executeTarget("test"); File f2 = new File(BASEDIR + "test16/build1/test.r"); assertTrue(f2.exists()); File f3 = new File(BASEDIR + "test16/build2/test.r"); assertTrue(f3.exists()); File f4 = new File(BASEDIR + "test16/build3/test.r"); assertTrue(f4.exists()); } @Test(groups = {"v10"}) public void test17() { configureProject(BASEDIR + "test17/build.xml"); executeTarget("xcode"); File f1 = new File(BASEDIR + "test17/src/xcode/test.p"); assertTrue(f1.exists()); expectBuildException("test1", "No XCodeKey"); executeTarget("test2"); File f2 = new File(BASEDIR + "test17/build/xcode/test.r"); assertFalse(f2.exists()); File f3 = new File(BASEDIR + "test17/build2/xcode/test.r"); assertTrue(f3.exists()); } @Test(groups = {"v10"}) public void test19() { configureProject(BASEDIR + "test19/build.xml"); executeTarget("test1"); File f1 = new File(BASEDIR + "test19/build/test.r"); File f2 = new File(BASEDIR + "test19/build/.pct/test.p.crc"); assertTrue(f1.exists()); assertTrue(f2.exists()); long mod1 = f1.lastModified(); long mod2 = f2.lastModified(); executeTarget("test2"); assertTrue(mod1 < f1.lastModified()); assertTrue(mod2 < f2.lastModified()); } @Test(groups = {"v10"}) public void test20() { configureProject(BASEDIR + "test20/build.xml"); executeTarget("test1"); File dotR = new File(BASEDIR + "test20/build/test.r"); File f1 = new File(BASEDIR + "test20/build/.pct/test.p"); File f2 = new File(BASEDIR + "test20/build/.pct/test.p.preprocess"); File f3 = new File(BASEDIR + "test20/build/.dbg/test.p"); File f4 = new File(BASEDIR + "test20/build/.pct/test.p.xref"); File f5 = new File(BASEDIR + "test20/debug/test.p"); File f6 = new File(BASEDIR + "test20/debug/dir1_dir2_test.p"); assertTrue(dotR.exists()); assertFalse(f1.exists()); assertFalse(f2.exists()); assertFalse(f3.exists()); assertFalse(f4.exists()); executeTarget("test2"); assertTrue(f1.exists(), "Unable to find listing file"); assertTrue(f2.exists(), "Unable to find preprocess file"); assertTrue(f3.exists(), "Unable to find debug-listing file"); assertTrue(f4.exists(), "Unable to find xref file"); assertTrue((f4.length() > 0), "Empty xref file"); executeTarget("test3"); assertTrue(f5.exists(), "Unable to find debug-listing file"); assertTrue(f6.exists(), "Unable to find debug-listing file"); } @Test(groups = {"v10"}) public void test21() { configureProject(BASEDIR + "test21/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test21/build/package/testclass.r"); assertTrue(f1.exists()); } @Test(groups = {"v10"}) public void test22() { configureProject(BASEDIR + "test22/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test22/build/X.r"); assertTrue(f1.exists()); File f2 = new File(BASEDIR + "test22/build/Y.r"); assertTrue(f2.exists()); File f3 = new File(BASEDIR + "test22/build/.pct/X.cls.crc"); assertTrue(f3.exists()); File f4 = new File(BASEDIR + "test22/build/.pct/Y.cls.crc"); assertTrue(f4.exists()); executeTarget("test2"); File f5 = new File(BASEDIR + "test22/build2/Y.r"); assertTrue(f5.exists()); File f6 = new File(BASEDIR + "test22/build2/X.r"); assertTrue(f6.exists()); } @Test(groups = {"v10", "win"}) public void test23() { configureProject(BASEDIR + "test23/build.xml"); expectBuildException("test1", "Should fail - No stream-io"); File f = new File(BASEDIR + "test23/build/test.r"); assertFalse(f.exists()); executeTarget("test2"); assertTrue(f.exists()); } @Test(groups = {"v10"}) public void test24() { configureProject(BASEDIR + "test24/build.xml"); File f = new File(BASEDIR + "test24/build/test.r"); assertFalse(f.exists()); executeTarget("test1"); assertFalse(f.exists()); executeTarget("test2"); assertTrue(f.exists()); } @Test(groups = {"v10"}) public void test25() { configureProject(BASEDIR + "test25/build.xml"); executeTarget("test"); File f = new File(BASEDIR + "test25/build/test.r"); assertTrue(f.exists()); } // Dropping this test case, doesn't work on 11.3 anymore, and no time to maintain it // @Test(groups= {"win"}) public void test26() { configureProject(BASEDIR + "test26/build.xml"); executeTarget("test"); File f = new File(BASEDIR + "test26/build/Ö_example.r"); assertTrue(f.exists()); } @Test(groups = {"v10"}) public void test27() { configureProject(BASEDIR + "test27/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test27/build/eu/rssw/pct/A.r"); assertTrue(f1.exists()); File f2 = new File(BASEDIR + "test27/build/eu/rssw/pct/B.r"); assertTrue(f2.exists()); File f3 = new File(BASEDIR + "test27/build/eu/rssw/pct/X.r"); assertTrue(f3.exists()); File f4 = new File(BASEDIR + "test27/build/eu/rssw/pct/Y.r"); assertTrue(f4.exists()); File f5 = new File(BASEDIR + "test27/build/eu/rssw/pct/Z.r"); assertTrue(f5.exists()); File f6 = new File(BASEDIR + "test27/build/.pct/eu/rssw/pct/Z.cls.hierarchy"); assertTrue(f6.exists()); assertTrue(f6.length() > 0); } @Test(groups = {"win", "v10"}) public void test28() { configureProject(BASEDIR + "test28/build.xml"); executeTarget("build"); File f1 = new File(BASEDIR + "test28/src-tty/test.p"); assertTrue(f1.exists()); assertTrue(f1.length() > 0); File f2 = new File(BASEDIR + "test28/src-gui/test.p"); assertTrue(f2.exists()); assertTrue(f2.length() > 0); File f3 = new File(BASEDIR + "test28/src-tty/sub1/sub2/sub3/test.p"); assertTrue(f3.exists()); File f4 = new File(BASEDIR + "test28/src-tty/sub1/sub2/sub4/test.p"); assertTrue(f4.exists()); executeTarget("test"); String str1 = getProject().getProperty("test28-tty"); assertTrue(str1.equals("TTY")); String str2 = getProject().getProperty("test28-gui"); assertTrue(str2.startsWith("MS-WIN")); } @Test(groups = {"v10"}) public void test29() { configureProject(BASEDIR + "test29/build.xml"); executeTarget("build"); File f1 = new File(BASEDIR + "test29/build1/test.r"); assertTrue(f1.exists()); File f2 = new File(BASEDIR + "test29/build2/test.r"); assertTrue(f2.exists()); executeTarget("test1"); executeTarget("test2"); executeTarget("test3"); String test1Inc = getProject().getProperty("test1-inc"); // Absolute paths, so it should be found File ff = new File(test1Inc); assertTrue(ff.exists()); String test1Main = getProject().getProperty("test1-main"); File ff2 = new File(test1Main); assertTrue(ff2.exists()); String test2Inc = getProject().getProperty("test2-inc"); assertEquals(test2Inc.replace('\\', '/'), "inc/test.i"); String test2Main = getProject().getProperty("test2-main"); assertEquals(test2Main.replace('\\', '/'), "src/test.p"); String test3Main = getProject().getProperty("test3-main"); assertEquals(test3Main.replace('\\', '/'), "src/foo/bar/test.p"); String test3Inc1 = getProject().getProperty("test3-inc1"); assertEquals(test3Inc1.replace('\\', '/'), "src/foo/foo.i"); String test3Inc2 = getProject().getProperty("test3-inc2"); assertEquals(test3Inc2.replace('\\', '/'), "inc/foo/bar.i"); } @Test(groups = {"v10"}) public void test30() { configureProject(BASEDIR + "test30/build.xml"); executeTarget("test"); assertTrue(new File(BASEDIR + "test30/build/test1.r").exists()); assertFalse(new File(BASEDIR + "test30/build/test2.r").exists()); assertTrue(new File(BASEDIR + "test30/build/test3.r").exists()); expectBuildException("test2", "ZipFileset not supported"); executeTarget("test3"); assertFalse(new File(BASEDIR + "test30/build3/test1.r").exists()); assertTrue(new File(BASEDIR + "test30/build3/test2.r").exists()); assertFalse(new File(BASEDIR + "test30/build3/test3.r").exists()); executeTarget("test4"); assertEquals(new File(BASEDIR + "test30/build4").list().length, 1); // Only .pct executeTarget("test5"); assertTrue(new File(BASEDIR + "test30/build5/test1.r").exists()); assertTrue(new File(BASEDIR + "test30/build5/test2.r").exists()); assertTrue(new File(BASEDIR + "test30/build5/test3.r").exists()); executeTarget("test6"); assertTrue(new File(BASEDIR + "test30/build6/test1.r").exists()); assertFalse(new File(BASEDIR + "test30/build6/test2.r").exists()); assertFalse(new File(BASEDIR + "test30/build6/test3.r").exists()); executeTarget("test7"); assertTrue(new File(BASEDIR + "test30/build7/test1.r").exists()); assertTrue(new File(BASEDIR + "test30/build7/test2.r").exists()); assertTrue(new File(BASEDIR + "test30/build7/test3.r").exists()); executeTarget("test8"); assertTrue(new File(BASEDIR + "test30/build8/test1.r").exists()); assertTrue(new File(BASEDIR + "test30/build8/test2.r").exists()); assertTrue(new File(BASEDIR + "test30/build8/test3.r").exists()); } @Test(groups = {"v10"}) public void test32() { configureProject(BASEDIR + "test32/build.xml"); executeTarget("test"); assertTrue(new File(BASEDIR + "test32/build1/.pct/test1.p.strxref").exists()); assertTrue(new File(BASEDIR + "test32/build1/.pct/test2.p.strxref").exists()); assertTrue(new File(BASEDIR + "test32/build2/.pct/strings.xref").exists()); } @Test(groups = {"v10"}) public void test33() { configureProject(BASEDIR + "test33/build.xml"); executeTarget("test"); assertTrue(new File(BASEDIR + "test33/build/test1.r").exists()); assertTrue(new File(BASEDIR + "test33/build/test2.r").exists()); expectBuildException("test2", "Expected failure"); assertFalse(new File(BASEDIR + "test33/build2/test1.r").exists()); assertFalse(new File(BASEDIR + "test33/build2/test2.r").exists()); assertFalse(new File(BASEDIR + "test33/build2/test3.r").exists()); } @Test(groups = {"v10"}) public void test34() throws IOException, InvalidRCodeException { configureProject(BASEDIR + "test34/build.xml"); executeTarget("test"); File dbg1 = new File(BASEDIR + "test34/debugListing/test1.p"); File dbg2 = new File(BASEDIR + "test34/debugListing/foo_bar_test2.p"); File rcode1 = new File(BASEDIR + "test34/build/test1.r"); File rcode2 = new File(BASEDIR + "test34/build/foo/bar/test2.r"); assertTrue(dbg1.exists()); assertTrue(dbg2.exists()); assertTrue(rcode1.exists()); assertTrue(rcode2.exists()); // Doesn't work... // RCodeInfo r1 = new RCodeInfo(rcode1); // RCodeInfo r2 = new RCodeInfo(rcode2); // assertEquals(r1.getDebugListingFile(), "test1.p"); // assertEquals(r2.getDebugListingFile(), "foo_bar_test2.p"); } @Test(groups = {"v10"}) public void test35() throws IOException { configureProject(BASEDIR + "test35/build.xml"); executeTarget("init"); executeTarget("test"); executeTarget("test2"); File crc = new File(BASEDIR + "test35/build/.pct/test.p.crc"); assertTrue(crc.exists()); String line = Files.readFirstLine(crc, Charset.defaultCharset()); assertTrue(line.startsWith("\"sports2000.Item\"")); File inc = new File(BASEDIR + "test35/build/.pct/test.p.inc"); assertTrue(inc.exists()); LineProcessor<Boolean> lineProcessor = new Test35LineProcessor(); Files.readLines(inc, Charset.defaultCharset(), lineProcessor); assertTrue(lineProcessor.getResult()); File crc2 = new File(BASEDIR + "test35/build2/.pct/test.p.crc"); assertTrue(crc2.exists()); String line2 = Files.readFirstLine(crc2, Charset.defaultCharset()); assertTrue(line2.startsWith("\"sports2000.Item\"")); File inc2 = new File(BASEDIR + "test35/build2/.pct/test.p.inc"); assertTrue(inc2.exists()); LineProcessor<Boolean> lineProcessor2 = new Test35LineProcessor(); Files.readLines(inc2, Charset.defaultCharset(), lineProcessor2); assertTrue(lineProcessor2.getResult()); } private final static class Test35LineProcessor implements LineProcessor<Boolean> { private boolean retVal = false; private int zz = 0; @Override public Boolean getResult() { return retVal; } @Override public boolean processLine(String line) throws IOException { if (zz == 0) { retVal = line.startsWith("\"test.i\""); } else if (zz == 1) { retVal &= line.startsWith("\"test2.i\""); } else if (zz == 2) { retVal &= line.startsWith("\"test3.i\""); } zz++; return true; } } @Test(groups = {"v10"}) public void test36() throws IOException { configureProject(BASEDIR + "test36/build.xml"); executeTarget("test"); assertTrue(new File(BASEDIR + "test36/build/bar/test1.r").exists()); assertTrue(new File(BASEDIR + "test36/build/bar/test2.r").exists()); assertTrue(new File(BASEDIR + "test36/build/bar/test3.r").exists()); assertFalse(new File(BASEDIR + "test36/build/bar/test4.r").exists()); assertTrue(new File(BASEDIR + "test36/build/foo/test.r").exists()); assertTrue(new File(BASEDIR + "test36/build/foo/subdir/subdir2/test.r").exists()); assertFalse(new File(BASEDIR + "test36/build/baz/test.r").exists()); executeTarget("test2"); assertTrue(new File(BASEDIR + "test36/build2/bar/test1.r").exists()); assertTrue(new File(BASEDIR + "test36/build2/bar/test2.r").exists()); assertTrue(new File(BASEDIR + "test36/build2/bar/test3.r").exists()); assertFalse(new File(BASEDIR + "test36/build2/bar/test4.r").exists()); assertTrue(new File(BASEDIR + "test36/build2/foo/test.r").exists()); assertTrue(new File(BASEDIR + "test36/build2/foo/subdir/subdir2/test.r").exists()); assertFalse(new File(BASEDIR + "test36/build2/baz/test.r").exists()); } // @Test(groups = {"v10"}) // Not really a test case, just to show something is broken... public void test37() throws IOException { configureProject(BASEDIR + "test37/build.xml"); executeTarget("init"); assertTrue(new File(BASEDIR + "test37/build1/package/bar.r").exists()); assertTrue(new File(BASEDIR + "test37/build1/package/Foo.r").exists()); assertTrue(new File(BASEDIR + "test37/build2/package/bar.r").exists()); assertTrue(new File(BASEDIR + "test37/build2/package/foo.r").exists()); assertTrue(new File(BASEDIR + "test37/build3/package/bAr.r").exists()); assertTrue(new File(BASEDIR + "test37/build3/package/fOO.r").exists()); executeTarget("test1"); executeTarget("test2"); executeTarget("test3"); } @Test(groups = {"v10"}) public void test38() { // Compile error with xcode configureProject(BASEDIR + "test38/build.xml"); executeTarget("init"); expectBuildException("test", "Should fail - Progress syntax error"); } @Test(groups = {"v10"}) public void test39() { // Compile error, no xcode configureProject(BASEDIR + "test39/build.xml"); expectBuildException("test", "Should fail - Progress syntax error"); } @Test(groups = {"v10"}) public void test40() { // Test keepXref attribute configureProject(BASEDIR + "test40/build.xml"); executeTarget("test"); assertFalse(new File(BASEDIR + "test40/build1/.pct/test.p.xref").exists()); assertTrue(new File(BASEDIR + "test40/build2/.pct/test.p.xref").exists()); } @Test(groups = {"v10"}) public void test42() { configureProject(BASEDIR + "test42/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test42/build/test.r"); File f2 = new File(BASEDIR + "test42/build2/test.r"); long mod1 = f1.lastModified(); long mod2 = f2.lastModified(); executeTarget("test2"); assertTrue(f1.lastModified() > mod1); assertTrue(f2.lastModified() > mod2); } @Test(groups = {"v10"}) public void test43() { configureProject(BASEDIR + "test43/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test43/build/test.r"); File f2 = new File(BASEDIR + "test43/build2/test.r"); long mod1 = f1.lastModified(); long mod2 = f2.lastModified(); assertFalse(new File(BASEDIR + "test43/build/.pct/test.p.xref").exists()); assertFalse(new File(BASEDIR + "test43/build/.pct/test.p.inc").exists()); assertFalse(new File(BASEDIR + "test43/build/.pct/test.p.crc").exists()); assertFalse(new File(BASEDIR + "test43/build/.dbg/test.p").exists()); assertTrue(new File(BASEDIR + "test43/build2/.dbg/test.p").exists()); assertTrue(new File(BASEDIR + "test43/build2/.pct/test.p.preprocess").exists()); executeTarget("test2"); assertTrue(f1.lastModified() > mod1); assertTrue(f2.lastModified() > mod2); } @Test(groups = {"v10"}) public void test45() { configureProject(BASEDIR + "test45/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test45/build/test.r"); File f2 = new File(BASEDIR + "test45/build/.pct/test.p"); assertTrue(f1.exists()); assertTrue(f2.exists()); assertTrue(f2.length() > 650); } @Test(groups = {"v10"}) public void test46() { configureProject(BASEDIR + "test46/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test46/build/test.r"); File f2 = new File(BASEDIR + "test46/build/.pct/test.p"); File f3 = new File(BASEDIR + "test46/build2/test.r"); File f4 = new File(BASEDIR + "test46/build2/.pct/test.p"); assertTrue(f1.exists()); assertTrue(f2.exists()); assertTrue(f3.exists()); assertTrue(f4.exists()); try { // Preprocessed source code removes many lines of unreachable code assertTrue(Files.readLines(f2, Charsets.UTF_8).size() + 10 < Files .readLines(f4, Charsets.UTF_8).size()); } catch (IOException caught) { Assert.fail("Unable to open file", caught); } } @Test(groups = {"v10"}) public void test47() { configureProject(BASEDIR + "test47/build.xml"); executeTarget("test1"); File f1 = new File(BASEDIR + "test47/build/dir1/test.r"); assertTrue(f1.exists()); long mod1 = f1.lastModified(); executeTarget("test2"); assertTrue(f1.lastModified() > mod1); } @Test(groups = {"v10"}) public void test48() { configureProject(BASEDIR + "test48/build.xml"); executeTarget("test1"); File f1 = new File(BASEDIR + "test48/build/test.r"); assertTrue(f1.exists()); long mod1 = f1.lastModified(); executeTarget("test2"); assertTrue(f1.lastModified() > mod1); } @Test(groups = {"v10"}) public void test49() { configureProject(BASEDIR + "test49/build.xml"); executeTarget("test1"); File warns = new File(BASEDIR + "test49/build/.pct/test.p.warnings"); assertTrue(warns.exists()); assertTrue(warns.length() > 0); } @Test(groups = {"v10"}) public void test50() { configureProject(BASEDIR + "test50/build.xml"); executeTarget("test1"); File rcode = new File(BASEDIR + "test50/build/test.r"); assertTrue(rcode.exists()); assertTrue(rcode.length() > 0); } @Test(groups = {"v10"}) public void test51() { configureProject(BASEDIR + "test51/build.xml"); executeTarget("test1"); /* compile all programms */ File f1 = new File(BASEDIR + "test51/build/test.r"); assertTrue(f1.exists()); long mod1 = f1.lastModified(); File f2 = new File(BASEDIR + "test51/build/test2.r"); assertTrue(f2.exists()); long mod2 = f2.lastModified(); executeTarget("test2"); /* nothing should compile */ File f3 = new File(BASEDIR + "test51/build/test.r"); assertTrue(f3.exists()); assertFalse(f3.lastModified() > mod1); mod1 = f1.lastModified(); File f4 = new File(BASEDIR + "test51/build/test2.r"); assertTrue(f4.exists()); assertFalse(f4.lastModified() > mod2); executeTarget("test3"); /* all programms should be compiled */ File f5 = new File(BASEDIR + "test51/build/test.r"); long mod5 = f5.lastModified(); assertTrue(f5.exists()); assertTrue(mod5 > mod1); File f6 = new File(BASEDIR + "test51/build/test2.r"); long mod6 = f6.lastModified(); assertTrue(f6.exists()); assertTrue(mod6 > mod2); executeTarget("test4"); /* all programms should be compiled */ File f7 = new File(BASEDIR + "test51/build/test.r"); assertTrue(f7.exists()); assertTrue(f7.lastModified() > mod5); File f8 = new File(BASEDIR + "test51/build/test2.r"); assertTrue(f8.exists()); assertTrue(f8.lastModified() > mod6); } @Test(groups = {"v11"}) public void test52() { // Only work with 11.7+ try { DLCVersion version = DLCVersion.getObject(new File(System.getProperty("DLC"))); if ((version.getMajorVersion() == 11) && (version.getMinorVersion() <= 6)) return; } catch (IOException caught) { return; } catch (InvalidRCodeException caught) { return; } configureProject(BASEDIR + "test52/build.xml"); executeTarget("test1"); File f1 = new File(BASEDIR + "test52/build1/test.r"); assertTrue(f1.exists()); executeTarget("test2"); File f2 = new File(BASEDIR + "test52/build2/test.r"); assertTrue(f2.exists()); File f3 = new File(BASEDIR + "test52/build2/.pct/test.p.warnings"); assertTrue(f3.exists()); } @Test(groups = {"v11"}) public void test53() { // Only work with 11.7+ try { DLCVersion version = DLCVersion.getObject(new File(System.getProperty("DLC"))); if ((version.getMajorVersion() == 11) && (version.getMinorVersion() <= 6)) return; } catch (IOException caught) { return; } catch (InvalidRCodeException caught) { return; } configureProject(BASEDIR + "test53/build.xml"); executeTarget("db"); executeTarget("test1"); File f1 = new File(BASEDIR + "test53/build1/test.r"); assertTrue(f1.exists()); executeTarget("test2"); File f2 = new File(BASEDIR + "test53/build2/test.r"); assertTrue(f2.exists()); File f3 = new File(BASEDIR + "test53/build2/.pct/test.p.warnings"); assertTrue(f3.exists()); } @Test(groups = {"v11"}) public void test54() { // Only work with 11.7+ try { DLCVersion version = DLCVersion.getObject(new File(System.getProperty("DLC"))); if ((version.getMajorVersion() == 11) && (version.getMinorVersion() <= 6)) return; } catch (IOException caught) { return; } catch (InvalidRCodeException caught) { return; } configureProject(BASEDIR + "test54/build.xml"); executeTarget("db"); executeTarget("test1"); File f1 = new File(BASEDIR + "test54/build1/test.r"); assertTrue(f1.exists()); executeTarget("test2"); File f2 = new File(BASEDIR + "test54/build2/test.r"); assertTrue(f2.exists()); File f3 = new File(BASEDIR + "test54/build2/.pct/test.p.warnings"); assertTrue(f3.exists()); } @Test(groups = {"v10"}) public void test55() { configureProject(BASEDIR + "test55/build.xml"); executeTarget("test1"); assertTrue(new File(BASEDIR + "test55/build1/test.r").exists()); assertTrue(new File(BASEDIR + "test55/build1/.pct/test.p.inc").exists()); executeTarget("test2"); assertFalse(new File(BASEDIR + "test55/build2/.pct").exists()); assertTrue(new File(BASEDIR + "test55/xref2/test.p.inc").exists()); executeTarget("test3"); assertFalse(new File(BASEDIR + "test55/build3/.pct").exists()); assertTrue(new File(BASEDIR + "test55/xref3/test.p.inc").exists()); assertTrue(new File(BASEDIR + "test55/build3/test.r").exists()); assertTrue(new File(BASEDIR + "test55/build3/test2.r").exists()); executeTarget("test4"); assertTrue(new File(BASEDIR + "test55/src/test.p").exists()); assertTrue(new File(BASEDIR + "test55/src/subdir/test2.p").exists()); assertTrue(new File(BASEDIR + "test55/src/test.r").exists()); assertTrue(new File(BASEDIR + "test55/src/test2.r").exists()); } @Test(groups = {"v10"}) public void test56() { configureProject(BASEDIR + "test56/build.xml"); executeTarget("test"); assertTrue(new File(BASEDIR + "test56/build1/build2/build3/test.r").exists()); } @Test(groups = {"v10"}) public void test57() { configureProject(BASEDIR + "test57/build.xml"); executeTarget("test"); assertTrue(new File(BASEDIR + "test57/build/test.r").exists()); } @Test(groups = {"v10"}) public void test58() { configureProject(BASEDIR + "test58/build.xml"); executeTarget("db"); executeTarget("build"); assertTrue(new File(BASEDIR + "test58/build1/file1.r").exists()); assertTrue(new File(BASEDIR + "test58/build1/dir1/file2.r").exists()); assertTrue(new File(BASEDIR + "test58/build1/dir1/file3.r").exists()); expectLog("test-fr-1", new String[] { "FR1-FR1", "7", "FR2-FR2", "7"}); expectLog("test-de-1", new String[] { "DE1-DE1", "7", "DE2-DE2", "7"}); expectLog("test-fr-2", new String[] { "FR1-FR1-FR1", "14", "FR2-FR2-FR2", "14"}); expectLog("test-de-2", new String[] { "DE1-DE1-DE1", "14", "DE2-DE2-DE2", "14"}); } @Test(groups = {"v10"}) public void test59() { configureProject(BASEDIR + "test59/build.xml"); executeTarget("test"); File warns1 = new File(BASEDIR + "test59/build1/.pct/test.p.warnings"); assertFalse(warns1.exists()); File warns2 = new File(BASEDIR + "test59/build2/.pct/test.p.warnings"); assertTrue(warns2.exists()); assertTrue(warns2.length() > 0); } @Test(groups = {"v10"}) public void test60() { configureProject(BASEDIR + "test60/build.xml"); executeTarget("test"); File warns = new File(BASEDIR + "test60/build/.pct/test.p.warnings"); assertTrue(warns.exists()); assertTrue(warns.length() > 0); executeTarget("test2"); assertFalse(warns.exists()); } @Test(groups = {"v10"}) public void test61() { configureProject(BASEDIR + "test61/build.xml"); expectBuildException("test", "Expected..."); File xref = new File(BASEDIR + "test61/build/.pct/test.p.xref"); assertFalse(xref.exists()); } @Test(groups = {"v11"}) public void test62() { // Same as test60 but with -swl. configureProject(BASEDIR + "test62/build.xml"); executeTarget("test"); File warns1 = new File(BASEDIR + "test62/build1/.pct/test.p.warnings"); assertTrue(warns1.exists()); assertTrue(warns1.length() > 0); File warns2 = new File(BASEDIR + "test62/build2/.pct/test.p.warnings"); assertTrue(warns2.exists()); assertTrue(warns2.length() > 0); assertTrue(warns2.length() < warns1.length()); File warns3 = new File(BASEDIR + "test62/build3/.pct/test.p.warnings"); assertTrue(warns3.exists()); assertEquals(warns3.length(), 0); } @Test(groups = {"v10"}) public void test63() { configureProject(BASEDIR + "test63/build.xml"); List<String> rexp = new ArrayList<>(); rexp.add("PCTCompile - Progress Code Compiler"); rexp.add("Error compiling file 'src/dir1/test1.p' \\.\\.\\."); rexp.add(" \\.\\.\\. in main file at line 3.*"); expectLogRegexp("test1", rexp, false); rexp.clear(); rexp.add("PCTCompile - Progress Code Compiler"); rexp.add("Error compiling file 'src/dir1/test2.p' \\.\\.\\."); rexp.add(" \\.\\.\\. in file 'src/dir1/test2.i' at line 3.*"); expectLogRegexp("test2", rexp, false); rexp.clear(); rexp.add("PCTCompile - Progress Code Compiler"); rexp.add("Error compiling file 'src/dir1/test3.p' \\.\\.\\."); rexp.add(" \\.\\.\\. in file 'src/dir1/test2.i' at line 3.*"); rexp.add(".*"); rexp.add(".*"); rexp.add(".*"); rexp.add(".*"); rexp.add(" \\.\\.\\. in main file at line 4.*"); expectLogRegexp("test3", rexp, false); rexp.clear(); rexp.add("PCTCompile - Progress Code Compiler"); rexp.add("Error compiling file 'src/dir1/test4.p' \\.\\.\\."); rexp.add(" \\.\\.\\. in file 'src/rssw/pct/TestClass.cls' at line 2.*"); rexp.add(".*"); rexp.add(".*"); rexp.add(".*"); rexp.add(".*"); rexp.add(" \\.\\.\\. in main file at line 2.*"); expectLogRegexp("test4", rexp, false); rexp.clear(); rexp.add("PCTCompile - Progress Code Compiler"); rexp.add("Error compiling file 'rssw/pct/TestClass2.cls' \\.\\.\\."); rexp.add(" \\.\\.\\. in main file at line 2.*"); expectLogRegexp("test5", rexp, false); } @Test(groups = {"v10"}) public void test64() { // Simplified version of test58 configureProject(BASEDIR + "test64/build.xml"); executeTarget("init"); executeTarget("build"); assertTrue(new File(BASEDIR + "test64/build1/file1.r").exists()); assertTrue(new File(BASEDIR + "test64/build2/file1.r").exists()); assertTrue(new File(BASEDIR + "test64/build1/.dbg/file1.p").exists()); assertTrue(new File(BASEDIR + "test64/build2/.dbg/file1.p").exists()); expectLog("test-fr-1", new String[] { "FR1-FR1", "7", "FR2-FR2", "7"}); expectLog("test-fr-2", new String[] { "FR1-FR1", "7", "FR2-FR2", "7"}); } @Test(groups = {"v10"}) public void test65() { // Test without destDir configureProject(BASEDIR + "test65/build.xml"); executeTarget("build_a"); executeTarget("build_b"); executeTarget("build_c"); assertTrue(new File(BASEDIR + "test65/a/src/a/a.r").exists()); assertTrue(new File(BASEDIR + "test65/b/src/b/b.r").exists()); assertTrue(new File(BASEDIR + "test65/c/src/c/c.r").exists()); assertFalse(new File(BASEDIR + "test65/b/src/a/a.r").exists()); assertFalse(new File(BASEDIR + "test65/c/src/a/a.r").exists()); assertFalse(new File(BASEDIR + "test65/c/src/b/b.r").exists()); } @Test(groups = {"v10", "win"}) public void test66() throws InvalidRCodeException, IOException { configureProject(BASEDIR + "test66/build.xml"); executeTarget("test"); assertTrue(new File(BASEDIR + "test66/build/v9.r").exists()); assertTrue(new File(BASEDIR + "test66/build-v6/v9.r").exists()); assertTrue(new File(BASEDIR + "test66/build-v6underline/v9.r").exists()); assertTrue(new File(BASEDIR + "test66/build-v6revvideo/v9.r").exists()); RCodeInfo rci0 = new RCodeInfo(new File(BASEDIR + "test66/build/v9.r")); RCodeInfo rci1 = new RCodeInfo(new File(BASEDIR + "test66/build/v6.r")); RCodeInfo rci2 = new RCodeInfo(new File(BASEDIR + "test66/build-v6/v9.r")); assertEquals(rci1.getRCodeSize(), rci2.getRCodeSize()); RCodeInfo rci3 = new RCodeInfo(new File(BASEDIR + "test66/build/ul.r")); RCodeInfo rci4 = new RCodeInfo(new File(BASEDIR + "test66/build-v6underline/v9.r")); assertEquals(rci3.getRCodeSize(), rci4.getRCodeSize()); RCodeInfo rci5 = new RCodeInfo(new File(BASEDIR + "test66/build/rv.r")); RCodeInfo rci6 = new RCodeInfo(new File(BASEDIR + "test66/build-v6revvideo/v9.r")); assertEquals(rci5.getRCodeSize(), rci6.getRCodeSize()); assertNotEquals(rci0.getRCodeSize(), rci1.getRCodeSize()); assertNotEquals(rci1.getRCodeSize(), rci3.getRCodeSize()); assertNotEquals(rci1.getRCodeSize(), rci5.getRCodeSize()); } @Test(groups = {"v10"}) public void test67() { configureProject(BASEDIR + "test67/build.xml"); executeTarget("test"); assertTrue(new File(BASEDIR + "test67/build-interface/rssw/pct/ITest.r").exists()); assertTrue(new File(BASEDIR + "test67/build-impl/rssw/pct/TestImpl.r").exists()); assertFalse(new File(BASEDIR + "test67/build-impl/rssw/pct/ITest.r").exists()); } @Test(groups = {"v10"}) public void test68() { configureProject(BASEDIR + "test68/build.xml"); executeTarget("test"); assertTrue(new File(BASEDIR + "test68/src1/rssw/pct/ITest.r").exists()); assertTrue(new File(BASEDIR + "test68/build-impl/rssw/pct/TestImpl.r").exists()); // This file shouldn't be there, and is incorrectly created by the compiler // assertFalse(new File(BASEDIR + "test68/build-impl/rssw/pct/ITest.r").exists()); } @Test(groups = {"v10"}) public void test69() { configureProject(BASEDIR + "test69/build.xml"); executeTarget("init"); executeTarget("test1"); executeTarget("test2"); assertTrue(new File(BASEDIR + "test69/build/test1.r").exists()); assertTrue(new File(BASEDIR + "test69/build/test2.r").exists()); assertTrue(new File(BASEDIR + "test69/build/.dbg/test2.p").exists()); } @Test(groups = {"v10"}) public void test70() { configureProject(BASEDIR + "test70/build.xml"); executeTarget("test"); // Extension is .p, not .r... assertTrue(new File(BASEDIR + "test70/build/test1.p").exists()); assertTrue(new File(BASEDIR + "test70/build/test2.p").exists()); assertFalse(new File(BASEDIR + "test70/build/subdir/test2.p").exists()); } @Test(groups = {"v10"}) public void test71() { configureProject(BASEDIR + "test71/build.xml"); executeTarget("test"); assertTrue(new File(BASEDIR + "test71/build/test1.r").exists()); assertTrue(new File(BASEDIR + "test71/build/.pct/test1.p.xref").exists()); } @Test(groups = {"v10"}) public void test72() { configureProject(BASEDIR + "test72/build.xml"); executeTarget("db"); // STOP condition raised by warning 4516 has to be trapped executeTarget("build"); } // ResultProperty is meaningless in multi-threaded builds @Test(enabled=false, groups = {"v10"}) public void test73() { configureProject(BASEDIR + "test73/build.xml"); executeTarget("test1"); assertPropertyEquals("test73Result1", "10"); executeTarget("test2"); assertPropertyEquals("test73Result2", "0"); } @Test(groups = {"v10"}) public void test74() { configureProject(BASEDIR + "test74/build.xml"); executeTarget("init"); executeTarget("test"); assertTrue(new File(BASEDIR + "test74/build/test.r").exists()); } @Test(groups = {"v10"}) public void test75() { configureProject(BASEDIR + "test75/build.xml"); executeTarget("test"); File f = new File(BASEDIR + "test75/build/test.r"); assertTrue(f.exists()); } @Test(groups = {"v11"}) public void test76() { // Only work with 11.3+ try { DLCVersion version = DLCVersion.getObject(new File(System.getProperty("DLC"))); if ((version.getMajorVersion() == 11) && (version.getMinorVersion() <= 2)) return; } catch (IOException e) { return; } catch (InvalidRCodeException e) { return; } configureProject(BASEDIR + "test76/build.xml"); executeTarget("compile"); expectLog("testInitialize", "Initialize#pct/pctBgCompile.p"); expectLog("testBeforeCompile", "Before Compile#pct/pctBgCompile.p#test.p#src"); expectLog("testAfterCompile", "After Compile#pct/pctBgCompile.p#test.p#src"); File f = new File(BASEDIR + "test76/build/test.r"); assertTrue(f.exists()); } @Test(groups = {"v11"}) public void test77() { // Only work with 11.3+ try { DLCVersion version = DLCVersion.getObject(new File(System.getProperty("DLC"))); if ((version.getMajorVersion() == 11) && (version.getMinorVersion() <= 2)) return; } catch (IOException e) { return; } catch (InvalidRCodeException e) { return; } configureProject(BASEDIR + "test77/build.xml"); executeTarget("compile"); File f1 = new File(BASEDIR + "test77/build/test01.r"); assertTrue(f1.exists()); File f2 = new File(BASEDIR + "test77/build/test02.r"); assertTrue(f2.exists()); File f3 = new File(BASEDIR + "test77/build/excl01.r"); assertFalse(f3.exists()); File f4 = new File(BASEDIR + "test77/build/excl02.r"); assertFalse(f4.exists()); } @Test(groups = {"v10"}) public void test78() { char ff = (char) 12; configureProject(BASEDIR + "test78/build.xml"); executeTarget("compile"); File listing = new File(BASEDIR + "test78/build/.pct/testPage.p"); assertTrue(listing.exists(), "Unable to find listing file"); try { List<String> lines = Files.readLines(listing, Charset.defaultCharset()); // Test the ASCII code at the defined PAGE-SIZE - 1 (zero based). assertTrue(lines.size() > 10 && lines.get(10).contains(String.valueOf(ff))); // Test the length of the first line containing code. assertTrue(lines.get(4).length() == 90); } catch (IOException e) { Assert.fail("Unable to read file", e); } } @Test(groups = {"v10"}) public void test79() { // No test case as 'outputType' attribute is not implemented in PCTCompileExt } @Test(groups = {"v10"}) public void test101() { configureProject(BASEDIR + "test101/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test101/build/test1.p"); assertTrue(f1.exists()); File f2 = new File(BASEDIR + "test101/build/test2.p"); assertTrue(f2.exists()); } @Test(groups = {"v10"}) public void test102() { configureProject(BASEDIR + "test102/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test102/build/testrenamed.r"); File f2 = new File(BASEDIR + "test102/build/test2renamed.r"); File f3 = new File(BASEDIR + "test102/build/triggers/trigger.r"); assertTrue(f1.exists()); assertTrue(f2.exists()); assertTrue(f3.exists()); long l1 = f1.lastModified(); long l2 = f2.lastModified(); long l3 = f3.lastModified(); executeTarget("test2"); assertEquals(f1.lastModified(), l1); assertEquals(f2.lastModified(), l2); assertEquals(f3.lastModified(), l3); } @Test(groups = {"v10"}) public void test103() throws IOException { File inputDir = new File(BASEDIR + "test103/src"); File subDir1 = new File(inputDir, "dir1"); File subDir2 = new File(subDir1, "dir2"); subDir2.mkdirs(); File srcFile = new File(BASEDIR + "test103/query-tester.w"); for (int ii = 0; ii < 10; ii++) { for (int jj = 0; jj < 10; jj++) { Files.copy(srcFile, new File(subDir2, "test" + ii + jj + ".p")); } } configureProject(BASEDIR + "test103/build.xml"); executeTarget("test"); File f = new File(BASEDIR + "test103/build/dir1/dir2/test00.r"); assertTrue(f.exists()); f = new File(BASEDIR + "test103/build/dir1/dir2/test99.r"); assertTrue(f.exists()); } @Test(groups = {"v10"}) public void test104() throws IOException { configureProject(BASEDIR + "test104/build.xml"); executeTarget("base"); expectBuildException("test1", "Invalid alias"); executeTarget("test2"); executeTarget("test3"); executeTarget("test4"); File f1 = new File(BASEDIR + "test104/build/proc.r"); File f2 = new File(BASEDIR + "test104/build/proc2.r"); File f3 = new File(BASEDIR + "test104/build/proc3.r"); assertTrue(f1.exists()); assertTrue(f2.exists()); assertTrue(f3.exists()); } @Test(groups = {"v10"}) public void test105() throws IOException { configureProject(BASEDIR + "test105/build.xml"); executeTarget("base"); executeTarget("test1"); expectBuildException("test2", "No DB connection, should throw BuildException"); File f1 = new File(BASEDIR + "test105/build/test.r"); File f2 = new File(BASEDIR + "test105/build2/test.r"); assertTrue(f1.exists()); assertFalse(f2.exists()); } @Test(groups = {"v10"}) public void test106() throws IOException { configureProject(BASEDIR + "test106/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test106/profiler"); // 2 profiler files generated assertEquals(f1.list().length, 2); } @Test(groups = {"v10"}) public void test107() throws IOException { configureProject(BASEDIR + "test107/build.xml"); executeTarget("test"); File f1 = new File(BASEDIR + "test107/build/test.r"); File f2 = new File(BASEDIR + "test107/build/test2.r"); assertTrue(f1.exists()); assertTrue(f2.exists()); } }
package uo270318.mp.tareaS9.dome.model; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import uo270318.mp.tareaS10.dome.exceptions.RepeatedElementException; public class CdTest { private Cd cd; @Before public void setUp() throws Exception { cd = new Cd("title1", "artist1", 6, 30, false); } @Test public void testCd() { Cd cd2 = new Cd("Come Together", "Beatles", 4, 70, false); assertEquals("Come Together", cd2.getTitle()); assertEquals("Beatles", cd2.getArtist()); assertEquals(70, cd2.getPlayingTime()); assertEquals(4, cd2.getNumberOfTracks()); assertEquals(false, cd2.getOwn()); assertEquals("", cd2.getComment()); } @Test public void testSetTitle() { // Titulo correcto cd.setTitle("newTitle"); assertEquals("newTitle", cd.getTitle()); // Titulo incorrecto (null) try { cd = new Cd(null, "Beatles", 4, 70, false); fail("Se esperaba un error de cadena incorrecta"); } catch (IllegalArgumentException iae) { assertEquals("La cadena es incorrecta", iae.getMessage()); } // Titulo incorrecto (vacio) try { cd = new Cd(" ", "Beatles", 4, 70, false); fail("Se esperaba un error de cadena incorrecta"); } catch (IllegalArgumentException iae) { assertEquals("La cadena es incorrecta", iae.getMessage()); } } @Test public void testSetArtist() { // Artista correcto cd.setArtist("newArtist"); assertEquals("newArtist", cd.getArtist()); // Artista incorrecto (null) try { cd = new Cd("Come Together", null, 4, 70, false); fail("Se esperaba un error de cadena incorrecta"); } catch (IllegalArgumentException iae) { assertEquals("La cadena es incorrecta", iae.getMessage()); } // Artista incorrecto (vacio) try { cd = new Cd("Come Together", " ", 4, 70, false); fail("Se esperaba un error de cadena incorrecta"); } catch (IllegalArgumentException iae) { assertEquals("La cadena es incorrecta", iae.getMessage()); } } @Test public void testSetNumberOfTracks() { // Numero de pistas correcto cd.setNumberOfTracks(10); assertEquals(10, cd.getNumberOfTracks()); // Numero de pistas incorrecto cd = new Cd("Come Together", "Beatles", -9, 70, false); assertEquals(0, cd.getNumberOfTracks()); } @Test public void testSetPlayingTime() { // Tiempo correcto cd.setPlayingTime(90); assertEquals(90, cd.getPlayingTime()); // Tiempo incorrecto cd = new Cd("Come Together", "Beatles", 4, -6, false); assertEquals(0, cd.getPlayingTime()); } @Test public void testSetComment() { // Comentario correcto cd.setComment("comment"); assertEquals("comment", cd.getComment()); // Comentario incorrecto (null) try { cd.setComment(null); fail("Se esperaba un error de cadena incorrecta"); } catch (IllegalArgumentException iae) { assertEquals("La cadena es incorrecta", iae.getMessage()); } } @Test public void testSetOwn() { // Pertenece cd.setOwn(true); assertTrue(cd.getOwn()); // No pertenece cd.setOwn(false); assertFalse(cd.getOwn()); } @Test public void setBasePrice() { // Precio valido cd.setBasePrice(9.99); assertEquals(9.99, cd.getBasePrice(), 0.1); // Precio invalido try { cd.setBasePrice(200000.00); fail("Se esperaba un error de cadena incorrecta"); } catch (IllegalArgumentException iae) { assertEquals("El precio debe estar dentro del rango permitido", iae.getMessage()); } try { cd.setBasePrice(-200.00); fail("Se esperaba un error de cadena incorrecta"); } catch (IllegalArgumentException iae) { assertEquals("El precio debe estar dentro del rango permitido", iae.getMessage()); } } @Test public void testSetAvailable() { // Disponible para prestar cd.setAvailable(true); assertTrue(cd.getAvailable()); // No pertenece cd.setAvailable(false); assertFalse(cd.getAvailable()); } @Test public void testToString() { assertEquals("CD: title1" + "\nYou do not own it" + "\nPrice: 0.0" + "\nComment: " + "\nPlaying time: 30 mins." + "\nArtist: artist1" + "\nTracks: 6", cd.toString()); } @Test public void testSearch() throws RepeatedElementException { Database db = new Database(); db.add(new Cd("title", "artist", 3, 18, false)); db.add(new Cd("title2", "artist2", 5, 17, false)); db.add(cd); // Encuentra al item assertEquals(cd, db.search(cd)); // No encuentra al item assertEquals(null, db.search(new Cd("title3", "artist2", 5, 57, false))); } @Test public void testIsAvailableItem() { //Disponible cd.setOwn(true); cd.setAvailable(true); assertTrue(cd.isAvailableItem()); //No disponible cd.setOwn(false); assertFalse(cd.isAvailableItem()); cd.setOwn(true); cd.setAvailable(false); assertFalse(cd.isAvailableItem()); } }
package com.idogs.okhttpdemo.okhttp.listener; /** * 业务层处理 */ public interface DisposeDataListener { /** * 请求成功回调事件处理 */ public void onSuccess(Object responseObj); /** * 请求失败回调事件处理 */ public void onFailure(Object reasonObj); }
package com.socialthingy.plusf.z80.operations; import com.socialthingy.plusf.z80.ContentionModel; import com.socialthingy.plusf.z80.Processor; public class OpRrca extends RotateOperation { public OpRrca(final Processor processor) { super(processor); } @Override public void execute(ContentionModel contentionModel, int initialPcValue, int irValue) { contentionModel.applyContention(initialPcValue, 4); final int value = accumulator.get(); final int lowBit = value & 0b1; accumulator.set(value >> 1 | (lowBit * 0b10000000)); setCarryAndNegateAfterRotate(lowBit); flagsRegister.setUndocumentedFlagsFromValue(accumulator.get()); } @Override public String toString() { return "rrca"; } }
package org.springframework.samples.petclinic.trainer; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.Repository; import org.springframework.transaction.annotation.Transactional; /* * @spacexjedi */ public interface AnimalRepository extends Repository<Animal, Integer> { /** * Retrieve all {@link AnimalType}s from the data store. * @return a Collection of {@link AnimalType}s. */ @Query("SELECT ptype FROM AnimalType ptype ORDER BY ptype.name") @Transactional(readOnly = true) List<AnimalType> findAnimalTypes(); /** * Retrieve a {@link Animal} from the data store by id. * @param id the id to search for * @return the {@link Animal} if found */ @Transactional(readOnly = true) Animal findById(Integer id); /** * Save a {@link Animal} to the data store, either inserting or updating it. * @param animal the {@link Animal} to save */ void save(Animal animal); }
package com.mercury.common.utils; import org.springframework.context.MessageSource; import com.mercury.common.utils.spring.SpringUtils; /** * 获取i18n资源文件 * * @author Sendy */ public class MessageUtils { /** * 根据消息键和参数 获取消息 委托给spring messageSource * * @param code 消息键 * @param args 参数 * @return */ public static String message(String code, Object... args) { MessageSource messageSource = SpringUtils.getBean(MessageSource.class); return messageSource.getMessage(code, args, null); } }
package org.pushingpixels.demo.substance.main.check.svg.filetypes; import java.awt.*; import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.*; import java.lang.ref.WeakReference; import java.util.Base64; import java.util.Stack; import javax.imageio.ImageIO; import javax.swing.SwingUtilities; import javax.swing.plaf.UIResource; import org.pushingpixels.neon.api.icon.NeonIcon; import org.pushingpixels.neon.api.icon.NeonIconUIResource; /** * This class has been automatically generated using <a * href="https://github.com/kirill-grouchnikov/radiance">Photon SVG transcoder</a>. */ public class ext_sass implements NeonIcon { private Shape shape = null; private GeneralPath generalPath = null; private Paint paint = null; private Stroke stroke = null; private Shape clip = null; private NeonIcon.ColorFilter colorFilter = null; private Stack<AffineTransform> transformsStack = new Stack<>(); private void _paint0(Graphics2D g,float origAlpha) { transformsStack.push(g.getTransform()); // g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(0.009999999776482582f, 0.0f, 0.0f, 0.009999999776482582f, 0.13999999687075615f, -0.0f)); // _0 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_0 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.0f, 1.0f); generalPath.lineTo(72.0f, 27.7f); generalPath.lineTo(72.0f, 99.0f); generalPath.lineTo(0.0f, 99.0f); generalPath.lineTo(0.0f, 1.0f); generalPath.lineTo(45.0f, 1.0f); generalPath.closePath(); shape = generalPath; paint = new LinearGradientPaint(new Point2D.Double(36.0, 97.0), new Point2D.Double(36.0, -1.0), new float[] {0.0f,0.139f,0.359f,0.617f,1.0f}, new Color[] {((colorFilter != null) ? colorFilter.filter(new Color(200, 212, 219, 255)) : new Color(200, 212, 219, 255)),((colorFilter != null) ? colorFilter.filter(new Color(216, 225, 230, 255)) : new Color(216, 225, 230, 255)),((colorFilter != null) ? colorFilter.filter(new Color(235, 240, 243, 255)) : new Color(235, 240, 243, 255)),((colorFilter != null) ? colorFilter.filter(new Color(249, 250, 251, 255)) : new Color(249, 250, 251, 255)),((colorFilter != null) ? colorFilter.filter(new Color(255, 255, 255, 255)) : new Color(255, 255, 255, 255))}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 2.0f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_1 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.0f, 1.0f); generalPath.lineTo(72.0f, 27.7f); generalPath.lineTo(72.0f, 99.0f); generalPath.lineTo(0.0f, 99.0f); generalPath.lineTo(0.0f, 1.0f); generalPath.lineTo(45.0f, 1.0f); generalPath.closePath(); shape = generalPath; paint = (colorFilter != null) ? colorFilter.filter(new Color(0, 0, 0, 0)) : new Color(0, 0, 0, 0); g.setPaint(paint); g.fill(shape); paint = (colorFilter != null) ? colorFilter.filter(new Color(113, 145, 161, 255)) : new Color(113, 145, 161, 255); stroke = new BasicStroke(2.0f,0,0,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.0f, 1.0f); generalPath.lineTo(72.0f, 27.7f); generalPath.lineTo(72.0f, 99.0f); generalPath.lineTo(0.0f, 99.0f); generalPath.lineTo(0.0f, 1.0f); generalPath.lineTo(45.0f, 1.0f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 0.95f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_2 g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_2_0 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(14.4f, 44.1f); generalPath.lineTo(14.4f, 39.199997f); generalPath.curveTo(15.4f, 39.1f, 16.199999f, 38.999996f, 16.699999f, 38.699997f); generalPath.curveTo(17.199999f, 38.499996f, 17.599998f, 37.999996f, 17.999998f, 37.499996f); generalPath.curveTo(18.399998f, 36.899998f, 18.599998f, 36.199997f, 18.799997f, 35.299995f); generalPath.curveTo(18.899998f, 34.599995f, 18.999998f, 33.499996f, 18.999998f, 31.899996f); generalPath.curveTo(18.999998f, 29.199995f, 19.099998f, 27.399996f, 19.399998f, 26.299995f); generalPath.curveTo(19.599998f, 25.299995f, 20.099998f, 24.399996f, 20.699997f, 23.799995f); generalPath.curveTo(21.299995f, 23.199995f, 22.299997f, 22.699995f, 23.499996f, 22.299995f); generalPath.curveTo(24.299995f, 22.099995f, 25.599997f, 21.899996f, 27.399996f, 21.899996f); generalPath.lineTo(28.499996f, 21.899996f); generalPath.lineTo(28.499996f, 26.799995f); generalPath.curveTo(26.999996f, 26.799995f, 25.999996f, 26.899996f, 25.599997f, 27.099995f); generalPath.curveTo(25.199997f, 27.299995f, 24.899996f, 27.499994f, 24.599997f, 27.899994f); generalPath.curveTo(24.399996f, 28.199993f, 24.299997f, 28.799994f, 24.299997f, 29.699993f); generalPath.curveTo(24.299997f, 30.599993f, 24.199997f, 32.199993f, 24.099997f, 34.599995f); generalPath.curveTo(23.999996f, 35.999996f, 23.899996f, 37.099995f, 23.599997f, 37.999996f); generalPath.curveTo(23.299997f, 38.799995f, 22.899996f, 39.499996f, 22.499996f, 40.099995f); generalPath.curveTo(22.099997f, 40.599995f, 21.399996f, 41.199993f, 20.499996f, 41.799995f); generalPath.curveTo(21.299995f, 42.299995f, 21.999996f, 42.799995f, 22.499996f, 43.399994f); generalPath.curveTo(22.999996f, 43.999992f, 23.399996f, 44.799995f, 23.699997f, 45.699993f); generalPath.curveTo(23.999998f, 46.59999f, 24.199997f, 47.79999f, 24.199997f, 49.29999f); generalPath.curveTo(24.299997f, 51.59999f, 24.299997f, 52.999992f, 24.299997f, 53.699993f); generalPath.curveTo(24.299997f, 54.599995f, 24.399998f, 55.199993f, 24.599997f, 55.599995f); generalPath.curveTo(24.799997f, 55.999996f, 25.199997f, 56.199993f, 25.599997f, 56.399994f); generalPath.curveTo(25.999996f, 56.599995f, 26.999996f, 56.699993f, 28.499996f, 56.699993f); generalPath.lineTo(28.499996f, 61.599995f); generalPath.lineTo(27.399996f, 61.599995f); generalPath.curveTo(25.599997f, 61.599995f, 24.099997f, 61.499996f, 23.199997f, 61.199993f); generalPath.curveTo(22.199997f, 60.899994f, 21.399998f, 60.399994f, 20.699997f, 59.699993f); generalPath.curveTo(19.999996f, 58.999992f, 19.599997f, 58.199993f, 19.299997f, 57.199993f); generalPath.curveTo(19.099997f, 56.199993f, 18.999998f, 54.599995f, 18.999998f, 52.399994f); generalPath.curveTo(18.999998f, 49.899994f, 18.899998f, 48.199993f, 18.699999f, 47.499992f); generalPath.curveTo(18.4f, 46.399994f, 17.9f, 45.59999f, 17.3f, 45.09999f); generalPath.curveTo(16.599998f, 44.499992f, 15.699999f, 44.09999f, 14.4f, 44.09999f); generalPath.closePath(); shape = generalPath; paint = new LinearGradientPaint(new Point2D.Double(21.450000762939453, 61.54999923706055), new Point2D.Double(21.450000762939453, 21.950000762939453), new float[] {0.0f,1.0f}, new Color[] {((colorFilter != null) ? colorFilter.filter(new Color(173, 204, 220, 255)) : new Color(173, 204, 220, 255)),((colorFilter != null) ? colorFilter.filter(new Color(76, 108, 123, 255)) : new Color(76, 108, 123, 255))}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_2_1 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(58.7f, 44.1f); generalPath.curveTo(57.7f, 44.199997f, 56.9f, 44.3f, 56.4f, 44.6f); generalPath.curveTo(55.9f, 44.8f, 55.5f, 45.3f, 55.100002f, 45.8f); generalPath.curveTo(54.7f, 46.399998f, 54.500004f, 47.1f, 54.300003f, 48.0f); generalPath.curveTo(54.200005f, 48.7f, 54.100002f, 49.8f, 54.100002f, 51.4f); generalPath.curveTo(54.100002f, 54.100002f, 54.000004f, 55.9f, 53.7f, 57.0f); generalPath.curveTo(53.5f, 58.1f, 53.0f, 58.9f, 52.4f, 59.5f); generalPath.curveTo(51.800003f, 60.1f, 50.800003f, 60.6f, 49.600002f, 61.0f); generalPath.curveTo(48.800003f, 61.2f, 47.500004f, 61.4f, 45.7f, 61.4f); generalPath.lineTo(44.600002f, 61.4f); generalPath.lineTo(44.600002f, 56.5f); generalPath.curveTo(46.100002f, 56.5f, 47.000004f, 56.4f, 47.500004f, 56.2f); generalPath.curveTo(48.000004f, 56.0f, 48.300003f, 55.7f, 48.500004f, 55.4f); generalPath.curveTo(48.700005f, 55.100002f, 48.800003f, 54.5f, 48.800003f, 53.600002f); generalPath.curveTo(48.800003f, 52.800003f, 48.9f, 51.2f, 49.000004f, 48.800003f); generalPath.curveTo(49.100002f, 47.4f, 49.300003f, 46.200005f, 49.600002f, 45.4f); generalPath.curveTo(49.9f, 44.5f, 50.300003f, 43.800003f, 50.800003f, 43.2f); generalPath.curveTo(51.300003f, 42.6f, 51.9f, 42.100002f, 52.700005f, 41.600002f); generalPath.curveTo(51.700005f, 40.9f, 50.900005f, 40.300003f, 50.500004f, 39.7f); generalPath.curveTo(49.900005f, 38.8f, 49.400005f, 37.600002f, 49.200005f, 36.3f); generalPath.curveTo(49.000004f, 35.3f, 48.900005f, 33.2f, 48.900005f, 30.0f); generalPath.curveTo(48.900005f, 29.0f, 48.800007f, 28.3f, 48.600006f, 27.9f); generalPath.curveTo(48.400005f, 27.6f, 48.100006f, 27.3f, 47.700005f, 27.1f); generalPath.curveTo(47.300003f, 26.9f, 46.300003f, 26.800001f, 44.700005f, 26.800001f); generalPath.lineTo(44.700005f, 22.0f); generalPath.lineTo(45.800003f, 22.0f); generalPath.curveTo(47.600002f, 22.0f, 49.100002f, 22.1f, 50.000004f, 22.4f); generalPath.curveTo(51.000004f, 22.699999f, 51.800003f, 23.199999f, 52.500004f, 23.9f); generalPath.curveTo(53.200005f, 24.6f, 53.600002f, 25.4f, 53.900005f, 26.4f); generalPath.curveTo(54.100006f, 27.4f, 54.300007f, 29.0f, 54.300007f, 31.2f); generalPath.curveTo(54.300007f, 33.7f, 54.400005f, 35.3f, 54.600006f, 36.100002f); generalPath.curveTo(54.900005f, 37.2f, 55.400005f, 38.000004f, 56.000008f, 38.4f); generalPath.curveTo(56.600006f, 38.9f, 57.600006f, 39.100002f, 58.800007f, 39.2f); generalPath.lineTo(58.70001f, 44.100002f); generalPath.closePath(); shape = generalPath; paint = new LinearGradientPaint(new Point2D.Double(51.70000076293945, 61.45000076293945), new Point2D.Double(51.70000076293945, 21.950000762939453), new float[] {0.0f,1.0f}, new Color[] {((colorFilter != null) ? colorFilter.filter(new Color(173, 204, 220, 255)) : new Color(173, 204, 220, 255)),((colorFilter != null) ? colorFilter.filter(new Color(76, 108, 123, 255)) : new Color(76, 108, 123, 255))}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_3 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.0f, 1.0f); generalPath.lineTo(72.0f, 27.7f); generalPath.lineTo(45.0f, 27.7f); generalPath.lineTo(45.0f, 1.0f); generalPath.closePath(); shape = generalPath; paint = new LinearGradientPaint(new Point2D.Double(45.0369987487793, 25.812999725341797), new Point2D.Double(58.5369987487793, 12.312999725341797), new float[] {0.0f,0.35f,0.532f,0.675f,0.799f,0.908f,1.0f}, new Color[] {((colorFilter != null) ? colorFilter.filter(new Color(255, 255, 255, 255)) : new Color(255, 255, 255, 255)),((colorFilter != null) ? colorFilter.filter(new Color(250, 251, 251, 255)) : new Color(250, 251, 251, 255)),((colorFilter != null) ? colorFilter.filter(new Color(237, 241, 244, 255)) : new Color(237, 241, 244, 255)),((colorFilter != null) ? colorFilter.filter(new Color(221, 229, 233, 255)) : new Color(221, 229, 233, 255)),((colorFilter != null) ? colorFilter.filter(new Color(199, 211, 218, 255)) : new Color(199, 211, 218, 255)),((colorFilter != null) ? colorFilter.filter(new Color(173, 189, 199, 255)) : new Color(173, 189, 199, 255)),((colorFilter != null) ? colorFilter.filter(new Color(146, 165, 176, 255)) : new Color(146, 165, 176, 255))}, MultipleGradientPaint.CycleMethod.NO_CYCLE, MultipleGradientPaint.ColorSpaceType.SRGB, new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 2.0f)); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_4 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.0f, 1.0f); generalPath.lineTo(72.0f, 27.7f); generalPath.lineTo(45.0f, 27.7f); generalPath.lineTo(45.0f, 1.0f); generalPath.closePath(); shape = generalPath; paint = (colorFilter != null) ? colorFilter.filter(new Color(0, 0, 0, 0)) : new Color(0, 0, 0, 0); g.setPaint(paint); g.fill(shape); paint = (colorFilter != null) ? colorFilter.filter(new Color(113, 145, 161, 255)) : new Color(113, 145, 161, 255); stroke = new BasicStroke(2.0f,0,2,4.0f,null,0.0f); if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(45.0f, 1.0f); generalPath.lineTo(72.0f, 27.7f); generalPath.lineTo(45.0f, 27.7f); generalPath.lineTo(45.0f, 1.0f); generalPath.closePath(); shape = generalPath; g.setPaint(paint); g.setStroke(stroke); g.draw(shape); g.setTransform(transformsStack.pop()); g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha)); transformsStack.push(g.getTransform()); g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f)); // _0_5 if (generalPath == null) { generalPath = new GeneralPath(); } else { generalPath.reset(); } generalPath.moveTo(5.7f, 86.2f); generalPath.lineTo(8.9f, 85.899994f); generalPath.curveTo(9.099999f, 86.99999f, 9.5f, 87.799995f, 10.099999f, 88.299995f); generalPath.curveTo(10.699999f, 88.799995f, 11.499999f, 89.1f, 12.5f, 89.1f); generalPath.curveTo(13.6f, 89.1f, 14.4f, 88.9f, 14.9f, 88.4f); generalPath.curveTo(15.4f, 87.9f, 15.7f, 87.4f, 15.7f, 86.8f); generalPath.curveTo(15.7f, 86.4f, 15.599999f, 86.100006f, 15.4f, 85.8f); generalPath.curveTo(15.2f, 85.5f, 14.799999f, 85.3f, 14.2f, 85.100006f); generalPath.curveTo(13.8f, 85.00001f, 12.9f, 84.700005f, 11.5f, 84.40001f); generalPath.curveTo(9.7f, 84.00001f, 8.5f, 83.40001f, 7.7f, 82.80001f); generalPath.curveTo(6.7f, 81.90001f, 6.2f, 80.80001f, 6.2f, 79.50001f); generalPath.curveTo(6.2f, 78.700005f, 6.3999996f, 77.90001f, 6.8999996f, 77.100006f); generalPath.curveTo(7.3999996f, 76.40001f, 8.099999f, 75.8f, 9.0f, 75.40001f); generalPath.curveTo(9.9f, 75.00001f, 11.0f, 74.80001f, 12.2f, 74.80001f); generalPath.curveTo(14.299999f, 74.80001f, 15.799999f, 75.30001f, 16.9f, 76.20001f); generalPath.curveTo(17.9f, 77.10001f, 18.5f, 78.30001f, 18.5f, 79.80001f); generalPath.lineTo(15.2f, 79.90001f); generalPath.curveTo(15.099999f, 79.100006f, 14.8f, 78.40001f, 14.3f, 78.100006f); generalPath.curveTo(13.8f, 77.700005f, 13.1f, 77.50001f, 12.200001f, 77.50001f); generalPath.curveTo(11.200001f, 77.50001f, 10.500001f, 77.700005f, 9.900001f, 78.100006f); generalPath.curveTo(9.500001f, 78.40001f, 9.400001f, 78.700005f, 9.400001f, 79.100006f); generalPath.curveTo(9.400001f, 79.50001f, 9.6f, 79.8f, 9.900001f, 80.100006f); generalPath.curveTo(10.3f, 80.50001f, 11.3f, 80.8f, 13.0f, 81.200005f); generalPath.curveTo(14.6f, 81.600006f, 15.8f, 82.00001f, 16.6f, 82.4f); generalPath.curveTo(17.4f, 82.8f, 18.0f, 83.4f, 18.4f, 84.1f); generalPath.curveTo(18.8f, 84.799995f, 19.1f, 85.7f, 19.1f, 86.7f); generalPath.curveTo(19.1f, 87.6f, 18.800001f, 88.5f, 18.300001f, 89.399994f); generalPath.curveTo(17.800001f, 90.2f, 17.000002f, 90.799995f, 16.1f, 91.2f); generalPath.curveTo(15.199999f, 91.6f, 13.900001f, 91.799995f, 12.5f, 91.799995f); generalPath.curveTo(10.4f, 91.799995f, 8.8f, 91.299995f, 7.7f, 90.399994f); generalPath.curveTo(6.5999994f, 89.49999f, 5.8999996f, 87.99999f, 5.7f, 86.2f); generalPath.closePath(); generalPath.moveTo(36.7f, 91.5f); generalPath.lineTo(33.100002f, 91.5f); generalPath.lineTo(31.700003f, 87.8f); generalPath.lineTo(25.100002f, 87.8f); generalPath.lineTo(23.700003f, 91.5f); generalPath.lineTo(20.200003f, 91.5f); generalPath.lineTo(26.6f, 75.0f); generalPath.lineTo(30.1f, 75.0f); generalPath.lineTo(36.7f, 91.5f); generalPath.closePath(); generalPath.moveTo(30.6f, 85.0f); generalPath.lineTo(28.300001f, 78.9f); generalPath.lineTo(26.1f, 85.0f); generalPath.lineTo(30.6f, 85.0f); generalPath.closePath(); generalPath.moveTo(37.6f, 86.2f); generalPath.lineTo(40.8f, 85.899994f); generalPath.curveTo(41.0f, 86.99999f, 41.399998f, 87.799995f, 42.0f, 88.299995f); generalPath.curveTo(42.600002f, 88.799995f, 43.4f, 89.1f, 44.4f, 89.1f); generalPath.curveTo(45.5f, 89.1f, 46.300003f, 88.9f, 46.800003f, 88.4f); generalPath.curveTo(47.300003f, 87.9f, 47.600002f, 87.4f, 47.600002f, 86.8f); generalPath.curveTo(47.600002f, 86.4f, 47.500004f, 86.100006f, 47.300003f, 85.8f); generalPath.curveTo(47.100002f, 85.5f, 46.700005f, 85.3f, 46.100002f, 85.100006f); generalPath.curveTo(45.7f, 85.00001f, 44.800003f, 84.700005f, 43.4f, 84.40001f); generalPath.curveTo(41.600002f, 84.00001f, 40.4f, 83.40001f, 39.600002f, 82.80001f); generalPath.curveTo(38.600002f, 81.90001f, 38.100002f, 80.80001f, 38.100002f, 79.50001f); generalPath.curveTo(38.100002f, 78.700005f, 38.300003f, 77.90001f, 38.800003f, 77.100006f); generalPath.curveTo(39.300003f, 76.40001f, 40.000004f, 75.8f, 40.9f, 75.40001f); generalPath.curveTo(41.800003f, 75.00001f, 42.9f, 74.80001f, 44.100002f, 74.80001f); generalPath.curveTo(46.2f, 74.80001f, 47.7f, 75.30001f, 48.800003f, 76.20001f); generalPath.curveTo(49.800003f, 77.10001f, 50.4f, 78.30001f, 50.4f, 79.80001f); generalPath.lineTo(47.100002f, 79.90001f); generalPath.curveTo(47.000004f, 79.100006f, 46.7f, 78.40001f, 46.2f, 78.100006f); generalPath.curveTo(45.7f, 77.700005f, 45.0f, 77.50001f, 44.100002f, 77.50001f); generalPath.curveTo(43.100002f, 77.50001f, 42.4f, 77.700005f, 41.800003f, 78.100006f); generalPath.curveTo(41.4f, 78.40001f, 41.300003f, 78.700005f, 41.300003f, 79.100006f); generalPath.curveTo(41.300003f, 79.50001f, 41.500004f, 79.8f, 41.800003f, 80.100006f); generalPath.curveTo(42.200005f, 80.50001f, 43.200005f, 80.8f, 44.9f, 81.200005f); generalPath.curveTo(46.5f, 81.600006f, 47.7f, 82.00001f, 48.5f, 82.4f); generalPath.curveTo(49.3f, 82.8f, 49.9f, 83.4f, 50.3f, 84.1f); generalPath.curveTo(50.7f, 84.799995f, 51.0f, 85.7f, 51.0f, 86.7f); generalPath.curveTo(51.0f, 87.6f, 50.7f, 88.5f, 50.2f, 89.399994f); generalPath.curveTo(49.7f, 90.2f, 48.9f, 90.799995f, 48.0f, 91.2f); generalPath.curveTo(47.0f, 91.6f, 45.8f, 91.799995f, 44.4f, 91.799995f); generalPath.curveTo(42.300003f, 91.799995f, 40.7f, 91.299995f, 39.600002f, 90.399994f); generalPath.curveTo(38.500004f, 89.399994f, 37.800003f, 87.99999f, 37.600002f, 86.2f); generalPath.closePath(); generalPath.moveTo(53.0f, 86.2f); generalPath.lineTo(56.2f, 85.899994f); generalPath.curveTo(56.4f, 86.99999f, 56.8f, 87.799995f, 57.4f, 88.299995f); generalPath.curveTo(58.000004f, 88.799995f, 58.800003f, 89.1f, 59.800003f, 89.1f); generalPath.curveTo(60.9f, 89.1f, 61.700005f, 88.9f, 62.200005f, 88.4f); generalPath.curveTo(62.700005f, 87.9f, 63.000004f, 87.4f, 63.000004f, 86.8f); generalPath.curveTo(63.000004f, 86.4f, 62.900005f, 86.100006f, 62.700005f, 85.8f); generalPath.curveTo(62.500004f, 85.5f, 62.100006f, 85.3f, 61.500004f, 85.100006f); generalPath.curveTo(61.100002f, 85.00001f, 60.200005f, 84.700005f, 58.800003f, 84.40001f); generalPath.curveTo(57.000004f, 84.00001f, 55.800003f, 83.40001f, 55.000004f, 82.80001f); generalPath.curveTo(54.000004f, 81.90001f, 53.500004f, 80.80001f, 53.500004f, 79.50001f); generalPath.curveTo(53.500004f, 78.700005f, 53.700005f, 77.90001f, 54.200005f, 77.100006f); generalPath.curveTo(54.700005f, 76.40001f, 55.400005f, 75.8f, 56.300003f, 75.40001f); generalPath.curveTo(57.200005f, 75.00001f, 58.300003f, 74.80001f, 59.500004f, 74.80001f); generalPath.curveTo(61.600002f, 74.80001f, 63.100002f, 75.30001f, 64.200005f, 76.20001f); generalPath.curveTo(65.200005f, 77.10001f, 65.8f, 78.30001f, 65.8f, 79.80001f); generalPath.lineTo(62.500004f, 79.90001f); generalPath.curveTo(62.400005f, 79.100006f, 62.100002f, 78.40001f, 61.600002f, 78.100006f); generalPath.curveTo(61.100002f, 77.700005f, 60.4f, 77.50001f, 59.500004f, 77.50001f); generalPath.curveTo(58.500004f, 77.50001f, 57.800003f, 77.700005f, 57.200005f, 78.100006f); generalPath.curveTo(56.800003f, 78.40001f, 56.700005f, 78.700005f, 56.700005f, 79.100006f); generalPath.curveTo(56.700005f, 79.50001f, 56.900005f, 79.8f, 57.200005f, 80.100006f); generalPath.curveTo(57.600006f, 80.50001f, 58.600006f, 80.8f, 60.300003f, 81.200005f); generalPath.curveTo(61.9f, 81.600006f, 63.100002f, 82.00001f, 63.9f, 82.4f); generalPath.curveTo(64.700005f, 82.8f, 65.3f, 83.4f, 65.700005f, 84.1f); generalPath.curveTo(66.100006f, 84.799995f, 66.4f, 85.7f, 66.4f, 86.7f); generalPath.curveTo(66.4f, 87.6f, 66.1f, 88.5f, 65.6f, 89.399994f); generalPath.curveTo(65.1f, 90.2f, 64.299995f, 90.799995f, 63.399998f, 91.2f); generalPath.curveTo(62.399998f, 91.6f, 61.199997f, 91.799995f, 59.8f, 91.799995f); generalPath.curveTo(57.7f, 91.799995f, 56.1f, 91.299995f, 55.0f, 90.399994f); generalPath.curveTo(53.8f, 89.399994f, 53.2f, 87.99999f, 53.0f, 86.2f); generalPath.closePath(); shape = generalPath; paint = (colorFilter != null) ? colorFilter.filter(new Color(76, 108, 123, 255)) : new Color(76, 108, 123, 255); g.setPaint(paint); g.fill(shape); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); g.setTransform(transformsStack.pop()); } @SuppressWarnings("unused") private void innerPaint(Graphics2D g) { float origAlpha = 1.0f; Composite origComposite = g.getComposite(); if (origComposite instanceof AlphaComposite) { AlphaComposite origAlphaComposite = (AlphaComposite)origComposite; if (origAlphaComposite.getRule() == AlphaComposite.SRC_OVER) { origAlpha = origAlphaComposite.getAlpha(); } } _paint0(g, origAlpha); shape = null; generalPath = null; paint = null; stroke = null; clip = null; transformsStack.clear(); } /** * Returns the X of the bounding box of the original SVG image. * * @return The X of the bounding box of the original SVG image. */ public static double getOrigX() { return 0.12999999523162842; } /** * Returns the Y of the bounding box of the original SVG image. * * @return The Y of the bounding box of the original SVG image. */ public static double getOrigY() { return 0.0; } /** * Returns the width of the bounding box of the original SVG image. * * @return The width of the bounding box of the original SVG image. */ public static double getOrigWidth() { return 0.7400000095367432; } /** * Returns the height of the bounding box of the original SVG image. * * @return The height of the bounding box of the original SVG image. */ public static double getOrigHeight() { return 1.0; } /** The current width of this icon. */ private int width; /** The current height of this icon. */ private int height; /** * Creates a new transcoded SVG image. This is marked as private to indicate that app * code should be using the {@link #of(int, int)} method to obtain a pre-configured instance. */ private ext_sass() { this.width = (int) getOrigWidth(); this.height = (int) getOrigHeight(); } @Override public int getIconHeight() { return height; } @Override public int getIconWidth() { return width; } @Override public synchronized void setDimension(Dimension newDimension) { this.width = newDimension.width; this.height = newDimension.height; } @Override public boolean supportsColorFilter() { return true; } @Override public void setColorFilter(ColorFilter colorFilter) { this.colorFilter = colorFilter; } @Override public synchronized void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2d = (Graphics2D) g.create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.translate(x, y); double coef1 = (double) this.width / getOrigWidth(); double coef2 = (double) this.height / getOrigHeight(); double coef = Math.min(coef1, coef2); g2d.clipRect(0, 0, this.width, this.height); g2d.scale(coef, coef); g2d.translate(-getOrigX(), -getOrigY()); if (coef1 != coef2) { if (coef1 < coef2) { int extraDy = (int) ((getOrigWidth() - getOrigHeight()) / 2.0); g2d.translate(0, extraDy); } else { int extraDx = (int) ((getOrigHeight() - getOrigWidth()) / 2.0); g2d.translate(extraDx, 0); } } Graphics2D g2ForInner = (Graphics2D) g2d.create(); innerPaint(g2ForInner); g2ForInner.dispose(); g2d.dispose(); } /** * Returns a new instance of this icon with specified dimensions. * * @param width Required width of the icon * @param height Required height of the icon * @return A new instance of this icon with specified dimensions. */ public static NeonIcon of(int width, int height) { ext_sass base = new ext_sass(); base.width = width; base.height = height; return base; } /** * Returns a new {@link UIResource} instance of this icon with specified dimensions. * * @param width Required width of the icon * @param height Required height of the icon * @return A new {@link UIResource} instance of this icon with specified dimensions. */ public static NeonIconUIResource uiResourceOf(int width, int height) { ext_sass base = new ext_sass(); base.width = width; base.height = height; return new NeonIconUIResource(base); } /** * Returns a factory that returns instances of this icon on demand. * * @return Factory that returns instances of this icon on demand. */ public static Factory factory() { return ext_sass::new; } }
package com; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HttpServletDemo extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; /*If we are using all the methods which are doGet,dopost and all and service method is there then it will override all hide * all methods and only print the service method outut * */ /*protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter pw = resp.getWriter(); pw.println("This is my HttpServle Page"); }*/ /*Default method in jsp form tag is get if we are using get then we hazve to use here doGet method if we are using post * method in form tag then definitely we have to use doPost in servlet */ /*protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter pw = resp.getWriter(); try { pw.println("Division is : "+(Integer.parseInt(req.getParameter("n1"))/Integer.parseInt(req.getParameter("n2")))); } catch (ArithmeticException e) { // TODO: handle exception pw.println("Error : "+e); } }*/ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter pw = resp.getWriter(); int a = Integer.parseInt(req.getParameter("n1")); int b = Integer.parseInt(req.getParameter("n2")); try { pw.println("Division is : "+(a/b)); } catch (ArithmeticException e) { // TODO: handle exception pw.println("Error : "+e); } } }
/* * 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.hyracks.dataflow.common.data.normalizers; import org.apache.hyracks.api.dataflow.value.INormalizedKeyComputer; import org.apache.hyracks.api.dataflow.value.INormalizedKeyComputerFactory; import org.apache.hyracks.api.dataflow.value.INormalizedKeyProperties; import org.apache.hyracks.dataflow.common.utils.NormalizedKeyUtils; import org.apache.hyracks.util.string.UTF8StringUtil; public class UTF8String64BitNormalizedKeyComputerFactory implements INormalizedKeyComputerFactory { private static final long serialVersionUID = 1L; public static final INormalizedKeyProperties PROPERTIES = new INormalizedKeyProperties() { private static final long serialVersionUID = 1L; @Override public int getNormalizedKeyLength() { return 2; } @Override public boolean isDecisive() { return false; } }; @Override public INormalizedKeyComputer createNormalizedKeyComputer() { return new INormalizedKeyComputer() { @Override public void normalize(byte[] bytes, int start, int length, int[] normalizedKeys, int keyStart) { NormalizedKeyUtils.putLongIntoNormalizedKeys(normalizedKeys, keyStart, normalize(bytes, start, length)); } @Override public long normalize(byte[] bytes, int start, int length) { return UTF8StringUtil.normalize64(bytes, start) ^ Long.MIN_VALUE; } @Override public INormalizedKeyProperties getNormalizedKeyProperties() { return PROPERTIES; } }; } @Override public INormalizedKeyProperties getNormalizedKeyProperties() { return PROPERTIES; } }
/* * Copyright 2016 Crown Copyright * * 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 stroom.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import stroom.util.date.DateUtil; import stroom.util.shared.BuildInfo; import javax.inject.Provider; import javax.inject.Singleton; import java.io.IOException; import java.util.Properties; @Singleton class BuildInfoProvider implements Provider<BuildInfo> { private static final String upDate = DateUtil.createNormalDateTimeString(); private static final Logger LOGGER = LoggerFactory.getLogger(BuildInfoProvider.class); private BuildInfo buildInfo; public BuildInfo get() { if (buildInfo == null) { Properties properties = new Properties(); try { properties.load( BuildInfoProvider.class.getClassLoader().getResourceAsStream("META-INF/stroom-util-build.properties")); } catch (final IOException e) { LOGGER.error("Unable to load stroom-util-build.properties!", e); } final String buildVersion = properties.getProperty("buildVersion"); final String buildDate = properties.getProperty("buildDate"); buildInfo = new BuildInfo(upDate, buildVersion, buildDate); } return buildInfo; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.guet.flexbox.el; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; public abstract class ELContext { private Locale locale; private Map<Class<?>, Object> map; private boolean resolved; private ImportHandler importHandler = null; private List<EvaluationListener> listeners = new ArrayList<>(); private Deque<Map<String,Object>> lambdaArguments = new LinkedList<>(); public ELContext() { this.resolved = false; } public void setPropertyResolved(boolean resolved) { this.resolved = resolved; } /** * Mark the given property as resolved and notify any interested listeners. * * @param base The base object on which the property was found * @param property The property that was resolved * * @since EL 3.0 */ public void setPropertyResolved(Object base, Object property) { setPropertyResolved(true); notifyPropertyResolved(base, property); } public boolean isPropertyResolved() { return this.resolved; } // Can't use Class<?> because API needs to match specification /** * Add an object to this EL context under the given key. * * @param key The key under which to store the object * @param contextObject The object to add * * @throws NullPointerException * If the supplied key or context is <code>null</code> */ public void putContext(@SuppressWarnings("rawtypes") Class key, Object contextObject) { Objects.requireNonNull(key); Objects.requireNonNull(contextObject); if (this.map == null) { this.map = new HashMap<>(); } this.map.put(key, contextObject); } // Can't use Class<?> because API needs to match specification /** * Obtain the context object for the given key. * * @param key The key of the required context object * * @return The value of the context object associated with the given key * * @throws NullPointerException * If the supplied key is <code>null</code> */ public Object getContext(@SuppressWarnings("rawtypes") Class key) { Objects.requireNonNull(key); if (this.map == null) { return null; } return this.map.get(key); } public abstract ELResolver getELResolver(); /** * Obtain the ImportHandler for this ELContext, creating one if necessary. * This method is not thread-safe. * * @return the ImportHandler for this ELContext. * * @since EL 3.0 */ public ImportHandler getImportHandler() { if (importHandler == null) { importHandler = new ImportHandler(); } return importHandler; } public abstract FunctionMapper getFunctionMapper(); public Locale getLocale() { return this.locale; } public void setLocale(Locale locale) { this.locale = locale; } public abstract VariableMapper getVariableMapper(); /** * Register an EvaluationListener with this ELContext. * * @param listener The EvaluationListener to register * * @since EL 3.0 */ public void addEvaluationListener(EvaluationListener listener) { listeners.add(listener); } /** * Obtain the list of registered EvaluationListeners. * * @return A list of the EvaluationListener registered with this ELContext * * @since EL 3.0 */ public List<EvaluationListener> getEvaluationListeners() { return listeners; } /** * Notify interested listeners that an expression will be evaluated. * * @param expression The expression that will be evaluated * * @since EL 3.0 */ public void notifyBeforeEvaluation(String expression) { for (EvaluationListener listener : listeners) { try { listener.beforeEvaluation(this, expression); } catch (Throwable t) { Util.handleThrowable(t); // Ignore - no option to log } } } /** * Notify interested listeners that an expression has been evaluated. * * @param expression The expression that was evaluated * * @since EL 3.0 */ public void notifyAfterEvaluation(String expression) { for (EvaluationListener listener : listeners) { try { listener.afterEvaluation(this, expression); } catch (Throwable t) { Util.handleThrowable(t); // Ignore - no option to log } } } /** * Notify interested listeners that a property has been resolved. * * @param base The object on which the property was resolved * @param property The property that was resolved * * @since EL 3.0 */ public void notifyPropertyResolved(Object base, Object property) { for (EvaluationListener listener : listeners) { try { listener.propertyResolved(this, base, property); } catch (Throwable t) { Util.handleThrowable(t); // Ignore - no option to log } } } /** * Determine if the specified name is recognised as the name of a lambda * argument. * * @param name The name of the lambda argument * * @return <code>true</code> if the name is recognised as the name of a * lambda argument, otherwise <code>false</code> * * @since EL 3.0 */ public boolean isLambdaArgument(String name) { for (Map<String,Object> arguments : lambdaArguments) { if (arguments.containsKey(name)) { return true; } } return false; } /** * Obtain the value of the lambda argument with the given name. * * @param name The name of the lambda argument * * @return The value of the specified argument * * @since EL 3.0 */ public Object getLambdaArgument(String name) { for (Map<String,Object> arguments : lambdaArguments) { Object result = arguments.get(name); if (result != null) { return result; } } return null; } /** * Called when starting to evaluate a lambda expression so that the * arguments are available to the EL context during evaluation. * * @param arguments The arguments in scope for the current lambda * expression. * @since EL 3.0 */ public void enterLambdaScope(Map<String,Object> arguments) { lambdaArguments.push(arguments); } /** * Called after evaluating a lambda expression to signal that the arguments * are no longer required. * * @since EL 3.0 */ public void exitLambdaScope() { lambdaArguments.pop(); } /** * Coerce the supplied object to the requested type. * * @param obj The object to be coerced * @param type The type to which the object should be coerced * * @return An instance of the requested type. * * @throws ELException * If the conversion fails * * @since EL 3.0 */ public Object convertToType(Object obj, Class<?> type) { boolean originalResolved = isPropertyResolved(); setPropertyResolved(false); try { ELResolver resolver = getELResolver(); if (resolver != null) { Object result = resolver.convertToType(this, obj, type); if (isPropertyResolved()) { return result; } } } finally { setPropertyResolved(originalResolved); } return ELManager.getExpressionFactory().coerceToType(obj, type); } }
// package me.dwliu.framework.integration.security.feign.fallback; // // import feign.hystrix.FallbackFactory; // import lombok.extern.slf4j.Slf4j; // import me.dwliu.framework.common.constant.ServiceConstant; // import me.dwliu.framework.common.model.Result; // import me.dwliu.framework.core.security.entity.UserInfoDetails; // import me.dwliu.framework.integration.security.feign.UserInfoDetailsFeignClient; // import org.springframework.cloud.openfeign.FeignClient; // import org.springframework.stereotype.Component; // // /** // * 用户接口FallbackFactory // * // * @author liudw // * @date 2020/7/3 22:36 // **/ // @Component // @Slf4j // public class UserInfoDetailsFallbackFactory implements FallbackFactory<UserInfoDetailsFeignClient> { // // // // @Override // // public UserInfoDetailsFeignClient create(Throwable throwable) { // // log.error("{}", throwable); // // return (username, from) -> new Result<>(); // // } // }
package br.com.ihelp.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import br.com.ihelp.service.AuthenticationService; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { private AuthenticationService authenticationService; public SecurityConfig(AuthenticationService authenticationService) { this.authenticationService = authenticationService; } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/shipments/**").authenticated() .and().formLogin().loginPage("/").defaultSuccessUrl("/shipments") .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout/**")).logoutSuccessUrl("/"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(authenticationService).passwordEncoder(AuthenticationService.getPasswordEncoder()); } }
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.skylarkbuildapi.cpp; import com.google.devtools.build.lib.events.Location; import com.google.devtools.build.lib.skylarkbuildapi.FileApi; import com.google.devtools.build.lib.skylarkbuildapi.SkylarkActionFactoryApi; import com.google.devtools.build.lib.skylarkbuildapi.SkylarkRuleContextApi; import com.google.devtools.build.lib.skylarkinterface.Param; import com.google.devtools.build.lib.skylarkinterface.ParamType; import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable; import com.google.devtools.build.lib.skylarkinterface.SkylarkModule; import com.google.devtools.build.lib.syntax.EvalException; import com.google.devtools.build.lib.syntax.Runtime.NoneType; import com.google.devtools.build.lib.syntax.SkylarkList; import com.google.devtools.build.lib.syntax.SkylarkList.Tuple; import com.google.devtools.build.lib.syntax.SkylarkNestedSet; import com.google.devtools.build.lib.syntax.StarlarkThread; /** Utilites related to C++ support. */ @SkylarkModule( name = "cc_common", doc = "Utilities for C++ compilation, linking, and command line generation.") public interface BazelCcModuleApi< SkylarkActionFactoryT extends SkylarkActionFactoryApi, FileT extends FileApi, SkylarkRuleContextT extends SkylarkRuleContextApi, CcToolchainProviderT extends CcToolchainProviderApi<FeatureConfigurationT>, FeatureConfigurationT extends FeatureConfigurationApi, CompilationContextT extends CcCompilationContextApi, CompilationOutputsT extends CcCompilationOutputsApi<FileT>, LinkingOutputsT extends CcLinkingOutputsApi<FileT>, LibraryToLinkT extends LibraryToLinkApi<FileT>, LinkingContextT extends CcLinkingContextApi<FileT>, CcToolchainVariablesT extends CcToolchainVariablesApi, CcToolchainConfigInfoT extends CcToolchainConfigInfoApi> extends CcModuleApi< SkylarkActionFactoryT, FileT, CcToolchainProviderT, FeatureConfigurationT, CompilationContextT, LinkingContextT, LibraryToLinkT, CcToolchainVariablesT, SkylarkRuleContextT, CcToolchainConfigInfoT, CompilationOutputsT> { @SkylarkCallable( name = "compile", doc = "Should be used for C++ compilation.", useStarlarkThread = true, useLocation = true, parameters = { @Param( name = "actions", type = SkylarkActionFactoryApi.class, positional = false, named = true, doc = "<code>actions</code> object."), @Param( name = "feature_configuration", doc = "<code>feature_configuration</code> to be queried.", positional = false, named = true, type = FeatureConfigurationApi.class), @Param( name = "cc_toolchain", doc = "<code>CcToolchainInfo</code> provider to be used.", positional = false, named = true, type = CcToolchainProviderApi.class), @Param( name = "srcs", doc = "The list of source files to be compiled.", positional = false, named = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "public_hdrs", doc = "List of headers needed for compilation of srcs and may be included by dependent " + "rules transitively.", positional = false, named = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "private_hdrs", doc = "List of headers needed for compilation of srcs and NOT to be included by" + " dependent rules.", positional = false, named = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "includes", doc = "Search paths for header files referenced both by angle bracket and quotes. " + "Usually passed with -I. Propagated to dependents transitively.", positional = false, named = true, noneable = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "quote_includes", doc = "Search paths for header files referenced by quotes, " + "e.g. #include \"foo/bar/header.h\". They can be either relative to the exec " + "root or absolute. Usually passed with -iquote. Propagated to dependents " + "transitively.", positional = false, named = true, noneable = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "system_includes", doc = "Search paths for header files referenced by angle brackets, e.g. #include" + " <foo/bar/header.h>. They can be either relative to the exec root or" + " absolute. Usually passed with -isystem. Propagated to dependents " + "transitively.", positional = false, named = true, noneable = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "framework_includes", doc = "Search paths for header files from Apple frameworks. They can be either relative " + "to the exec root or absolute. Usually passed with -F. Propagated to " + "dependents transitively.", positional = false, named = true, noneable = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "defines", doc = "Set of defines needed to compile this target. Each define is a string. Propagated" + " to dependents transitively.", positional = false, named = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "local_defines", doc = "Set of defines needed to compile this target. Each define is a string. Not" + " propagated to dependents transitively.", positional = false, named = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "user_compile_flags", doc = "Additional list of compilation options.", positional = false, named = true, noneable = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "compilation_contexts", doc = "Headers from dependencies used for compilation.", positional = false, named = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "name", doc = "This is used for naming the output artifacts of actions created by this " + "method.", positional = false, named = true, type = String.class), @Param( name = "disallow_pic_outputs", doc = "Whether PIC outputs should be created.", positional = false, named = true, defaultValue = "False", type = Boolean.class), @Param( name = "disallow_nopic_outputs", doc = "Whether NOPIC outputs should be created.", positional = false, named = true, defaultValue = "False", type = Boolean.class), @Param( name = "additional_inputs", doc = "List of additional files needed for compilation of srcs", positional = false, named = true, defaultValue = "[]", type = SkylarkList.class), }) Tuple<Object> compile( SkylarkActionFactoryT skylarkActionFactoryApi, FeatureConfigurationT skylarkFeatureConfiguration, CcToolchainProviderT skylarkCcToolchainProvider, SkylarkList<FileT> sources, SkylarkList<FileT> publicHeaders, SkylarkList<FileT> privateHeaders, SkylarkList<String> includes, SkylarkList<String> quoteIncludes, SkylarkList<String> systemIncludes, SkylarkList<String> frameworkIncludes, SkylarkList<String> defines, SkylarkList<String> localDefines, SkylarkList<String> userCompileFlags, SkylarkList<CompilationContextT> ccCompilationContexts, String name, boolean disallowPicOutputs, boolean disallowNopicOutputs, SkylarkList<FileT> additionalInputs, Location location, StarlarkThread thread) throws EvalException, InterruptedException; @SkylarkCallable( name = "link", doc = "Should be used for C++ transitive linking.", useStarlarkThread = true, useLocation = true, parameters = { @Param( name = "actions", type = SkylarkActionFactoryApi.class, positional = false, named = true, doc = "<code>actions</code> object."), @Param( name = "feature_configuration", doc = "<code>feature_configuration</code> to be queried.", positional = false, named = true, type = FeatureConfigurationApi.class), @Param( name = "cc_toolchain", doc = "<code>CcToolchainInfo</code> provider to be used.", positional = false, named = true, type = CcToolchainProviderApi.class), @Param( name = "compilation_outputs", doc = "Compilation outputs containing object files to link.", positional = false, named = true, defaultValue = "None", noneable = true, allowedTypes = { @ParamType(type = CcCompilationOutputsApi.class), @ParamType(type = NoneType.class) }), @Param( name = "user_link_flags", doc = "Additional list of linker options.", positional = false, named = true, defaultValue = "[]", noneable = true, type = SkylarkList.class), @Param( name = "linking_contexts", doc = "Linking contexts from dependencies to be linked into the linking context " + "generated by this rule.", positional = false, named = true, noneable = true, defaultValue = "[]", type = SkylarkList.class), @Param( name = "name", doc = "This is used for naming the output artifacts of actions created by this " + "method.", positional = false, named = true, type = String.class), @Param( name = "language", doc = "Only C++ supported for now. Do not use this parameter.", positional = false, named = true, noneable = true, defaultValue = "'c++'", type = String.class), @Param( name = "output_type", doc = "Can be either 'executable' or 'dynamic_library'.", positional = false, named = true, noneable = true, defaultValue = "'executable'", type = String.class), @Param( name = "link_deps_statically", doc = " True to link dependencies statically, False dynamically.", positional = false, named = true, noneable = true, defaultValue = "True", type = Boolean.class), @Param( name = "additional_inputs", doc = "For additional inputs to the linking action, e.g.: linking scripts.", positional = false, named = true, defaultValue = "[]", type = SkylarkList.class), }) LinkingOutputsT link( SkylarkActionFactoryT skylarkActionFactoryApi, FeatureConfigurationT skylarkFeatureConfiguration, CcToolchainProviderT skylarkCcToolchainProvider, Object compilationOutputs, SkylarkList<String> userLinkFlags, SkylarkList<LinkingContextT> linkingContexts, String name, String language, String outputType, boolean linkDepsStatically, SkylarkList<FileT> additionalInputs, Location location, StarlarkThread thread) throws InterruptedException, EvalException; @SkylarkCallable( name = "create_compilation_outputs", doc = "Create compilation outputs object.", useLocation = true, parameters = { @Param( name = "objects", doc = "List of object files.", positional = false, named = true, noneable = true, defaultValue = "None", allowedTypes = { @ParamType(type = SkylarkNestedSet.class), @ParamType(type = NoneType.class) }), @Param( name = "pic_objects", doc = "List of pic object files.", positional = false, named = true, noneable = true, defaultValue = "None", allowedTypes = { @ParamType(type = SkylarkNestedSet.class), @ParamType(type = NoneType.class) }), }) CompilationOutputsT createCompilationOutputsFromSkylark( Object objectsObject, Object picObjectsObject, Location location) throws EvalException; @SkylarkCallable( name = "merge_compilation_outputs", doc = "Merge compilation outputs.", parameters = { @Param( name = "compilation_outputs", positional = false, named = true, defaultValue = "[]", type = SkylarkList.class), }) CompilationOutputsT mergeCcCompilationOutputsFromSkylark( SkylarkList<CompilationOutputsT> compilationOutputs); }
/* * Copyright (c) 2008-2019 Haulmont. * * 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.haulmont.reports.gui.template.edit.pivottable.property.edit; import com.haulmont.cuba.gui.components.AbstractEditor; import com.haulmont.cuba.gui.components.FieldGroup; import com.haulmont.cuba.gui.components.SourceCodeEditor; import com.haulmont.cuba.gui.data.Datasource; import com.haulmont.reports.entity.pivottable.PivotTableProperty; import com.haulmont.reports.entity.pivottable.PivotTablePropertyType; import javax.inject.Inject; public class PivotTablePropertyEdit extends AbstractEditor<PivotTableProperty> { @Inject protected FieldGroup editGroup; @Inject protected Datasource<PivotTableProperty> propertyDs; @Inject protected SourceCodeEditor sourceCodeEditor; @Override protected void postInit() { super.postInit(); initFunctionField(); propertyDs.addItemPropertyChangeListener(e -> { if ("type".equals(e.getProperty())) { initFunctionField(); } }); sourceCodeEditor.setContextHelpIconClickHandler(e -> showMessageDialog(getMessage("pivotTable.functionHelpCaption"), getMessage("pivotTable.propertyFunctionHelp"), MessageType.CONFIRMATION_HTML .modal(false) .width(560f))); } protected void initFunctionField() { PivotTableProperty property = getItem(); editGroup.getFieldNN("function") .setVisible(property.getType() == PivotTablePropertyType.DERIVED); } @Override public boolean commit() { return true; } }
/* * Copyright 2011 LMAX Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lmax.disruptor.queue; import com.lmax.disruptor.AbstractPerfTestQueue; import com.lmax.disruptor.support.ValueAdditionQueueBatchProcessor; import com.lmax.disruptor.support.ValueQueuePublisher; import com.lmax.disruptor.util.DaemonThreadFactory; import java.util.concurrent.*; /** * <pre> * * Sequence a series of events from multiple publishers going to one event processor. * * +----+ * | P1 |------+ * +----+ | * v * +----+ +-----+ * | P1 |--->| EP1 | * +----+ +-----+ * ^ * +----+ | * | P3 |------+ * +----+ * * * Queue Based: * ============ * * +----+ put * | P1 |------+ * +----+ | * v take * +----+ +====+ +-----+ * | P2 |--->| Q1 |<---| EP1 | * +----+ +====+ +-----+ * ^ * +----+ | * | P3 |------+ * +----+ * * P1 - Publisher 1 * P2 - Publisher 2 * P3 - Publisher 3 * Q1 - Queue 1 * EP1 - EventProcessor 1 * * </pre> */ public final class ThreeToOneQueueBatchThroughputTest extends AbstractPerfTestQueue { private static final int NUM_PUBLISHERS = 3; private static final int BUFFER_SIZE = 1024 * 64; private static final long ITERATIONS = 1000L * 1000L * 20L; private final ExecutorService executor = Executors.newFixedThreadPool(NUM_PUBLISHERS + 1, DaemonThreadFactory.INSTANCE); private final CyclicBarrier cyclicBarrier = new CyclicBarrier(NUM_PUBLISHERS + 1); /////////////////////////////////////////////////////////////////////////////////////////////// private final BlockingQueue<Long> blockingQueue = new ArrayBlockingQueue<>(BUFFER_SIZE); private final ValueAdditionQueueBatchProcessor queueProcessor = new ValueAdditionQueueBatchProcessor(blockingQueue, ((ITERATIONS / NUM_PUBLISHERS) * NUM_PUBLISHERS) - 1L); private final ValueQueuePublisher[] valueQueuePublishers = new ValueQueuePublisher[NUM_PUBLISHERS]; { for (int i = 0; i < NUM_PUBLISHERS; i++) { valueQueuePublishers[i] = new ValueQueuePublisher(cyclicBarrier, blockingQueue, ITERATIONS / NUM_PUBLISHERS); } } /////////////////////////////////////////////////////////////////////////////////////////////// @Override protected int getRequiredProcessorCount() { return 4; } @Override protected long runQueuePass() throws Exception { final CountDownLatch latch = new CountDownLatch(1); queueProcessor.reset(latch); Future<?>[] futures = new Future[NUM_PUBLISHERS]; for (int i = 0; i < NUM_PUBLISHERS; i++) { futures[i] = executor.submit(valueQueuePublishers[i]); } Future<?> processorFuture = executor.submit(queueProcessor); long start = System.currentTimeMillis(); cyclicBarrier.await(); for (int i = 0; i < NUM_PUBLISHERS; i++) { futures[i].get(); } latch.await(); long opsPerSecond = (ITERATIONS * 1000L) / (System.currentTimeMillis() - start); queueProcessor.halt(); processorFuture.cancel(true); return opsPerSecond; } public static void main(String[] args) throws Exception { new ThreeToOneQueueBatchThroughputTest().testImplementations(); } }
/* * Copyright (c) 2017 <l_iupeiyu@qq.com> All rights reserved. */ package com.geekcattle.mapper.console; import com.geekcattle.model.console.Menu; import com.geekcattle.util.CustomerMapper; import org.springframework.stereotype.Service; import java.util.List; import java.util.Set; @Service public interface MenuMapper extends CustomerMapper<Menu> { Set<String> findMenuCodeByUserId(String userId); Set<String> getALLMenuCode(); List<Menu> selectMenuByAdminId(String userId); List<Menu> selectAllMenu(); List<Menu> selectMenuByRoleId(String roleId); }
package ch.uzh.ifi.hase.soprafs22.rest.dto; import ch.uzh.ifi.hase.soprafs22.constant.Campus; import ch.uzh.ifi.hase.soprafs22.entity.SleepEvent; import java.util.List; public class PlaceGetDTO { private int placeId; private int providerId; private String name; private String address; private Campus closestCampus; private String description; private String pictureOfThePlace; private List<SleepEvent> sleepEvents; public int getPlaceId(){ return placeId; } public void setPlaceId(int placeId){ this.placeId = placeId; } public int getProviderId(){ return providerId; } public void setProviderId(int providerId){ this.providerId = providerId; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public String getAddress(){ return address; } public void setAddress(String address){ this.address = address; } public Campus getClosestCampus(){ return closestCampus; } public void setClosestCampus(Campus closestCampus){ this.closestCampus = closestCampus; } public String getDescription(){ return description; } public void setDescription(String description){ this.description = description; } public String getPictureOfThePlace(){ return pictureOfThePlace; } public void setPictureOfThePlace(String pictureOfThePlace){ this.pictureOfThePlace = pictureOfThePlace; } public List<SleepEvent> getSleepEvents(){ return sleepEvents; } public void setSleepEvents(List<SleepEvent> sleepEvents){ this.sleepEvents = sleepEvents; } }
package fake.package_4; public class Foo189 { public void foo0(){ new Foo188().foo49(); } public void foo1(){ foo0(); } public void foo2(){ foo1(); } public void foo3(){ foo2(); } public void foo4(){ foo3(); } public void foo5(){ foo4(); } public void foo6(){ foo5(); } public void foo7(){ foo6(); } public void foo8(){ foo7(); } public void foo9(){ foo8(); } public void foo10(){ foo9(); } public void foo11(){ foo10(); } public void foo12(){ foo11(); } public void foo13(){ foo12(); } public void foo14(){ foo13(); } public void foo15(){ foo14(); } public void foo16(){ foo15(); } public void foo17(){ foo16(); } public void foo18(){ foo17(); } public void foo19(){ foo18(); } public void foo20(){ foo19(); } public void foo21(){ foo20(); } public void foo22(){ foo21(); } public void foo23(){ foo22(); } public void foo24(){ foo23(); } public void foo25(){ foo24(); } public void foo26(){ foo25(); } public void foo27(){ foo26(); } public void foo28(){ foo27(); } public void foo29(){ foo28(); } public void foo30(){ foo29(); } public void foo31(){ foo30(); } public void foo32(){ foo31(); } public void foo33(){ foo32(); } public void foo34(){ foo33(); } public void foo35(){ foo34(); } public void foo36(){ foo35(); } public void foo37(){ foo36(); } public void foo38(){ foo37(); } public void foo39(){ foo38(); } public void foo40(){ foo39(); } public void foo41(){ foo40(); } public void foo42(){ foo41(); } public void foo43(){ foo42(); } public void foo44(){ foo43(); } public void foo45(){ foo44(); } public void foo46(){ foo45(); } public void foo47(){ foo46(); } public void foo48(){ foo47(); } public void foo49(){ foo48(); } }
package launchserver.auth.provider; import java.io.IOException; import java.util.Objects; import launcher.LauncherAPI; import launcher.helper.VerifyHelper; import launcher.serialize.config.entry.BlockConfigEntry; public class DelegateAuthProvider extends AuthProvider { private volatile AuthProvider delegate; public DelegateAuthProvider(BlockConfigEntry block) { super(block); } @Override public AuthProviderResult auth(String login, String password, String ip) throws Throwable { return getDelegate().auth(login, password, ip); } @Override public void close() throws IOException { AuthProvider delegate = this.delegate; if (delegate != null) { delegate.close(); } } @LauncherAPI public void setDelegate(AuthProvider delegate) { this.delegate = delegate; } private AuthProvider getDelegate() { return VerifyHelper.verify(delegate, Objects::nonNull, "Delegate auth provider wasn't set"); } }
package br.com.zup.proposal.resources.analysis; import javax.validation.constraints.NotBlank; public class AnalysisResourceRequest { @NotBlank String documento; @NotBlank String nome; @NotBlank String idProposta; public AnalysisResourceRequest ( @NotBlank String documento , @NotBlank String nome , @NotBlank String idProposta ) { this.documento = documento; this.nome = nome; this.idProposta = idProposta; } public String getDocumento () { return documento; } public String getNome () { return nome; } public String getIdProposta () { return idProposta; } }
/* * Copyright 2012-2020 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.gradle.docs; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import java.util.zip.ZipEntry; import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.gradle.junit.GradleMultiDslExtension; import org.springframework.boot.gradle.testkit.GradleBuild; import org.springframework.util.FileCopyUtils; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for the packaging documentation. * * @author Andy Wilkinson * @author Jean-Baptiste Nizet */ @ExtendWith(GradleMultiDslExtension.class) class PackagingDocumentationTests { GradleBuild gradleBuild; @TestTemplate void warContainerDependencyEvaluatesSuccessfully() { this.gradleBuild.script("src/docs/gradle/packaging/war-container-dependency").build(); } @TestTemplate void bootJarMainClass() throws IOException { this.gradleBuild.script("src/docs/gradle/packaging/boot-jar-main-class").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) .isEqualTo("com.example.ExampleApplication"); } } @TestTemplate void bootJarManifestMainClass() throws IOException { this.gradleBuild.script("src/docs/gradle/packaging/boot-jar-manifest-main-class").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) .isEqualTo("com.example.ExampleApplication"); } } @TestTemplate void applicationPluginMainClass() throws IOException { this.gradleBuild.script("src/docs/gradle/packaging/application-plugin-main-class").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) .isEqualTo("com.example.ExampleApplication"); } } @TestTemplate void springBootDslMainClass() throws IOException { this.gradleBuild.script("src/docs/gradle/packaging/spring-boot-dsl-main-class").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Start-Class")) .isEqualTo("com.example.ExampleApplication"); } } @TestTemplate void bootWarIncludeDevtools() throws IOException { jarFile(new File(this.gradleBuild.getProjectDir(), "spring-boot-devtools-1.2.3.RELEASE.jar")); this.gradleBuild.script("src/docs/gradle/packaging/boot-war-include-devtools").build("bootWar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".war"); assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getEntry("WEB-INF/lib/spring-boot-devtools-1.2.3.RELEASE.jar")).isNotNull(); } } @TestTemplate void bootJarRequiresUnpack() throws IOException { this.gradleBuild.script("src/docs/gradle/packaging/boot-jar-requires-unpack").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { JarEntry entry = jar.getJarEntry("BOOT-INF/lib/jruby-complete-1.7.25.jar"); assertThat(entry).isNotNull(); assertThat(entry.getComment()).startsWith("UNPACK:"); } } @TestTemplate void bootJarIncludeLaunchScript() throws IOException { this.gradleBuild.script("src/docs/gradle/packaging/boot-jar-include-launch-script").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); assertThat(FileCopyUtils.copyToString(new FileReader(file))).startsWith("#!/bin/bash"); } @TestTemplate void bootJarLaunchScriptProperties() throws IOException { this.gradleBuild.script("src/docs/gradle/packaging/boot-jar-launch-script-properties").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); assertThat(FileCopyUtils.copyToString(new FileReader(file))).contains("example-app.log"); } @TestTemplate void bootJarCustomLaunchScript() throws IOException { File customScriptFile = new File(this.gradleBuild.getProjectDir(), "src/custom.script"); customScriptFile.getParentFile().mkdirs(); FileCopyUtils.copy("custom", new FileWriter(customScriptFile)); this.gradleBuild.script("src/docs/gradle/packaging/boot-jar-custom-launch-script").build("bootJar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(file).isFile(); assertThat(FileCopyUtils.copyToString(new FileReader(file))).startsWith("custom"); } @TestTemplate void bootWarPropertiesLauncher() throws IOException { this.gradleBuild.script("src/docs/gradle/packaging/boot-war-properties-launcher").build("bootWar"); File file = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".war"); assertThat(file).isFile(); try (JarFile jar = new JarFile(file)) { assertThat(jar.getManifest().getMainAttributes().getValue("Main-Class")) .isEqualTo("org.springframework.boot.loader.PropertiesLauncher"); } } @TestTemplate void bootJarAndJar() { this.gradleBuild.script("src/docs/gradle/packaging/boot-jar-and-jar").build("assemble"); File jar = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + ".jar"); assertThat(jar).isFile(); File bootJar = new File(this.gradleBuild.getProjectDir(), "build/libs/" + this.gradleBuild.getProjectDir().getName() + "-boot.jar"); assertThat(bootJar).isFile(); } protected void jarFile(File file) throws IOException { try (JarOutputStream jar = new JarOutputStream(new FileOutputStream(file))) { jar.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); new Manifest().write(jar); jar.closeEntry(); } } }
package com.stackroute.config; import com.stackroute.domain.Paragraph; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; import org.json.simple.JSONObject; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; import org.springframework.kafka.support.serializer.JsonSerializer; import java.util.HashMap; import java.util.Map; @Configuration public class ProducerKafkaConfiguration { @Bean public ProducerFactory<String, JSONObject> producerFactory() { Map<String, Object> config = new HashMap<>(); config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(config); } @Bean public KafkaTemplate<String, JSONObject> kafkaTemplate() { return new KafkaTemplate<>(producerFactory()); } }
package org.firstinspires.ftc.teamcode.Opmodes; import com.acmerobotics.dashboard.FtcDashboard; import com.acmerobotics.dashboard.telemetry.MultipleTelemetry; import com.disnodeteam.dogecv.detectors.skystone.SkystoneDetector; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.firstinspires.ftc.teamcode.Vision.CustomSkystoneDetector; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraRotation; import org.openftc.easyopencv.OpenCvInternalCamera; @TeleOp public class DogeCVTest extends LinearOpMode { CustomSkystoneDetector detector; OpenCvCamera phoneCam; @Override public void runOpMode() throws InterruptedException { detector = new CustomSkystoneDetector(); detector.useDefaults(); int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); phoneCam = new OpenCvInternalCamera(OpenCvInternalCamera.CameraDirection.BACK, cameraMonitorViewId); phoneCam.openCameraDevice(); phoneCam.setPipeline(detector); phoneCam.startStreaming(320, 240, OpenCvCameraRotation.SIDEWAYS_LEFT); MultipleTelemetry telemetry = new MultipleTelemetry(this.telemetry, FtcDashboard.getInstance().getTelemetry()); waitForStart(); while (opModeIsActive()) { telemetry.addData("FPS", String.format("%.2f", phoneCam.getFps())); telemetry.addData("Position", detector.getScreenPosition().x); telemetry.addData("Area",detector.foundRectangle().height * detector.foundRectangle().width); telemetry.addData("Width", detector.foundRectangle().width); telemetry.update(); sleep(10); } } }
package com.reminder_keeper.activities; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import com.reminder_keeper.R; import com.reminder_keeper.views.ToolbarView; public class AboutActivity extends AppCompatActivity { public static final String ABOUT_ACTIVITY = "aboutActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); setSupportActionBar((Toolbar) findViewById(R.id.toolbar_custom)); new ToolbarView(this, getSupportActionBar(), ABOUT_ACTIVITY); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: finish(); } return super.onOptionsItemSelected(item); } }
package edu.pku.intellimerge.model.node; import com.github.javaparser.Range; import edu.pku.intellimerge.model.SemanticNode; import edu.pku.intellimerge.model.constant.NodeType; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class TerminalNode extends SemanticNode { private String body; public TerminalNode( Integer nodeID, Boolean needToMerge, NodeType nodeType, String displayName, String qualifiedName, String originalSignature, String comment, List<String> annotations, List<String> modifiers, String body, Optional<Range> range) { super( nodeID, needToMerge, nodeType, displayName, qualifiedName, originalSignature, comment, annotations, modifiers, range); this.body = body; } public TerminalNode( Integer nodeID, Boolean needToMerge, NodeType nodeType, String displayName, String qualifiedName, String originalSignature, Optional<Range> range) { super( nodeID, needToMerge, nodeType, displayName, qualifiedName, originalSignature, "", new ArrayList<>(), new ArrayList<>(), false, range); } @Override public SemanticNode shallowClone() { TerminalNode clone = new TerminalNode( this.getNodeID(), this.needToMerge(), this.getNodeType(), this.getDisplayName(), this.getQualifiedName(), this.getOriginalSignature(), this.getComment(), this.getAnnotations(), this.getModifiers(), this.getBody(), this.getRange()); clone.followingEOL = this.followingEOL; return clone; } @Override public SemanticNode deepClone() { return shallowClone(); } /** * Consider that terminal node has no children * * @return */ @Override public List<SemanticNode> getChildren() { return new ArrayList<>(); } public String getBody() { return body; } public void setBody(String body) { this.body = body; } @Override public String getSignature() { return getQualifiedName(); } }
/* * JsonModelGen - Model Generation from JSON Schema * * Copyright (c) 2015-2016 Marco Hutter - http://www.javagl.de * * 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 de.javagl.jsonmodelgen.json.schema.v4; /** * Specialization of a {@link NumberSchema} for integer types. See * <a href="https://tools.ietf.org/html/draft-zyp-json-schema-03"> * https://tools.ietf.org/html/draft-zyp-json-schema-03</a> */ public class IntegerSchema extends NumberSchema { @Override public IntegerSchema asInteger() { return this; } }
/** * An implementation of the lazy Prim's algorithm with an adjacency matrix * which upon visiting a new node adds all the edges to the min priority * queue and also removes already seen edges when polling. * * Time Complexity: O(V^2) * * @author William Fiset, william.alexandre.fiset@gmail.com **/ package com.williamfiset.algorithms.graphtheory; import java.util.*; public class LazyPrimsAdjacencyMatrix { static class Edge implements Comparable <Edge> { int to, cost; public Edge(int to, int cost) { this.to = to; this.cost = cost; } @Override public int compareTo(Edge other) { return cost - other.cost; } } // Given an N*N undirected adjacency matrix, that is a // graph with matrix[i][j] = matrix[j][i] for all i,j this method // finds the minimum spanning tree cost using Prim's algorithm public static Long prims(Integer[][] graph) { int n = graph.length; long sum = 0, visitedNodes = 1; PriorityQueue <Edge> pq = new PriorityQueue<>(); boolean[] connected = new boolean[n]; connected[0] = true; for (int i = 1; i < n; i++) if (graph[0][i] != null) pq.offer(new Edge(i, graph[0][i])); // Loop while the MST is not complete while (visitedNodes != n && !pq.isEmpty()) { Edge edge = pq.poll(); if (!connected[edge.to]) { // Update minimum distances for (int i = 0; i < n; i++) if (!connected[i] && graph[edge.to][i] != null) pq.offer(new Edge(i, graph[edge.to][i])); connected[edge.to] = true; sum += edge.cost; visitedNodes++; } } // Make sure MST spans the whole graph if (visitedNodes != n) return null; return sum; } // Example usage public static void main(String[] args) { final int NUM_NODES = 10; Integer[][] graph = new Integer[NUM_NODES][NUM_NODES]; // Make an undirected graph graph[0][1] = graph[1][0] = 1; graph[0][3] = graph[3][0] = 4; graph[0][4] = graph[4][0] = 5; graph[1][3] = graph[3][1] = 2; graph[1][2] = graph[2][1] = 1; graph[2][3] = graph[3][2] = 5; graph[2][5] = graph[5][2] = 7; graph[3][4] = graph[4][3] = 2; graph[3][6] = graph[6][3] = 2; graph[3][5] = graph[5][3] = 11; graph[4][7] = graph[7][4] = 4; graph[5][6] = graph[6][5] = 1; graph[5][8] = graph[8][5] = 4; graph[6][7] = graph[7][6] = 4; graph[6][8] = graph[8][6] = 6; graph[7][8] = graph[8][7] = 1; graph[7][9] = graph[9][7] = 2; graph[8][9] = graph[9][8] = 0; Long mstCost = prims(graph); System.out.println("MST cost: " + mstCost); } }
package com.ethanco.mvvm_bridge_anno; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by YOLANDA on 2016-01-21. */ @Retention(RetentionPolicy.SOURCE) //@Target(ElementType.METHOD) public @interface MVVM { Class value(); // Class View(); // // Class ViewModel(); }
/* * MIT License * * Copyright (c) 2018 Ensar Sarajčić * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.ensarsarajcic.neovim.java.corerpc.client; import com.ensarsarajcic.neovim.java.corerpc.message.Message; import com.ensarsarajcic.neovim.java.corerpc.message.MessageIdGenerator; import com.ensarsarajcic.neovim.java.corerpc.message.NotificationMessage; import com.ensarsarajcic.neovim.java.corerpc.message.RequestMessage; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public class PackStreamTest { @Mock RpcListener rpcListener; @Mock RpcSender rpcSender; @Mock MessageIdGenerator messageIdGenerator; @InjectMocks PackStream packStream; @Mock InputStream inputStream; @Mock OutputStream outputStream; private RpcConnection connection; private ArgumentCaptor<RpcListener.RequestCallback> packStreamRequestCallback; private ArgumentCaptor<RpcListener.NotificationCallback> packStreamNotificationCallback; @Before public void setUp() throws Exception { prepareListeners(); connection = new RpcConnection() { @Override public InputStream getIncomingStream() { return inputStream; } @Override public OutputStream getOutgoingStream() { return outputStream; } @Override public void close() throws IOException { } }; } @Test public void testAttach() { // When attach is called packStream.attach(connection); // Rpc listener and sender should be prepared verify(rpcListener).listenForRequests(any()); verify(rpcListener).listenForNotifications(any()); verify(rpcListener).start(inputStream); verify(rpcSender).attach(outputStream); } @Test public void testSend() throws IOException { // When send is called Message message = () -> null; packStream.send(message); // Rpc sender should be used verify(rpcSender).send(message); } @Test public void testSendRequest() throws IOException { // Given a proper message id generator given(messageIdGenerator.nextId()).willReturn(25); // When send is called var message = new RequestMessage.Builder("test"); packStream.send(message); // Rpc sender should be used var argumentCaptor = ArgumentCaptor.forClass(RequestMessage.class); verify(rpcSender).send(argumentCaptor.capture()); assertEquals("test", argumentCaptor.getValue().getMethod()); // And id for the message should be generated verify(messageIdGenerator).nextId(); // And put into the message assertEquals(25, argumentCaptor.getValue().getId()); } @Test public void testSendRequestWithCallback() throws IOException { // Given a proper message id generator given(messageIdGenerator.nextId()).willReturn(25); // And callback var responseCallback = Mockito.mock(RpcListener.ResponseCallback.class); // When send is called var message = new RequestMessage.Builder("test"); packStream.send(message, responseCallback); // Rpc sender should be used var argumentCaptor = ArgumentCaptor.forClass(RequestMessage.class); verify(rpcSender).send(argumentCaptor.capture()); assertEquals("test", argumentCaptor.getValue().getMethod()); // And id for the message should be generated verify(messageIdGenerator).nextId(); // And put into the message assertEquals(25, argumentCaptor.getValue().getId()); // RPC Listener should be used too verify(rpcListener).listenForResponse(25, responseCallback); } @Test public void testRequestCallback() throws IOException { // Given a proper rpc listener and attached pack stream packStream.attach(connection); // When request callback is added var firstCallback = Mockito.mock(RpcListener.RequestCallback.class); packStream.addRequestCallback(firstCallback); // It should receive requests var msg1 = new RequestMessage.Builder("test").build(); packStreamRequestCallback.getValue().requestReceived(msg1); verify(firstCallback).requestReceived(msg1); // Multiple callbacks should be supported too var secondCallback = Mockito.mock(RpcListener.RequestCallback.class); packStream.addRequestCallback(secondCallback); // Both should receive messages var msg2 = new RequestMessage.Builder("test2").build(); packStreamRequestCallback.getValue().requestReceived(msg2); verify(firstCallback).requestReceived(msg2); verify(secondCallback).requestReceived(msg2); // Removing should be supported packStream.removeRequestCallback(firstCallback); // Only second should receive message now var msg3 = new RequestMessage.Builder("test3").build(); packStreamRequestCallback.getValue().requestReceived(msg3); verify(firstCallback, never()).requestReceived(msg3); verify(secondCallback).requestReceived(msg3); // Multiple removals packStream.removeRequestCallback(secondCallback); // None should receive message now var msg4 = new RequestMessage.Builder("test4").build(); packStreamRequestCallback.getValue().requestReceived(msg4); verify(firstCallback, never()).requestReceived(msg4); verify(secondCallback, never()).requestReceived(msg4); } @Test public void testNotificationCallback() throws IOException { // Given a proper rpc listener and attached pack stream packStream.attach(connection); // When notification callback is added var firstCallback = Mockito.mock(RpcListener.NotificationCallback.class); packStream.addNotificationCallback(firstCallback); // It should receive requests var msg1 = new NotificationMessage.Builder("test").build(); packStreamNotificationCallback.getValue().notificationReceived(msg1); verify(firstCallback).notificationReceived(msg1); // Multiple callbacks should be supported too var secondCallback = Mockito.mock(RpcListener.NotificationCallback.class); packStream.addNotificationCallback(secondCallback); // Both should receive messages var msg2 = new NotificationMessage.Builder("test2").build(); packStreamNotificationCallback.getValue().notificationReceived(msg2); verify(firstCallback).notificationReceived(msg2); verify(secondCallback).notificationReceived(msg2); // Removing should be supported packStream.removeNotificationCallback(firstCallback); // Only second should receive message now var msg3 = new NotificationMessage.Builder("test3").build(); packStreamNotificationCallback.getValue().notificationReceived(msg3); verify(firstCallback, never()).notificationReceived(msg3); verify(secondCallback).notificationReceived(msg3); // Multiple removals packStream.removeNotificationCallback(secondCallback); // None should receive message now var msg4 = new NotificationMessage.Builder("test4").build(); packStreamNotificationCallback.getValue().notificationReceived(msg4); verify(firstCallback, never()).notificationReceived(msg4); verify(secondCallback, never()).notificationReceived(msg4); } @Test(expected = NullPointerException.class) public void noNullRpcListener() { // When null rpc listener is passed, constructor should throw an exception try { new PackStream(rpcSender, null); fail("Constructor did not throw an exception"); } catch (NullPointerException ex) { // pass } new PackStream(rpcSender, null, messageIdGenerator); } @Test(expected = NullPointerException.class) public void noNullRpcSender() { // When null rpc sender is passed, constructor should throw an exception try { new PackStream(null, rpcListener); fail("Constructor did not throw an exception"); } catch (NullPointerException ex) { // pass } new PackStream(null, rpcListener, messageIdGenerator); } @Test(expected = NullPointerException.class) public void noNullMessageIdGenerator() { // When null message id generator is passed, constructor should throw an exception new PackStream(rpcSender, rpcListener, null); } private void prepareListeners() { packStreamNotificationCallback = ArgumentCaptor.forClass(RpcListener.NotificationCallback.class); doNothing().when(rpcListener).listenForNotifications(packStreamNotificationCallback.capture()); packStreamRequestCallback = ArgumentCaptor.forClass(RpcListener.RequestCallback.class); doNothing().when(rpcListener).listenForRequests(packStreamRequestCallback.capture()); } }
package org.bigbio.pgatk.pepgenome.io; import org.bigbio.pgatk.pepgenome.common.FastaEntry; import org.bigbio.pgatk.pepgenome.common.Utils; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.Serializable; /** * This fastaparser reads fasta files. it will convert input sequences into * iso-sequences [I, L] will be converted to J * * @author ypriverol * */ public class FastaParser implements Serializable { private static final long serialVersionUID = -4871649120608342251L; //inputstream. private BufferedReader br = null; //current line. private String mLine = ""; //meyers singleton instance. private static FastaParser instance = null; private FastaParser() { } //singleton get_instance method. public static FastaParser get_instance() { if (instance == null) { instance = new FastaParser(); } return instance; } //opens the file public boolean open(String file) throws Exception { if (br == null) { br = new BufferedReader(new FileReader(file)); mLine = ""; } return br.ready(); } //closes the filestream public final void close() { mLine = ""; try { br.close(); } catch (IOException e) { //e.printStackTrace(); } br = null; } //parses and returns the next FASTA entry. public final FastaEntry nextEntry() throws IOException { if (mLine.isEmpty()) { mLine = br.readLine(); } if (mLine == null) { return new FastaEntry("", ""); } String header = mLine; StringBuilder sequenceBuilder = new StringBuilder(); while ((mLine = br.readLine()) != null && !mLine.startsWith(">")) { sequenceBuilder.append(Utils.make_iso_sequence(mLine)); } if (mLine == null || !mLine.startsWith(">")) { mLine = ""; } return new FastaEntry(header, sequenceBuilder.toString()); } }
/* * Copyright 2012-2016 Nathan Freitas * Copyright 2015 str4d * * 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 info.guardianproject.netcipher.client; import android.content.Context; import java.io.IOException; import java.io.InputStream; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import javax.net.ssl.TrustManagerFactory; import ch.boye.httpclientandroidlib.HttpHost; import ch.boye.httpclientandroidlib.conn.ClientConnectionOperator; import ch.boye.httpclientandroidlib.conn.params.ConnRoutePNames; import ch.boye.httpclientandroidlib.conn.scheme.PlainSocketFactory; import ch.boye.httpclientandroidlib.conn.scheme.Scheme; import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry; import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; import ch.boye.httpclientandroidlib.impl.conn.tsccm.ThreadSafeClientConnManager; public class StrongHttpsClient extends DefaultHttpClient { final Context context; private HttpHost proxyHost; private String proxyType; private SocksAwareProxyRoutePlanner routePlanner; private StrongSSLSocketFactory sFactory; private SchemeRegistry mRegistry; private final static String TRUSTSTORE_TYPE = "BKS"; private final static String TRUSTSTORE_PASSWORD = "changeit"; /** * @param context the app {@link Context} * @param resid the BKS keystore as a raw resource ID */ public StrongHttpsClient(Context context, int resid) { this.context = context; mRegistry = new SchemeRegistry(); mRegistry.register( new Scheme(TYPE_HTTP, 80, PlainSocketFactory.getSocketFactory())); try { KeyStore keyStore = loadKeyStore(resid); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sFactory = new StrongSSLSocketFactory(context, trustManagerFactory.getTrustManagers(), keyStore, TRUSTSTORE_PASSWORD); mRegistry.register(new Scheme("https", 443, sFactory)); } catch (Exception e) { throw new AssertionError(e); } } private KeyStore loadKeyStore(int resid) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore trustStore = KeyStore.getInstance(TRUSTSTORE_TYPE); // load our bundled cacerts from raw assets InputStream in = context.getResources().openRawResource(resid); trustStore.load(in, TRUSTSTORE_PASSWORD.toCharArray()); return trustStore; } public StrongHttpsClient(Context context, KeyStore keystore) { this.context = context; mRegistry = new SchemeRegistry(); mRegistry.register( new Scheme(TYPE_HTTP, 80, PlainSocketFactory.getSocketFactory())); try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); sFactory = new StrongSSLSocketFactory(context, trustManagerFactory.getTrustManagers(), keystore, TRUSTSTORE_PASSWORD); mRegistry.register(new Scheme("https", 443, sFactory)); } catch (Exception e) { throw new AssertionError(e); } } @Override protected ThreadSafeClientConnManager createClientConnectionManager() { return new ThreadSafeClientConnManager(getParams(), mRegistry) { @Override protected ClientConnectionOperator createConnectionOperator( SchemeRegistry schreg) { return new SocksAwareClientConnOperator(schreg, proxyHost, proxyType, routePlanner); } }; } public void useProxy(boolean enableTor, String type, String host, int port) { if (enableTor) { this.proxyType = type; if (type.equalsIgnoreCase(TYPE_SOCKS)) { proxyHost = new HttpHost(host, port); } else { proxyHost = new HttpHost(host, port, type); getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); } } else { getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); proxyHost = null; } } public void disableProxy() { getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY); proxyHost = null; } public void useProxyRoutePlanner(SocksAwareProxyRoutePlanner proxyRoutePlanner) { routePlanner = proxyRoutePlanner; setRoutePlanner(proxyRoutePlanner); } /** * NOT ADVISED, but some sites don't yet have latest protocols and ciphers available, and some * apps still need to support them * https://dev.guardianproject.info/issues/5644 */ public void enableSSLCompatibilityMode() { sFactory.setEnableStongerDefaultProtocalVersion(false); sFactory.setEnableStongerDefaultSSLCipherSuite(false); } public final static String TYPE_SOCKS = "socks"; public final static String TYPE_HTTP = "http"; }
/* * Copyright (C) 2012 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.util; import java.lang.reflect.Constructor; public class ExceptionUtils { private ExceptionUtils() { throw new AssertionError("Not instantiable: " + ExceptionUtils.class); } public static <T extends Exception, S extends Exception> T wrap(S e, Class<T> clazz) { if (clazz.isAssignableFrom(e.getClass())) { return clazz.cast(e); } try { Constructor<T> constructor = clazz.getConstructor(Throwable.class); // get the exception constructor with one argument return constructor.newInstance(e); } catch (RuntimeException exception) { throw exception; } catch (Exception exception) { throw new RuntimeException(exception); } } }
/** * Copyright (c) 2011 Michael Kutschke. * 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: * Michael Kutschke - initial API and implementation. */ package org.eclipse.recommenders.internal.jayes.util; /** * Disjoint Set Datastructure, uses Union by Rank and Path Compression heuristics. * * @see "Efficiency of a Good But Not Linear Set Union Algorithm" (Tarjan, 1975) */ public class UnionFind { private UnionFind parent = this; private int rank = 0; /** * @return the set that contains this element */ public UnionFind find() { if (parent == this) { return this; } parent = parent.find(); return parent; } /** * Unites the sets. In equal rank case, the other set is chosen as the new root. */ public void merge(final UnionFind other) { final UnionFind root = find(); final UnionFind root2 = other.find(); if (root == root2) { return; } if (root.rank == root2.rank) { root2.rank++; } if (root.rank > root2.rank) { root2.parent = root; } else { root.parent = root2; } } /** * @return upper bound for the height of the tree rooted at this element */ public int rank() { return rank; } public static UnionFind[] createArray(int size) { final UnionFind[] sets = new UnionFind[size]; for (int i = 0; i < sets.length; i++) { sets[i] = new UnionFind(); } return sets; } }
/* * Copyright 2013 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.sramp.ui.client.local.pages.ontologies; import java.util.Iterator; import java.util.List; import javax.annotation.PostConstruct; import javax.enterprise.context.Dependent; import javax.enterprise.inject.Instance; import javax.inject.Inject; import org.overlord.commons.gwt.client.local.widgets.UnorderedListPanel; import org.overlord.sramp.ui.client.local.ClientMessages; import org.overlord.sramp.ui.client.shared.beans.OntologySummaryBean; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.HasSelectionHandlers; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.Widget; /** * The Ontology summaries panel. * * @author Brett Meyer */ @Dependent public class OntologySummaryPanel extends FlowPanel implements HasValue<List<OntologySummaryBean>>, HasSelectionHandlers<OntologySummaryBean> { List<OntologySummaryBean> value = null; OntologySummaryPanelItem selected = null; @Inject ClientMessages i18n; @Inject Instance<OntologySummaryPanelItem> itemFactory; @Inject FlowPanel header; @Inject UnorderedListPanel items; /** * Constructor. */ public OntologySummaryPanel() { } /** * Called after the widget is created. */ @PostConstruct protected void postConstruct() { setStyleName("ontologies-canvas"); //$NON-NLS-1$ header.getElement().setClassName("sramp-ontology-box-header"); //$NON-NLS-1$ header.getElement().setInnerText(i18n.format("ontologies.ontologies")); items.setStyleName("nav"); //$NON-NLS-1$ items.addStyleName("nav-pills"); //$NON-NLS-1$ items.addStyleName("nav-stacked"); //$NON-NLS-1$ add(header); add(items); } /** * @see com.google.gwt.event.logical.shared.HasValueChangeHandlers#addValueChangeHandler(com.google.gwt.event.logical.shared.ValueChangeHandler) */ @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<List<OntologySummaryBean>> handler) { return addHandler(handler, ValueChangeEvent.getType()); } /** * @see com.google.gwt.user.client.ui.HasValue#getValue() */ @Override public List<OntologySummaryBean> getValue() { return value; } /** * @see com.google.gwt.user.client.ui.HasValue#setValue(java.lang.Object) */ @Override public void setValue(List<OntologySummaryBean> value) { setValue(value, false); } /** * @see com.google.gwt.user.client.ui.HasValue#setValue(java.lang.Object, boolean) */ @Override public void setValue(List<OntologySummaryBean> value, boolean fireEvents) { this.value = value; if (fireEvents) { ValueChangeEvent.fire(this, value); } items.clear(); for (OntologySummaryBean ontologyClass : value) { OntologySummaryPanelItem item = createItem(ontologyClass); items.add(item); } } /** * Creates an item from the given ontology class bean. * @param ontologyClass */ private OntologySummaryPanelItem createItem(OntologySummaryBean ontologyClass) { final OntologySummaryPanelItem item = itemFactory.get(); item.addValueChangeHandler(new ValueChangeHandler<OntologySummaryBean>() { @Override public void onValueChange(ValueChangeEvent<OntologySummaryBean> event) { // If the event value is null, that means we should remove the item. if (event.getValue() == null) { removeItem(item); } ValueChangeEvent.fire(OntologySummaryPanel.this, OntologySummaryPanel.this.value); } }); item.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { selectItem(item); } }); item.setValue(ontologyClass); return item; } /** * Removes the ontology item/class. This removes it both from the value {@link List} * as well as from the UI. * @param item */ protected void removeItem(OntologySummaryPanelItem item) { // When deleting the currently selected item, make sure to fire a // "deselected" event so that any forward tiers are removed from the UI. if (item == selected) { selected = null; SelectionEvent.fire(this, null); } items.remove(item); value.remove(item.getValue()); } /** * Selects a specific item in the tier. * @param item */ protected void selectItem(OntologySummaryPanelItem item) { OntologySummaryPanelItem oldSelection = selected; OntologySummaryPanelItem newSelection = item; if (oldSelection != null) { oldSelection.getElement().removeClassName("active"); //$NON-NLS-1$ oldSelection.hideActions(); } if (oldSelection == newSelection) { selected = null; SelectionEvent.fire(this, null); } else { newSelection.getElement().addClassName("active"); //$NON-NLS-1$ selected = newSelection; OntologySummaryBean bean = selected.getValue(); SelectionEvent.fire(this, bean); } } /** * Restores a selected item by UUID. Useful when OntologiesPage needs to completely replace the ontologies * after a new one has been uploaded. * * @param uuid */ public void restoreSelectedItem(String uuid) { Iterator<Widget> itr = items.iterator(); while (itr.hasNext()) { OntologySummaryPanelItem item = (OntologySummaryPanelItem) itr.next(); if (item.getValue().getUuid() != null && item.getValue().getUuid().equals(uuid)) { item.getElement().addClassName("active"); //$NON-NLS-1$ selected = item; selected.showActions(); // no need to re-fire the event } } } /** * @see com.google.gwt.event.logical.shared.HasSelectionHandlers#addSelectionHandler(com.google.gwt.event.logical.shared.SelectionHandler) */ @Override public HandlerRegistration addSelectionHandler(SelectionHandler<OntologySummaryBean> handler) { return addHandler(handler, SelectionEvent.getType()); } public OntologySummaryBean getSelectedOntology() { return selected == null ? null : selected.getValue(); } }
package com.dolphpire.api.action.igaccount.addAccount; public class LinkIGAccountAction { private LinkIGAccount mLinkIGAccount; public LinkIGAccountAction() { this.mLinkIGAccount = new LinkIGAccount(); } public LinkIGAccountAction withIGID(long name) { this.mLinkIGAccount.setIGID(String.valueOf(name)); return this; } public LinkIGAccountAction withPassword(String password) { this.mLinkIGAccount.setPassword(password.equals("") ? "null" : password); return this; } public LinkIGAccountAction withUsername(String username) { this.mLinkIGAccount.setUsername(username.equals("") ? "null" : username); return this; } public LinkIGAccountAction withProfilePicture(String profile_picture) { this.mLinkIGAccount.setProfilePicture(profile_picture.equals("") ? "null" : profile_picture); return this; } public LinkIGAccountAction isPrivate(boolean is_private) { this.mLinkIGAccount.setIsPrivate(String.valueOf(is_private ? 1 : 0)); return this; } public LinkIGAccount set() { return mLinkIGAccount; } }
package org.albianj.persistence.object; public interface IRunningStorageAttribute { IStorageAttribute getStorageAttribute(); void setStorageAttribute(IStorageAttribute sa); String getDatabase(); void setDatabase(String database); }
package io.contek.invoker.binancespot.api.websocket.market; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.contek.invoker.binancespot.api.websocket.common.WebSocketCommandConfirmation; import io.contek.invoker.commons.websocket.AnyWebSocketMessage; import io.contek.invoker.commons.websocket.IWebSocketMessageParser; import javax.annotation.concurrent.Immutable; @Immutable public final class MarketWebSocketMessageParser implements IWebSocketMessageParser { private final Gson gson = new Gson(); static MarketWebSocketMessageParser getInstance() { return MarketWebSocketMessageParser.InstanceHolder.INSTANCE; } @Override public AnyWebSocketMessage parse(String text) { JsonElement json = gson.fromJson(text, JsonElement.class); if (!json.isJsonObject()) { throw new IllegalArgumentException(text); } JsonObject obj = json.getAsJsonObject(); if (obj.has("id")) { return toRequestConfirmation(obj); } if (obj.has("stream")) { return toStreamData(obj); } return toBookTicker(obj); } private AnyWebSocketMessage toRequestConfirmation(JsonObject obj) { return gson.fromJson(obj, WebSocketCommandConfirmation.class); } private AnyWebSocketMessage toStreamData(JsonObject obj) { String stream = obj.get("stream").getAsString(); if (stream.endsWith("@aggTrade")) { return gson.fromJson(obj, AggTradeChannel.Message.class); } if (stream.endsWith("@depth@100ms")) { return gson.fromJson(obj, DepthUpdateChannel.Message.class); } throw new IllegalStateException(); } private AnyWebSocketMessage toBookTicker(JsonObject obj) { return gson.fromJson(obj, BookTickerEvent.class); } private MarketWebSocketMessageParser() {} @Immutable private static class InstanceHolder { private static final MarketWebSocketMessageParser INSTANCE = new MarketWebSocketMessageParser(); private InstanceHolder() {} } }
package Java_Array_String; /** Program to find the highest mark in 6 subject. */ import java.util.Scanner; import java.util.Arrays; public class highestMark { public static int highestM() { Scanner SC= new Scanner(System.in); int [] marks = new int[6]; System.out.println("Enter the marks:"); for(int i=0;i<marks.length;i++) { marks[i]=SC.nextInt(); if(marks[i]<0 || marks[i]>100) return -1; } Arrays.sort(marks); //Inbuilt function return marks[5]; } public static void main(String[] args) { int mark=highestM(); if(mark>=0) System.out.println("Highest mark is "+mark); else System.out.println("Invalid Mark"); } }
/* * Copyright (c) 2018, DThompson * All rights reserved. * * Licensed under: Creative Commons Attribution-NonCommercial 4.0 International Public License * See LICENSE.TXT included with this code to read the full license agreement. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package PolyGlot; import PolyGlot.CustomControls.GrammarChapNode; import PolyGlot.CustomControls.GrammarSectionNode; import PolyGlot.CustomControls.PGrammarPane; import java.awt.Color; import java.util.List; import java.util.Map.Entry; import javax.swing.JTextPane; import org.junit.AfterClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.BeforeClass; /** * * @author DThompson */ public class FormattedTextHelperTest { final DictCore core; private final static String BLACK = "black"; private final static String RED = "red"; private final static String GRAY = "gray"; private final static String GREEN = "green"; private final static String YELLOW = "yellow"; private final static String BLUE = "blue"; public FormattedTextHelperTest() throws Exception { core = new DictCore(); core.readFile("test/TestResources/Lodenkur_TEST.pgd"); } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Test public void testHTMLLineBreakParseNoBreaks() { String testVal = "golly gee"; String expectedVal = "golly gee"; String result = FormattedTextHelper.HTMLLineBreakParse(testVal); assertEquals(expectedVal, result); } @Test public void testHTMLLineBreakParseBr() { String testVal = "<br>golly gee"; String expectedVal = "<br>golly gee"; String result = FormattedTextHelper.HTMLLineBreakParse(testVal); assertEquals(expectedVal, result); } @Test public void testHTMLLineBreakParseNewlineThenBr() { String testVal = "x\n<br>golly gee"; String expectedVal = "x<br><br>golly gee"; String result = FormattedTextHelper.HTMLLineBreakParse(testVal); assertEquals(expectedVal, result); } @Test public void testHTMLLineBreakParseBrThenNewline() { String testVal = "<br>\ngolly gee"; String expectedVal = "<br>golly gee"; String result = FormattedTextHelper.HTMLLineBreakParse(testVal); assertEquals(expectedVal, result); } @Test public void testRestoreFromString() throws Exception { String testVal = "<font face=\"Lucida Grande\"size=\"12\"color=\"black\">Lodenkur is a language that technically does not have pronunciation in any way that we are able to perceive. It is a language \"spoken\" via radio frequency, similar to what we might think of as telepathy. This having been said, it is useful to have a way to speak and vocalize this language in a more familiar way, as a helpful mnemonic to remember vocabulary and to allow better interaction with it. Below is an attempt to convert this it a more human-friendly form. </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"18\"color=\"black\">A Basic Explanation of Characters</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> There are two types of characters, the tonal and the non-tonal. Tonal characters can be pronounced in one of three ways. The first comes with no special markers, and is flat. The second has a marker on the left side. This is pronounced with a rising tone. The third has a marker on the right side. This is pronounced with a descending tone. </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\">Flat Characters: </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">1234567890</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\">Rising Tone Characters: </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">qwertyuiop</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\">Falling Tone Characters: </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">asdfghjkl;</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> The second type of characters are not tonal. They are pronounced in ways the precludes rising or falling tone. In KLA, you will never see more than two of these consecutively, as this would be difficult or impossible to pronounce. </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\">Non-Tonal Characters: </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">zxcvb</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\">Pronunciation </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> Below is a basic pronunciation guide for each of the characters. These pronunciations do not account for tone, which is explained in greater detail later in this document. Rising and falling tones do not affect the pronunciation of characters. All pronunciations are in IPA style. </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">z</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : t - t - (today) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">x</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : th - θ (theigh) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">1</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : ha - hɑː (hall) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">2</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : wa - wɑː (water) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">3</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : no - noʊ (no) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">4</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : reh - ʀə (red) (note: french, guttural R) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">5</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : lo - loʊ (load) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">6</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : ku - kuː (cocoon) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">7</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : mi - miː (me) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">8</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : de - dɛ (debt) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">9</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : ya - jæ (yak) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">0</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : si - siː (see) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">c</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : sh - ʃ (shy) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">v</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : f - f (fan) </font><font face=\"Kukun_Linear_A\"size=\"18\"color=\"black\">b</font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> : ng - ŋ (sang) </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> Neutral tone is typically segmented by sentence. A speaker has their \"neutral\" voice tone, which is where each sentence begins. A character that is atonal or flat will leave the speaker's voice in the tone in which it began. A character with rising or falling tone however, will raise or lower the speaker's tone before the character is pronounced. This new tone replaces the base tone as the speaker continues. This results in a lyrical sound to speech, tone rising and falling through phrases and sentences. </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> </font><font face=\"Lucida Grande\"size=\"12\"color=\"black\"> In cases where the tone is too low or too high for a speaker to continue, they may return to the neutral tone between words by leaving a stressed pause between the words, although this is considered indicitive of poorly considered phrasing. Typically a speaker should manage this themselves. Tone may be raised or lowered as much as the speaker likes on an appropriate character, and the meaning remains the same. In this way, a speaker should take care that their words do not tonally escape them. Sentences tend to rise in tone as they continue, rather than dipping or staying in the same tonal position.</font>"; JTextPane pane = new JTextPane(); FormattedTextHelper.restoreFromString(testVal, pane, core); assertEquals(pane.getText(), "Lodenkur is a language that technically does not have pronunciation in any way that we are able to perceive. It is a language \"spoken\" via radio frequency, similar to what we might think of as telepathy. This having been said, it is useful to have a way to speak and vocalize this language in a more familiar way, as a helpful mnemonic to remember vocabulary and to allow better interaction with it. Below is an attempt to convert this it a more human-friendly form. A Basic Explanation of Characters There are two types of characters, the tonal and the non-tonal. Tonal characters can be pronounced in one of three ways. The first comes with no special markers, and is flat. The second has a marker on the left side. This is pronounced with a rising tone. The third has a marker on the right side. This is pronounced with a descending tone. Flat Characters: 1234567890 Rising Tone Characters: qwertyuiop Falling Tone Characters: asdfghjkl; The second type of characters are not tonal. They are pronounced in ways the precludes rising or falling tone. In KLA, you will never see more than two of these consecutively, as this would be difficult or impossible to pronounce. Non-Tonal Characters: zxcvb Pronunciation Below is a basic pronunciation guide for each of the characters. These pronunciations do not account for tone, which is explained in greater detail later in this document. Rising and falling tones do not affect the pronunciation of characters. All pronunciations are in IPA style. z : t - t - (today) x : th - θ (theigh) 1 : ha - hɑː (hall) 2 : wa - wɑː (water) 3 : no - noʊ (no) 4 : reh - ʀə (red) (note: french, guttural R) 5 : lo - loʊ (load) 6 : ku - kuː (cocoon) 7 : mi - miː (me) 8 : de - dɛ (debt) 9 : ya - jæ (yak) 0 : si - siː (see) c : sh - ʃ (shy) v : f - f (fan) b : ng - ŋ (sang) Neutral tone is typically segmented by sentence. A speaker has their \"neutral\" voice tone, which is where each sentence begins. A character that is atonal or flat will leave the speaker's voice in the tone in which it began. A character with rising or falling tone however, will raise or lower the speaker's tone before the character is pronounced. This new tone replaces the base tone as the speaker continues. This results in a lyrical sound to speech, tone rising and falling through phrases and sentences. In cases where the tone is too low or too high for a speaker to continue, they may return to the neutral tone between words by leaving a stressed pause between the words, although this is considered indicitive of poorly considered phrasing. Typically a speaker should manage this themselves. Tone may be raised or lowered as much as the speaker likes on an appropriate character, and the meaning remains the same. In this way, a speaker should take care that their words do not tonally escape them. Sentences tend to rise in tone as they continue, rather than dipping or staying in the same tonal position."); } @Test public void testGetSectionTextFontSpecifec() { GrammarChapNode chap = core.getGrammarManager().getChapters()[0]; String sectionText = ((GrammarSectionNode)chap.getFirstChild()).getSectionText(); List<Entry<String, PFontInfo>> results = FormattedTextHelper.getSectionTextFontSpecifec(sectionText, core); Entry<String, PFontInfo> title = results.get(0); Entry<String, PFontInfo> lodenkurExample = results.get(6); assertEquals(results.size(), 12); assertEquals(title.getKey(), "LODENKUR"); assertEquals(title.getValue().awtColor, Color.black); assertEquals(title.getValue().awtFont.getName(), "Lucida Grande"); assertEquals(title.getValue().size, 28); assertEquals(lodenkurExample.getKey(), "6f"); assertEquals(lodenkurExample.getValue().awtColor, Color.black); assertEquals(lodenkurExample.getValue().awtFont.getName(), "Kukun_Linear_A Regular"); assertEquals(lodenkurExample.getValue().size, 18); } @Test public void testStorageFormat() throws Exception { PGrammarPane pane = new PGrammarPane(core); GrammarChapNode chap = core.getGrammarManager().getChapters()[0]; String sectionText = ((GrammarSectionNode)chap.getChildAt(1)).getSectionText(); FormattedTextHelper.restoreFromString(sectionText, pane, core); assertEquals(sectionText, FormattedTextHelper.storageFormat(pane)); } @Test public void testColorToText() { assertEquals(FormattedTextHelper.colorToText(Color.black), BLACK); assertEquals(FormattedTextHelper.colorToText(Color.red), RED); assertEquals(FormattedTextHelper.colorToText(Color.green), GREEN); assertEquals(FormattedTextHelper.colorToText(Color.yellow), YELLOW); assertEquals(FormattedTextHelper.colorToText(Color.blue), BLUE); assertEquals(FormattedTextHelper.colorToText(Color.gray), GRAY); } @Test public void testTextToColor() { assertEquals(FormattedTextHelper.textToColor(BLACK), Color.black); assertEquals(FormattedTextHelper.textToColor(RED), Color.red); assertEquals(FormattedTextHelper.textToColor(GREEN), Color.green); assertEquals(FormattedTextHelper.textToColor(YELLOW), Color.yellow); assertEquals(FormattedTextHelper.textToColor(BLUE), Color.blue); assertEquals(FormattedTextHelper.textToColor(GRAY), Color.gray); } @Test public void testHTMLLineBreakParse() { String initial = "hello!\nto you!"; String expected = "hello!<br>to you!"; assertEquals(FormattedTextHelper.HTMLLineBreakParse(initial), expected); } @Test public void testGetTextBody() { String initial = "<html><head>adhgvasdjvsh</head><body>Zip zop!<br>Have a hyperlink! <a href =\"poop\">here!</a></body></html>"; String expected = "Zip zop!Have a hyperlink! here!"; assertEquals(FormattedTextHelper.getTextBody(initial), expected); } /** * Test of swtColorToItextColor method, of class FormattedTextHelper. */ @Test public void testSwtColorToItextColor() { Color awtc = Color.darkGray; com.itextpdf.kernel.colors.Color expResult = com.itextpdf.kernel.colors.ColorConstants.DARK_GRAY; com.itextpdf.kernel.colors.Color result = FormattedTextHelper.swtColorToItextColor(awtc); assertEquals(expResult, result); } }
package org.apache.helix.integration.messaging; /* * 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.StringWriter; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.UUID; import org.apache.helix.Criteria; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.InstanceType; import org.apache.helix.PropertyKey; import org.apache.helix.zookeeper.datamodel.ZNRecord; import org.apache.helix.integration.common.ZkStandAloneCMTestBase; import org.apache.helix.manager.zk.DefaultSchedulerMessageHandlerFactory; import org.apache.helix.model.ClusterConstraints.ConstraintType; import org.apache.helix.model.ConstraintItem; import org.apache.helix.model.Message; import org.apache.helix.model.Message.MessageState; import org.apache.helix.model.Message.MessageType; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; import org.testng.Assert; import org.testng.annotations.Test; public class TestSchedulerMsgContraints extends ZkStandAloneCMTestBase { @Test public void testSchedulerMsgContraints() throws Exception { TestSchedulerMessage.TestMessagingHandlerFactoryLatch factory = new TestSchedulerMessage.TestMessagingHandlerFactoryLatch(); HelixManager manager = null; for (int i = 0; i < NODE_NR; i++) { _participants[i].getMessagingService().registerMessageHandlerFactory( factory.getMessageType(), factory); _participants[i].getMessagingService().registerMessageHandlerFactory( factory.getMessageType(), factory); manager = _participants[i]; // _startCMResultMap.get(hostDest)._manager; } Message schedulerMessage = new Message(MessageType.SCHEDULER_MSG + "", UUID.randomUUID().toString()); schedulerMessage.setTgtSessionId("*"); schedulerMessage.setTgtName("CONTROLLER"); // TODO: change it to "ADMIN" ? schedulerMessage.setSrcName("CONTROLLER"); // Template for the individual message sent to each participant Message msg = new Message(factory.getMessageType(), "Template"); msg.setTgtSessionId("*"); msg.setMsgState(MessageState.NEW); // Criteria to send individual messages Criteria cr = new Criteria(); cr.setInstanceName("localhost_%"); cr.setRecipientInstanceType(InstanceType.PARTICIPANT); cr.setSessionSpecific(false); cr.setResource("%"); cr.setPartition("%"); ObjectMapper mapper = new ObjectMapper(); SerializationConfig serializationConfig = mapper.getSerializationConfig(); serializationConfig.set(SerializationConfig.Feature.INDENT_OUTPUT, true); StringWriter sw = new StringWriter(); mapper.writeValue(sw, cr); String crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); schedulerMessage.getRecord().setMapField("MessageTemplate", msg.getRecord().getSimpleFields()); schedulerMessage.getRecord().setSimpleField("TIMEOUT", "-1"); schedulerMessage.getRecord().setSimpleField("WAIT_ALL", "true"); schedulerMessage.getRecord().setSimpleField( DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE, "TestSchedulerMsgContraints"); Criteria cr2 = new Criteria(); cr2.setRecipientInstanceType(InstanceType.CONTROLLER); cr2.setInstanceName("*"); cr2.setSessionSpecific(false); TestSchedulerMessage.MockAsyncCallback callback = new TestSchedulerMessage.MockAsyncCallback(); mapper = new ObjectMapper(); serializationConfig = mapper.getSerializationConfig(); serializationConfig.set(SerializationConfig.Feature.INDENT_OUTPUT, true); sw = new StringWriter(); mapper.writeValue(sw, cr); HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = helixDataAccessor.keyBuilder(); // Set constraints that only 1 message per participant Map<String, String> constraints = new TreeMap<String, String>(); constraints.put("MESSAGE_TYPE", "STATE_TRANSITION"); constraints.put("TRANSITION", "OFFLINE-COMPLETED"); constraints.put("CONSTRAINT_VALUE", "1"); constraints.put("INSTANCE", ".*"); manager.getClusterManagmentTool().setConstraint(manager.getClusterName(), ConstraintType.MESSAGE_CONSTRAINT, "constraint1", new ConstraintItem(constraints)); // Send scheduler message crString = sw.toString(); schedulerMessage.getRecord().setSimpleField("Criteria", crString); manager.getMessagingService().sendAndWait(cr2, schedulerMessage, callback, -1); String msgId = callback._message.getResultMap() .get(DefaultSchedulerMessageHandlerFactory.SCHEDULER_MSG_ID); for (int j = 0; j < 10; j++) { Thread.sleep(200); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId); ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); if (statusUpdate.getMapFields().containsKey("SentMessageCount")) { Assert.assertEquals( statusUpdate.getMapFields().get("SentMessageCount").get("MessageCount"), "" + (_PARTITIONS * 3)); break; } } for (int i = 0; i < _PARTITIONS * 3 / 5; i++) { for (int j = 0; j < 10; j++) { Thread.sleep(300); if (factory._messageCount == 5 * (i + 1)) break; } Thread.sleep(300); Assert.assertEquals(factory._messageCount, 5 * (i + 1)); factory.signal(); // System.err.println(i); } for (int j = 0; j < 10; j++) { Thread.sleep(200); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId); ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); if (statusUpdate.getMapFields().containsKey("Summary")) { break; } } Assert.assertEquals(_PARTITIONS, factory._results.size()); PropertyKey controllerTaskStatus = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.name(), msgId); ZNRecord statusUpdate = helixDataAccessor.getProperty(controllerTaskStatus).getRecord(); Assert.assertTrue(statusUpdate.getMapField("SentMessageCount").get("MessageCount") .equals("" + (_PARTITIONS * 3))); int messageResultCount = 0; for (String key : statusUpdate.getMapFields().keySet()) { if (key.startsWith("MessageResult ")) { messageResultCount++; } } Assert.assertEquals(messageResultCount, _PARTITIONS * 3); int count = 0; for (Set<String> val : factory._results.values()) { count += val.size(); } Assert.assertEquals(count, _PARTITIONS * 3); manager.getClusterManagmentTool().removeConstraint(manager.getClusterName(), ConstraintType.MESSAGE_CONSTRAINT, "constraint1"); } }
package liquibase.integration.commandline; import liquibase.*; import liquibase.change.CheckSum; import liquibase.changelog.ChangeLogParameters; import liquibase.changelog.visitor.ChangeExecListener; import liquibase.command.AbstractSelfConfiguratingCommand; import liquibase.command.CommandFactory; import liquibase.command.LiquibaseCommand; import liquibase.command.core.*; import liquibase.configuration.GlobalConfiguration; import liquibase.configuration.LiquibaseConfiguration; import liquibase.database.Database; import liquibase.diff.compare.CompareControl; import liquibase.diff.output.DiffOutputControl; import liquibase.diff.output.ObjectChangeFilter; import liquibase.diff.output.StandardObjectChangeFilter; import liquibase.exception.*; import liquibase.license.*; import liquibase.lockservice.LockService; import liquibase.lockservice.LockServiceFactory; import liquibase.logging.Logger; import liquibase.resource.ClassLoaderResourceAccessor; import liquibase.resource.CompositeResourceAccessor; import liquibase.resource.FileSystemResourceAccessor; import liquibase.resource.ResourceAccessor; import liquibase.ui.ConsoleUIService; import liquibase.util.ISODateFormat; import liquibase.util.LiquibaseUtil; import liquibase.util.StringUtil; import liquibase.util.xml.XMLResourceBundle; import liquibase.util.xml.XmlResourceBundleControl; import java.io.*; import java.lang.reflect.Field; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Paths; import java.security.AccessController; import java.security.PrivilegedAction; import java.text.MessageFormat; import java.text.ParseException; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.logging.*; import static java.util.ResourceBundle.getBundle; /** * Class for executing Liquibase via the command line. */ public class Main { private static final String ERRORMSG_UNEXPECTED_PARAMETERS = "unexpected.command.parameters"; private static final Logger LOG = Scope.getCurrentScope().getLog(Main.class); private static ResourceBundle coreBundle = getBundle("liquibase/i18n/liquibase-core"); private static XMLResourceBundle commandLineHelpBundle = ((XMLResourceBundle) getBundle ("liquibase/i18n/liquibase-commandline-helptext", new XmlResourceBundleControl())); protected ClassLoader classLoader; protected String driver; protected String username; protected String password; protected String url; protected String databaseClass; protected String defaultSchemaName; protected String outputDefaultSchema; protected String outputDefaultCatalog; protected String liquibaseCatalogName; protected String liquibaseSchemaName; protected String databaseChangeLogTableName; protected String databaseChangeLogLockTableName; protected String databaseChangeLogTablespaceName; protected String defaultCatalogName; protected String changeLogFile; protected String overwriteOutputFile; protected String classpath; protected String contexts; protected String labels; protected String driverPropertiesFile; protected String propertyProviderClass; protected String changeExecListenerClass; protected String changeExecListenerPropertiesFile; protected Boolean promptForNonLocalDatabase; protected Boolean includeSystemClasspath; protected Boolean strict = Boolean.TRUE; protected String defaultsFile = "liquibase.properties"; protected String diffTypes; protected String changeSetAuthor; protected String changeSetContext; protected String dataOutputDirectory; protected String referenceDriver; protected String referenceUrl; protected String referenceUsername; protected String referencePassword; protected String referenceDefaultCatalogName; protected String referenceDefaultSchemaName; protected String currentDateTimeFunction; protected String command; protected Set<String> commandParams = new LinkedHashSet<>(); protected String logLevel; protected String logFile; protected Map<String, Object> changeLogParameters = new HashMap<>(); protected String outputFile; protected String excludeObjects; protected Boolean includeCatalog; protected String includeObjects; protected Boolean includeSchema; protected Boolean includeTablespace; protected String outputSchemasAs; protected String referenceSchemas; protected String schemas; protected String snapshotFormat; protected String liquibaseProLicenseKey; private boolean liquibaseProLicenseValid = false; private Boolean managingLogConfig = null; private boolean outputsLogMessages = false; protected String sqlFile; protected String delimiter; protected String rollbackScript; private static int[] suspiciousCodePoints = {160, 225, 226, 227, 228, 229, 230, 198, 200, 201, 202, 203, 204, 205, 206, 207, 209, 210, 211, 212, 213, 214, 217, 218, 219, 220, 222, 223, 232, 233, 234, 235, 236, 237, 238, 239, 241, 249, 250, 251, 252, 255, 284, 332, 333, 334, 335, 336, 337, 359, 360, 361, 362, 363, 364, 365, 366, 367, 377, 399, 8192, 8193, 8194, 8196, 8197, 8199, 8200, 8201, 8202, 8203, 8211, 8287 }; protected static class CodePointCheck { public int position; public char ch; } /** * Entry point. This is what gets executes when starting this program from the command line. This is actually * a simple wrapper so that an errorlevel of != 0 is guaranteed in case of an uncaught exception. * * @param args the command line arguments */ public static void main(String[] args) { int errorLevel = 0; try { errorLevel = run(args); } catch (Throwable e) { System.exit(-1); } System.exit(errorLevel); } /** * Process the command line arguments and perform the appropriate main action (update, rollback etc.) * * @param args the command line arguments * @return the errorlevel to be returned to the operating system, e.g. for further processing by scripts * @throws LiquibaseException a runtime exception */ public static int run(String[] args) throws Exception { ConsoleUIService ui = new ConsoleUIService(); Map<String, Object> scopeObjects = new HashMap<>(); scopeObjects.put(Scope.Attr.ui.name(), ui); return Scope.child(scopeObjects, new Scope.ScopedRunnerWithReturn<Integer>() { @Override public Integer run() throws Exception { Main main = new Main(); try { GlobalConfiguration globalConfiguration = LiquibaseConfiguration.getInstance().getConfiguration (GlobalConfiguration.class); if (!globalConfiguration.getShouldRun()) { Scope.getCurrentScope().getUI().sendErrorMessage(( String.format(coreBundle.getString("did.not.run.because.param.was.set.to.false"), LiquibaseConfiguration.getInstance().describeValueLookupLogic( globalConfiguration.getProperty(GlobalConfiguration.SHOULD_RUN))))); return 0; } if ((args.length == 0) || ((args.length == 1) && ("--" + OPTIONS.HELP).equals(args[0]))) { main.printHelp(System.out); return 0; } else if (("--" + OPTIONS.VERSION).equals(args[0])) { main.command = ""; main.parseDefaultPropertyFiles(); Scope.getCurrentScope().getUI().sendMessage(CommandLineUtils.getBanner()); Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("version.number"), LiquibaseUtil.getBuildVersion() )); LicenseService licenseService = Scope.getCurrentScope().getSingleton(LicenseServiceFactory.class).getLicenseService(); if (licenseService != null && main.liquibaseProLicenseKey != null) { Location licenseKeyLocation = new Location("property liquibaseProLicenseKey", LocationType.BASE64_STRING, main.liquibaseProLicenseKey); LicenseInstallResult result = licenseService.installLicense(licenseKeyLocation); if (result.code != 0) { String allMessages = String.join("\n", result.messages); Scope.getCurrentScope().getUI().sendErrorMessage(allMessages); } } if (licenseService != null) { Scope.getCurrentScope().getUI().sendMessage(licenseService.getLicenseInfo()); } Scope.getCurrentScope().getUI().sendMessage(String.format("Running Java under %s (Version %s)", System.getProperties().getProperty("java.home"), System.getProperty("java.version") )); return 0; } // // Look for characters which cannot be handled // for (int i = 0; i < args.length; i++) { CodePointCheck codePointCheck = checkArg(args[i]); if (codePointCheck != null) { String message = "A non-standard character '" + codePointCheck.ch + "' was detected on the command line at position " + (codePointCheck.position + 1) + " of argument number " + (i + 1) + ".\nIf problems occur, please remove the character and try again."; LOG.warning(message); System.err.println(message); } } try { main.parseOptions(args); if (main.command == null) { main.printHelp(System.out); return 0; } } catch (CommandLineParsingException e) { Scope.getCurrentScope().getUI().sendMessage(CommandLineUtils.getBanner()); Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("how.to.display.help")); throw e; } System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] %4$s [%2$s] %5$s%6$s%n"); java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger(""); if (main.logLevel == null) { String defaultLogLevel = System.getProperty("liquibase.log.level"); if (defaultLogLevel == null) { setLogLevel(rootLogger, Level.OFF); } else { setLogLevel(rootLogger, parseLogLevel(defaultLogLevel, ui)); } } else { setLogLevel(rootLogger, parseLogLevel(main.logLevel, ui)); } if (main.logFile != null) { FileHandler fileHandler = new FileHandler(main.logFile, true); fileHandler.setFormatter(new SimpleFormatter()); if (rootLogger.getLevel() == Level.OFF) { fileHandler.setLevel(Level.FINE); } rootLogger.addHandler(fileHandler); for (Handler handler : rootLogger.getHandlers()) { if (handler instanceof ConsoleHandler) { handler.setLevel(Level.OFF); } } } if (main.command != null && main.command.toLowerCase().endsWith("sql")) { ui.setOutputStream(System.err); } LicenseService licenseService = Scope.getCurrentScope().getSingleton(LicenseServiceFactory.class).getLicenseService(); if (licenseService != null) { if (main.liquibaseProLicenseKey == null) { Scope.getCurrentScope().getLog(getClass()).info("No Liquibase Pro license key supplied. Please set liquibaseProLicenseKey on command line or in liquibase.properties to use Liquibase Pro features."); } else { Location licenseKeyLocation = new Location("property liquibaseProLicenseKey", LocationType.BASE64_STRING, main.liquibaseProLicenseKey); LicenseInstallResult result = licenseService.installLicense(licenseKeyLocation); if (result.code != 0) { String allMessages = String.join("\n", result.messages); Scope.getCurrentScope().getUI().sendMessage( allMessages); } else { main.liquibaseProLicenseValid = true; } } // // Check to see if we have an expired license // if (licenseService.daysTilExpiration() < 0) { main.liquibaseProLicenseValid = false; } Scope.getCurrentScope().getUI().sendMessage(licenseService.getLicenseInfo()); } Scope.getCurrentScope().getUI().sendMessage(CommandLineUtils.getBanner()); if (main.commandParams.contains("--help") && (main.command.startsWith("rollbackOneChangeSet") || main.command.startsWith("rollbackOneUpdate") || (main.command.startsWith("diff") && main.isFormattedDiff()))) { //don't need to check setup } else { List<String> setupMessages = main.checkSetup(); if (!setupMessages.isEmpty()) { main.printHelp(setupMessages, isStandardOutputRequired(main.command) ? System.err : System.out); return 1; } } main.applyDefaults(); Scope.child(Scope.Attr.resourceAccessor, new ClassLoaderResourceAccessor(main.configureClassLoader()), () -> { main.doMigration(); if (COMMANDS.UPDATE.equals(main.command)) { Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("update.successful")); } else if (main.command.startsWith(COMMANDS.ROLLBACK)) { Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("rollback.successful")); } else { Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("command.successful"), main.command)); } }); } catch (Throwable e) { String message = e.getMessage(); if (e.getCause() != null) { message = e.getCause().getMessage(); } if (message == null) { message = coreBundle.getString("unknown.reason"); } // At a minimum, log the message. We don't need to print the stack // trace because the logger already did that upstream. try { if (e.getCause() instanceof ValidationFailedException) { ((ValidationFailedException) e.getCause()).printDescriptiveError(System.out); } else { if (main.outputsLogMessages) { Scope.getCurrentScope().getUI().sendErrorMessage((String.format(coreBundle.getString("unexpected.error"), message)), e); } else { Scope.getCurrentScope().getUI().sendMessage((String.format(coreBundle.getString("unexpected.error"), message))); Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("for.more.information.use.loglevel.flag")); //send it to the LOG in case we're using logFile Scope.getCurrentScope().getLog(getClass()).severe((String.format(coreBundle.getString("unexpected.error"), message)), e); } } } catch (IllegalFormatException e1) { e1.printStackTrace(); } throw new LiquibaseException(String.format(coreBundle.getString("unexpected.error"), message), e); } return 0; } }); } protected static void setLogLevel(java.util.logging.Logger logger, java.util.logging.Level level) { logger.setLevel(level); for (Handler handler : logger.getHandlers()) { handler.setLevel(level); } } private static Level parseLogLevel(String logLevelName, ConsoleUIService ui) { logLevelName = logLevelName.toUpperCase(); Level logLevel; if (logLevelName.equals("DEBUG")) { logLevel = Level.FINE; } else if (logLevelName.equals("WARN")) { logLevel = Level.WARNING; } else if (logLevelName.equals("ERROR")) { logLevel = Level.SEVERE; } else { try { logLevel = Level.parse(logLevelName); } catch (IllegalArgumentException e) { ui.sendErrorMessage("Unknown log level " + logLevelName); logLevel = Level.OFF; } } return logLevel; } /** * Warns the user that some logging was suppressed because the --logLevel command line switch was not set high * enough * * @param outputLoggingEnabled if a warning should be printed * @return the warning message (if outputLoggingEnabled==true), an empty String otherwise */ private static String generateLogLevelWarningMessage(boolean outputLoggingEnabled) { if (outputLoggingEnabled) { return ""; } else { return "\n\n" + coreBundle.getString("for.more.information.use.loglevel.flag"); } } /** * Splits a String of the form "key=value" into the respective parts. * * @param arg The String expression to split * @return An array of exactly 2 entries * @throws CommandLineParsingException if the string cannot be split into exactly 2 parts */ // What the number 2 stands for is obvious from the context @SuppressWarnings("squid:S109") private static String[] splitArg(String arg) throws CommandLineParsingException { String[] splitArg = arg.split("=", 2); if (splitArg.length < 2) { throw new CommandLineParsingException( String.format(coreBundle.getString("could.not.parse.expression"), arg) ); } splitArg[0] = splitArg[0].replaceFirst("--", ""); return splitArg; } /** * Returns true if the given command requires stdout * * @param command the command to check * @return true if stdout needs for a command, false if not */ private static boolean isStandardOutputRequired(String command) { return COMMANDS.SNAPSHOT.equalsIgnoreCase(command) || COMMANDS.SNAPSHOT_REFERENCE.equalsIgnoreCase(command) || COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(command) || COMMANDS.MARK_NEXT_CHANGESET_RAN_SQL.equalsIgnoreCase(command) || COMMANDS.UPDATE_COUNT_SQL.equalsIgnoreCase(command) || COMMANDS.UPDATE_TO_TAG_SQL.equalsIgnoreCase(command) || COMMANDS.UPDATE_SQL.equalsIgnoreCase(command) || COMMANDS.ROLLBACK_SQL.equalsIgnoreCase(command) || COMMANDS.ROLLBACK_TO_DATE_SQL.equalsIgnoreCase(command) || COMMANDS.ROLLBACK_COUNT_SQL.equalsIgnoreCase(command) || COMMANDS.FUTURE_ROLLBACK_SQL.equalsIgnoreCase(command) || COMMANDS.FUTURE_ROLLBACK_COUNT_SQL.equalsIgnoreCase(command) || COMMANDS.FUTURE_ROLLBACK_FROM_TAG_SQL.equalsIgnoreCase(command); } /** * Returns true if the parameter --changeLogFile is requited for a given command * * @param command the command to test * @return true if a ChangeLog is required, false if not. */ private static boolean isChangeLogRequired(String command) { return command.toLowerCase().startsWith(COMMANDS.UPDATE) || (command.toLowerCase().startsWith(COMMANDS.ROLLBACK) && (!command.equalsIgnoreCase(COMMANDS.ROLLBACK_ONE_CHANGE_SET) && !command.equalsIgnoreCase(COMMANDS.ROLLBACK_ONE_UPDATE))) || COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(command) || COMMANDS.STATUS.equalsIgnoreCase(command) || COMMANDS.VALIDATE.equalsIgnoreCase(command) || COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(command) || COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(command) || COMMANDS.GENERATE_CHANGELOG.equalsIgnoreCase(command) || COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(command) || COMMANDS.ROLLBACK_ONE_CHANGE_SET.equalsIgnoreCase(command) || COMMANDS.ROLLBACK_ONE_UPDATE.equalsIgnoreCase(command); } /** * Returns true if the given arg is a valid main command of Liquibase. * * @param arg the String to test * @return true if it is a valid main command, false if not */ private static boolean isCommand(String arg) { return COMMANDS.MIGRATE.equals(arg) || COMMANDS.MIGRATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE.equalsIgnoreCase(arg) || COMMANDS.UPDATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_COUNT.equalsIgnoreCase(arg) || COMMANDS.UPDATE_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TO_TAG.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TO_TAG_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_TO_DATE.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_COUNT.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_TO_DATE_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_COUNT_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_TO_TAG_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TESTING_ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.TAG.equalsIgnoreCase(arg) || COMMANDS.TAG_EXISTS.equalsIgnoreCase(arg) || COMMANDS.LIST_LOCKS.equalsIgnoreCase(arg) || COMMANDS.HISTORY.equalsIgnoreCase(arg) || COMMANDS.DROP_ALL.equalsIgnoreCase(arg) || COMMANDS.RELEASE_LOCKS.equalsIgnoreCase(arg) || COMMANDS.STATUS.equalsIgnoreCase(arg) || COMMANDS.UNEXPECTED_CHANGESETS.equalsIgnoreCase(arg) || COMMANDS.VALIDATE.equalsIgnoreCase(arg) || COMMANDS.HELP.equalsIgnoreCase(arg) || COMMANDS.DIFF.equalsIgnoreCase(arg) || COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(arg) || COMMANDS.GENERATE_CHANGELOG.equalsIgnoreCase(arg) || COMMANDS.SNAPSHOT.equalsIgnoreCase(arg) || COMMANDS.SNAPSHOT_REFERENCE.equalsIgnoreCase(arg) || COMMANDS.EXECUTE_SQL.equalsIgnoreCase(arg) || COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(arg) || COMMANDS.CLEAR_CHECKSUMS.equalsIgnoreCase(arg) || COMMANDS.DB_DOC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_ONE_CHANGE_SET.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_ONE_CHANGE_SET_SQL.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_ONE_UPDATE.equalsIgnoreCase(arg) || COMMANDS.ROLLBACK_ONE_UPDATE_SQL.equalsIgnoreCase(arg); } /** * Returns true if the given main command arg needs no special parameters. * * @param arg the main command to test * @return true if arg is a valid main command and needs no special parameters, false in all other cases */ private static boolean isNoArgCommand(String arg) { return COMMANDS.MIGRATE.equals(arg) || COMMANDS.MIGRATE_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE.equalsIgnoreCase(arg) || COMMANDS.UPDATE_SQL.equalsIgnoreCase(arg) || COMMANDS.FUTURE_ROLLBACK_SQL.equalsIgnoreCase(arg) || COMMANDS.UPDATE_TESTING_ROLLBACK.equalsIgnoreCase(arg) || COMMANDS.LIST_LOCKS.equalsIgnoreCase(arg) || COMMANDS.DROP_ALL.equalsIgnoreCase(arg) || COMMANDS.RELEASE_LOCKS.equalsIgnoreCase(arg) || COMMANDS.VALIDATE.equalsIgnoreCase(arg) || COMMANDS.HELP.equalsIgnoreCase(arg) || COMMANDS.CLEAR_CHECKSUMS.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(arg) || COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN.equalsIgnoreCase(arg) || COMMANDS.MARK_NEXT_CHANGESET_RAN_SQL.equalsIgnoreCase(arg); } private static void addWarFileClasspathEntries(File classPathFile, List<URL> urls) throws IOException { URL jarUrl = new URL("jar:" + classPathFile.toURI().toURL() + "!/WEB-INF/classes/"); LOG.info("adding '" + jarUrl + "' to classpath"); urls.add(jarUrl); try ( JarFile warZip = new JarFile(classPathFile) ) { Enumeration<? extends JarEntry> entries = warZip.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().startsWith("WEB-INF/lib") && entry.getName().toLowerCase().endsWith(".jar")) { File jar = extract(warZip, entry); URL newUrl = new URL("jar:" + jar.toURI().toURL() + "!/"); LOG.info("adding '" + newUrl + "' to classpath"); urls.add(newUrl); jar.deleteOnExit(); } } } } /** * Extract a single object from a JAR file into a temporary file. * * @param jar the JAR file from which we will extract * @param entry the object inside the JAR file that to be extracted * @return a File object with the temporary file containing the extracted object * @throws IOException if an I/O problem occurs */ private static File extract(JarFile jar, JarEntry entry) throws IOException { // expand to temp dir and add to list File tempFile = File.createTempFile("liquibase.tmp", null); // read from jar and write to the tempJar file try ( BufferedInputStream inStream = new BufferedInputStream(jar.getInputStream(entry)); BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(tempFile)) ) { int status; while ((status = inStream.read()) != -1) { outStream.write(status); } } return tempFile; } /** * Search for both liquibase.properties (or whatever the name of the current * defaultsFile is) and the "local" variant liquibase.local.properties. The contents of the local * variant overwrite parameters with the same name in the regular properties file. * * @throws CommandLineParsingException if an error occurs during parsing */ protected void parseDefaultPropertyFiles() throws CommandLineParsingException { File[] potentialPropertyFiles = new File[2]; potentialPropertyFiles[0] = new File(defaultsFile); String localDefaultsPathName = defaultsFile.replaceFirst("(\\.[^\\.]+)$", ".local$1"); potentialPropertyFiles[1] = new File(localDefaultsPathName); for (File potentialPropertyFile : potentialPropertyFiles) { try { if (potentialPropertyFile.exists()) { parseDefaultPropertyFileFromFile(potentialPropertyFile); } else { parseDefaultPropertyFileFromResource(potentialPropertyFile); } } catch (IOException e) { throw new CommandLineParsingException(e); } } } /** * Open a property file that is embedded as a Java resource and parse it. * * @param potentialPropertyFile location and file name of the property file * @throws IOException if the file cannot be opened * @throws CommandLineParsingException if an error occurs during parsing */ private void parseDefaultPropertyFileFromResource(File potentialPropertyFile) throws IOException, CommandLineParsingException { try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream (potentialPropertyFile.getAbsolutePath())) { if (resourceAsStream != null) { parsePropertiesFile(resourceAsStream); } } } /** * Open a regular property file (not embedded in a resource - use {@link #parseDefaultPropertyFileFromResource} * for that) and parse it. * * @param potentialPropertyFile path and file name to the the property file * @throws IOException if the file cannot be opened * @throws CommandLineParsingException if an error occurs during parsing */ private void parseDefaultPropertyFileFromFile(File potentialPropertyFile) throws IOException, CommandLineParsingException { try (FileInputStream stream = new FileInputStream(potentialPropertyFile)) { parsePropertiesFile(stream); } } /** * On windows machines, it splits args on '=' signs. Put it back like it was. */ protected String[] fixupArgs(String[] args) { List<String> fixedArgs = new ArrayList<>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if ((i + 1) < args.length) { nextArg = args[i + 1]; } if ((nextArg != null) && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } // Sometimes, commas are still escaped as \, at this point, fix it: arg = arg.replace("\\,", ","); fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); } /** * After parsing, checks if the given combination of main command and can be executed. * * @return an empty List if successful, or a list of error messages */ protected List<String> checkSetup() { List<String> messages = new ArrayList<>(); if (command == null) { messages.add(coreBundle.getString("command.not.passed")); } else if (!isCommand(command)) { messages.add(String.format(coreBundle.getString("command.unknown"), command)); } else { if (StringUtil.trimToNull(url) == null) { messages.add(String.format(coreBundle.getString("option.required"), "--" + OPTIONS.URL)); } if (isChangeLogRequired(command) && (StringUtil.trimToNull(changeLogFile) == null)) { messages.add(String.format(coreBundle.getString("option.required"), "--" + OPTIONS.CHANGELOG_FILE)); } if (isNoArgCommand(command) && !commandParams.isEmpty()) { messages.add(coreBundle.getString(ERRORMSG_UNEXPECTED_PARAMETERS) + commandParams); } else { validateCommandParameters(messages); } } return messages; } /** * Checks for unexpected (unknown) command line parameters and, if any problems are found, * returns the list of issues in String form. * * @param messages an array of Strings to which messages for issues found will be added */ private void checkForUnexpectedCommandParameter(List<String> messages) { if (COMMANDS.UPDATE_COUNT.equalsIgnoreCase(command) || COMMANDS.UPDATE_COUNT_SQL.equalsIgnoreCase(command) || COMMANDS.UPDATE_TO_TAG.equalsIgnoreCase(command) || COMMANDS.UPDATE_TO_TAG_SQL.equalsIgnoreCase(command) || COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(command) || COMMANDS.DB_DOC.equalsIgnoreCase(command) || COMMANDS.TAG.equalsIgnoreCase(command) || COMMANDS.TAG_EXISTS.equalsIgnoreCase(command)) { if ((!commandParams.isEmpty()) && commandParams.iterator().next().startsWith("-")) { messages.add(coreBundle.getString(ERRORMSG_UNEXPECTED_PARAMETERS) + commandParams); } } else if (COMMANDS.STATUS.equalsIgnoreCase(command) || COMMANDS.UNEXPECTED_CHANGESETS.equalsIgnoreCase(command)) { if ((!commandParams.isEmpty()) && !commandParams.iterator().next().equalsIgnoreCase("--" + OPTIONS.VERBOSE)) { messages.add(coreBundle.getString(ERRORMSG_UNEXPECTED_PARAMETERS) + commandParams); } } else if (COMMANDS.DIFF.equalsIgnoreCase(command) || COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(command)) { if ((!commandParams.isEmpty())) { for (String cmdParm : commandParams) { if (!cmdParm.startsWith("--" + OPTIONS.REFERENCE_USERNAME) && !cmdParm.startsWith("--" + OPTIONS.REFERENCE_PASSWORD) && !cmdParm.startsWith("--" + OPTIONS.REFERENCE_DRIVER) && !cmdParm.startsWith("--" + OPTIONS.REFERENCE_DEFAULT_CATALOG_NAME) && !cmdParm.startsWith("--" + OPTIONS.REFERENCE_DEFAULT_SCHEMA_NAME) && !cmdParm.startsWith("--" + OPTIONS.INCLUDE_SCHEMA) && !cmdParm.startsWith("--" + OPTIONS.INCLUDE_CATALOG) && !cmdParm.startsWith("--" + OPTIONS.INCLUDE_TABLESPACE) && !cmdParm.startsWith("--" + OPTIONS.SCHEMAS) && !cmdParm.startsWith("--" + OPTIONS.OUTPUT_SCHEMAS_AS) && !cmdParm.startsWith("--" + OPTIONS.REFERENCE_SCHEMAS) && !cmdParm.startsWith("--" + OPTIONS.REFERENCE_URL) && !cmdParm.startsWith("--" + OPTIONS.EXCLUDE_OBJECTS) && !cmdParm.startsWith("--" + OPTIONS.INCLUDE_OBJECTS) && !cmdParm.startsWith("--" + OPTIONS.DIFF_TYPES) && !cmdParm.startsWith("--" + OPTIONS.FORMAT) && !cmdParm.startsWith("--" + OPTIONS.HELP) && !cmdParm.startsWith("--" + OPTIONS.SNAPSHOT_FORMAT)) { messages.add(String.format(coreBundle.getString("unexpected.command.parameter"), cmdParm)); } if (COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(command) && cmdParm.startsWith("--" + OPTIONS.FORMAT)) { messages.add(String.format(coreBundle.getString("unexpected.command.parameter"), cmdParm)); } } } } else if ((COMMANDS.SNAPSHOT.equalsIgnoreCase(command) || COMMANDS.GENERATE_CHANGELOG.equalsIgnoreCase(command)) && (!commandParams.isEmpty())) { for (String cmdParm : commandParams) { if (!cmdParm.startsWith("--" + OPTIONS.INCLUDE_SCHEMA) && !cmdParm.startsWith("--" + OPTIONS.INCLUDE_CATALOG) && !cmdParm.startsWith("--" + OPTIONS.INCLUDE_TABLESPACE) && !cmdParm.startsWith("--" + OPTIONS.SCHEMAS) && !cmdParm.startsWith("--" + OPTIONS.SNAPSHOT_FORMAT) && !cmdParm.startsWith("--" + OPTIONS.DATA_OUTPUT_DIRECTORY) && !cmdParm.startsWith("--" + OPTIONS.OUTPUT_SCHEMAS_AS)) { messages.add(String.format(coreBundle.getString("unexpected.command.parameter"), cmdParm)); } } } else if (COMMANDS.ROLLBACK_ONE_CHANGE_SET.equalsIgnoreCase(command)) { for (String cmdParm : commandParams) { if (!cmdParm.startsWith("--" + OPTIONS.CHANGE_SET_ID) && !cmdParm.startsWith("--" + OPTIONS.HELP) && !cmdParm.startsWith("--" + OPTIONS.FORCE) && !cmdParm.startsWith("--" + OPTIONS.CHANGE_SET_PATH) && !cmdParm.startsWith("--" + OPTIONS.CHANGE_SET_AUTHOR) && !cmdParm.startsWith("--" + OPTIONS.ROLLBACK_SCRIPT)) { messages.add(String.format(coreBundle.getString("unexpected.command.parameter"), cmdParm)); } } } else if (COMMANDS.ROLLBACK_ONE_CHANGE_SET_SQL.equalsIgnoreCase(command)) { for (String cmdParm : commandParams) { if (!cmdParm.startsWith("--" + OPTIONS.CHANGE_SET_ID) && !cmdParm.startsWith("--" + OPTIONS.HELP) && !cmdParm.startsWith("--" + OPTIONS.FORCE) && !cmdParm.startsWith("--" + OPTIONS.CHANGE_SET_PATH) && !cmdParm.startsWith("--" + OPTIONS.CHANGE_SET_AUTHOR) && !cmdParm.startsWith("--" + OPTIONS.ROLLBACK_SCRIPT)) { messages.add(String.format(coreBundle.getString("unexpected.command.parameter"), cmdParm)); } } } else if (COMMANDS.ROLLBACK_ONE_UPDATE.equalsIgnoreCase(command)) { for (String cmdParm : commandParams) { if (!cmdParm.startsWith("--" + OPTIONS.DEPLOYMENT_ID) && !cmdParm.startsWith("--" + OPTIONS.HELP) && !cmdParm.startsWith("--" + OPTIONS.FORCE)) { messages.add(String.format(coreBundle.getString("unexpected.command.parameter"), cmdParm)); } } } else if (COMMANDS.ROLLBACK_ONE_UPDATE_SQL.equalsIgnoreCase(command)) { for (String cmdParm : commandParams) { if (!cmdParm.startsWith("--" + OPTIONS.DEPLOYMENT_ID) && !cmdParm.startsWith("--" + OPTIONS.HELP) && !cmdParm.startsWith("--" + OPTIONS.FORCE)) { messages.add(String.format(coreBundle.getString("unexpected.command.parameter"), cmdParm)); } } } } /** * Checks the command line for correctness and reports on unexpected, missing and/or malformed parameters. * * @param messages an array of Strings to which messages for issues found will be added */ private void validateCommandParameters(final List<String> messages) { checkForUnexpectedCommandParameter(messages); checkForMissingCommandParameters(messages); checkForMalformedCommandParameters(messages); } /** * Checks for missing command line parameters and, if any problems are found, * returns the list of issues in String form. * * @param messages an array of Strings to which messages for issues found will be added */ private void checkForMissingCommandParameters(final List<String> messages) { if ((commandParams.isEmpty() || commandParams.iterator().next().startsWith("-")) && (COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(command))) { messages.add(coreBundle.getString("changeset.identifier.missing")); } } /** * Checks for incorrectly written command line parameters and, if any problems are found, * returns the list of issues in String form. * * @param messages an array of Strings to which messages for issues found will be added */ private void checkForMalformedCommandParameters(final List<String> messages) { if (commandParams.isEmpty()) { return; } final int CHANGESET_MINIMUM_IDENTIFIER_PARTS = 3; if (COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(command)) { for (final String param : commandParams) { if ((param != null) && !param.startsWith("-")) { final String[] parts = param.split("::"); if (parts.length < CHANGESET_MINIMUM_IDENTIFIER_PARTS) { messages.add(coreBundle.getString("changeset.identifier.must.have.form.filepath.id.author")); break; } } } } else if (COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(command) && (diffTypes != null) && diffTypes.toLowerCase ().contains("data")) { messages.add(String.format(coreBundle.getString("including.data.diffchangelog.has.no.effect"), OPTIONS.DIFF_TYPES, COMMANDS.GENERATE_CHANGELOG )); } } /** * Reads various execution parameters from an InputStream and sets our internal state according to the values * found. * * @param propertiesInputStream an InputStream from a Java properties file * @throws IOException if there is a problem reading the InputStream * @throws CommandLineParsingException if an invalid property is encountered */ protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); if (props.containsKey("strict")) { strict = Boolean.valueOf(props.getProperty("strict")); } for (Map.Entry entry : props.entrySet()) { try { if ("promptOnNonLocalDatabase".equals(entry.getKey())) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue ()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (NoSuchFieldException ignored) { if (strict) { throw new CommandLineParsingException( String.format(coreBundle.getString("parameter.unknown"), entry.getKey()) ); } else { Scope.getCurrentScope().getLog(getClass()).warning( String.format(coreBundle.getString("parameter.ignored"), entry.getKey()) ); } } catch (IllegalAccessException e) { throw new UnexpectedLiquibaseException( String.format(coreBundle.getString("parameter.unknown"), entry.getKey()) ); } } } /** * If any errors have been found, print the list of errors first, then print the command line help text. * * @param errorMessages List of error messages * @param stream the output stream to write the text to */ protected void printHelp(List<String> errorMessages, PrintStream stream) { stream.println(coreBundle.getString("errors")); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); } /** * Print instructions on how to use this program from the command line. * * @param stream the output stream to write the help text to */ protected void printHelp(PrintStream stream) { this.logLevel = Level.WARNING.toString(); String helpText = commandLineHelpBundle.getString("commandline-helptext"); stream.println(helpText); } /** * Check the string for known characters which cannot be handled * * @param arg Input parameter to check * @return int A CodePointCheck object, or null to indicate all good */ protected static CodePointCheck checkArg(String arg) { char[] chars = arg.toCharArray(); for (int i = 0; i < chars.length; i++) { for (int j = 0; j < suspiciousCodePoints.length; j++) { if (suspiciousCodePoints[j] == chars[i]) { CodePointCheck codePointCheck = new CodePointCheck(); codePointCheck.position = i; codePointCheck.ch = chars[i]; return codePointCheck; } } } return null; } /** * Parses the command line options. If an invalid argument is given, a CommandLineParsingException is thrown. * * @param paramArgs the arguments to parse * @throws CommandLineParsingException thrown if an invalid argument is passed */ protected void parseOptions(String[] paramArgs) throws CommandLineParsingException { String[] args = fixupArgs(paramArgs); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase(COMMANDS.MIGRATE)) { this.command = COMMANDS.UPDATE; } else if (this.command.equalsIgnoreCase(COMMANDS.MIGRATE_SQL)) { this.command = COMMANDS.UPDATE_SQL; } seenCommand = true; } else if (seenCommand) { // ChangeLog parameter: if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); if (arg.startsWith("--")) { parseOptionArgument(arg, true); } } } else if (arg.startsWith("--")) { parseOptionArgument(arg, false); } else { throw new CommandLineParsingException( String.format(coreBundle.getString("unexpected.value"), arg)); } } // Now apply default values from the default property files. We waited with this until this point // since command line parameters might have changed the location where we will look for them. parseDefaultPropertyFiles(); } /** * Parses an option ("--someOption") from the command line * * @param arg the option to parse (including the "--") * @throws CommandLineParsingException if a problem occurs */ private void parseOptionArgument(String arg, boolean okIfNotAField) throws CommandLineParsingException { final String PROMPT_FOR_VALUE = "PROMPT"; if (arg.toLowerCase().startsWith("--" + OPTIONS.VERBOSE) || arg.toLowerCase().startsWith("--" + OPTIONS.HELP)) { return; } if (arg.toLowerCase().equals("--" + OPTIONS.FORCE) || arg.toLowerCase().equals("--" + OPTIONS.HELP)) { arg = arg + "=true"; } String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; if (PROMPT_FOR_VALUE.equalsIgnoreCase(StringUtil.trimToEmpty(value))) { Console c = System.console(); if (c == null) { throw new CommandLineParsingException( String.format(MessageFormat.format(coreBundle.getString( "cannot.prompt.for.the.value.no.console"), attributeName)) ); } //Prompt for value if (attributeName.toLowerCase().contains("password")) { value = new String(c.readPassword(attributeName + ": ")); } else { value = c.readLine(attributeName + ": "); } } try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (IllegalAccessException | NoSuchFieldException e) { if (!okIfNotAField) { throw new CommandLineParsingException( String.format(coreBundle.getString("option.unknown"), attributeName) ); } } } @SuppressWarnings("HardCodedStringLiteral") /** * Set (hopefully) sensible defaults for command line parameters */ protected void applyDefaults() { if (this.promptForNonLocalDatabase == null) { this.promptForNonLocalDatabase = Boolean.FALSE; } if (this.logLevel == null) { this.logLevel = "off"; } if (this.includeSystemClasspath == null) { this.includeSystemClasspath = Boolean.TRUE; } if (this.outputDefaultCatalog == null) { this.outputDefaultCatalog = "true"; } if (this.outputDefaultSchema == null) { this.outputDefaultSchema = "true"; } if (this.defaultsFile == null) { this.defaultsFile = "liquibase.properties"; } if (this.includeSchema == null) { this.includeSchema = false; } if (this.includeCatalog == null) { this.includeCatalog = false; } if (this.includeTablespace == null) { this.includeTablespace = false; } } protected ClassLoader configureClassLoader() throws CommandLineParsingException { final List<URL> urls = new ArrayList<>(); if (this.classpath != null) { String[] classpathSoFar; if (isWindows()) { classpathSoFar = this.classpath.split(";"); } else { classpathSoFar = this.classpath.split(":"); } for (String classpathEntry : classpathSoFar) { File classPathFile = new File(classpathEntry); if (!classPathFile.exists()) { throw new CommandLineParsingException( String.format(coreBundle.getString("does.not.exist"), classPathFile.getAbsolutePath())); } if (classpathEntry.endsWith(FILE_SUFFIXES.WAR_FILE_SUFFIX)) { try { addWarFileClasspathEntries(classPathFile, urls); } catch (IOException e) { throw new CommandLineParsingException(e); } } else if (classpathEntry.endsWith(FILE_SUFFIXES.FILE_SUFFIX_EAR)) { try (JarFile earZip = new JarFile(classPathFile)) { Enumeration<? extends JarEntry> entries = earZip.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().toLowerCase().endsWith(".jar")) { File jar = extract(earZip, entry); URL newUrl = new URL("jar:" + jar.toURI().toURL() + "!/"); urls.add(newUrl); LOG.fine(String.format(coreBundle.getString("adding.to.classpath"), newUrl)); jar.deleteOnExit(); } else if (entry.getName().toLowerCase().endsWith("war")) { File warFile = extract(earZip, entry); addWarFileClasspathEntries(warFile, urls); } } } catch (IOException e) { throw new CommandLineParsingException(e); } } else { URL newUrl = null; try { newUrl = new File(classpathEntry).toURI().toURL(); } catch (MalformedURLException e) { throw new CommandLineParsingException(e); } LOG.fine(String.format(coreBundle.getString("adding.to.classpath"), newUrl)); urls.add(newUrl); } } } if (includeSystemClasspath) { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { @Override public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread() .getContextClassLoader()); } }); } else { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { @Override public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()]), null); } }); } Thread.currentThread().setContextClassLoader(classLoader); return classLoader; } /** * Do the actual database migration, i.e. apply the ChangeSets. * * @throws Exception */ protected void doMigration() throws Exception { if (COMMANDS.HELP.equalsIgnoreCase(command)) { printHelp(System.err); return; } // // Check for a valid license to run PRO commands // String formatValue = getCommandParam(OPTIONS.FORMAT, null); if (isLicenseableCommand(formatValue)) { if (isFormattedDiff()) { if (formatValue != null && ! formatValue.equalsIgnoreCase("json")) { String messageString = "\nWARNING: The diff command optional Pro parameter '--format' " + "currently supports only 'TXT' or 'JSON' as values. (Blank defaults to 'TXT')"; throw new LiquibaseException(String.format(messageString)); } } if (!commandParams.contains("--help") && !liquibaseProLicenseValid) { String warningAboutCommand = command; if (command.equalsIgnoreCase(COMMANDS.DIFF) && formatValue != null && !formatValue.isEmpty()) { warningAboutCommand = "diff --format=" + formatValue; } String messageString = String.format(coreBundle.getString("no.pro.license.found"), warningAboutCommand); throw new LiquibaseException(messageString); } } try { // if (null != logFile) { // Scope.getCurrentScope().getLog(getClass()).setLogLevel(logLevel, logFile); // } else { // Scope.getCurrentScope().getLog(getClass()).setLogLevel(logLevel); // } } catch (IllegalArgumentException e) { throw new CommandLineParsingException(e.getMessage(), e); } CompositeResourceAccessor fileOpener = new CompositeResourceAccessor( new FileSystemResourceAccessor(Paths.get(".").toAbsolutePath().toFile()), new CommandLineResourceAccessor(classLoader) ); Database database = null; if (this.url != null) { database = CommandLineUtils.createDatabaseObject(fileOpener, this.url, this.username, this.password, this.driver, this.defaultCatalogName, this.defaultSchemaName, Boolean.parseBoolean(outputDefaultCatalog), Boolean.parseBoolean(outputDefaultSchema), this.databaseClass, this.driverPropertiesFile, this.propertyProviderClass, this.liquibaseCatalogName, this.liquibaseSchemaName, this.databaseChangeLogTableName, this.databaseChangeLogLockTableName); database.setLiquibaseTablespaceName(this.databaseChangeLogTablespaceName); } try { if ((excludeObjects != null) && (includeObjects != null)) { throw new UnexpectedLiquibaseException( String.format(coreBundle.getString("cannot.specify.both"), OPTIONS.EXCLUDE_OBJECTS, OPTIONS.INCLUDE_OBJECTS)); } // // Set the global configuration option based on presence of the dataOutputDirectory // boolean b = dataOutputDirectory != null; LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).setShouldSnapshotData(b); ObjectChangeFilter objectChangeFilter = null; CompareControl.ComputedSchemas computedSchemas = CompareControl.computeSchemas( schemas, referenceSchemas, outputSchemasAs, defaultCatalogName, defaultSchemaName, referenceDefaultCatalogName, referenceDefaultSchemaName, database); CompareControl.SchemaComparison[] finalSchemaComparisons = computedSchemas.finalSchemaComparisons; DiffOutputControl diffOutputControl = new DiffOutputControl( includeCatalog, includeSchema, includeTablespace, finalSchemaComparisons); if (excludeObjects != null) { objectChangeFilter = new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.EXCLUDE, excludeObjects); diffOutputControl.setObjectChangeFilter(objectChangeFilter); } if (includeObjects != null) { objectChangeFilter = new StandardObjectChangeFilter(StandardObjectChangeFilter.FilterType.INCLUDE, includeObjects); diffOutputControl.setObjectChangeFilter(objectChangeFilter); } for (CompareControl.SchemaComparison schema : finalSchemaComparisons) { diffOutputControl.addIncludedSchema(schema.getReferenceSchema()); diffOutputControl.addIncludedSchema(schema.getComparisonSchema()); } if (COMMANDS.DIFF.equalsIgnoreCase(command)) { if (commandParams.contains("--help")) { System.out.println("liquibase diff" + "\n" + " Outputs a description of differences. If you have a Liquibase Pro key, you can output the differences as JSON using the --format=JSON option\n"); System.exit(0); } if (isFormattedDiff()) { LiquibaseCommand liquibaseCommand = CommandFactory.getInstance().getCommand(COMMANDS.FORMATTED_DIFF); DiffCommand diffCommand = CommandLineUtils.createDiffCommand( createReferenceDatabaseFromCommandParams(commandParams, fileOpener), database, StringUtil.trimToNull(diffTypes), finalSchemaComparisons, objectChangeFilter, new PrintStream(getOutputStream())); Map<String, Object> argsMap = new HashMap<String, Object>(); argsMap.put("format", getCommandParam(OPTIONS.FORMAT, "JSON")); argsMap.put("diffCommand", diffCommand); ((AbstractSelfConfiguratingCommand) liquibaseCommand).configure(argsMap); liquibaseCommand.execute(); } else { CommandLineUtils.doDiff( createReferenceDatabaseFromCommandParams(commandParams, fileOpener), database, StringUtil.trimToNull(diffTypes), finalSchemaComparisons, objectChangeFilter, new PrintStream(getOutputStream())); } return; } else if (COMMANDS.DIFF_CHANGELOG.equalsIgnoreCase(command)) { CommandLineUtils.doDiffToChangeLog(changeLogFile, createReferenceDatabaseFromCommandParams(commandParams, fileOpener), database, diffOutputControl, objectChangeFilter, StringUtil.trimToNull(diffTypes), finalSchemaComparisons ); return; } else if (COMMANDS.GENERATE_CHANGELOG.equalsIgnoreCase(command)) { String currentChangeLogFile = this.changeLogFile; if (currentChangeLogFile == null) { //will output to stdout: currentChangeLogFile = ""; } File file = new File(currentChangeLogFile); if (file.exists() && (!Boolean.parseBoolean(overwriteOutputFile))) { throw new LiquibaseException( String.format(coreBundle.getString("changelogfile.already.exists"), currentChangeLogFile)); } else { try { if (!file.delete()) { // Nothing needs to be done } } catch (SecurityException e) { throw new LiquibaseException( String.format(coreBundle.getString("attempt.to.delete.the.file.failed.cannot.continue"), currentChangeLogFile ), e ); } } CatalogAndSchema[] finalTargetSchemas = computedSchemas.finalTargetSchemas; CommandLineUtils.doGenerateChangeLog(currentChangeLogFile, database, finalTargetSchemas, StringUtil.trimToNull(diffTypes), StringUtil.trimToNull(changeSetAuthor), StringUtil.trimToNull(changeSetContext), StringUtil.trimToNull(dataOutputDirectory), diffOutputControl); return; } else if (COMMANDS.SNAPSHOT.equalsIgnoreCase(command)) { SnapshotCommand snapshotCommand = (SnapshotCommand) CommandFactory.getInstance() .getCommand(COMMANDS.SNAPSHOT); snapshotCommand.setDatabase(database); snapshotCommand.setSchemas(getSchemaParams(database)); snapshotCommand.setSerializerFormat(getCommandParam(OPTIONS.SNAPSHOT_FORMAT, null)); Writer outputWriter = getOutputWriter(); String result = snapshotCommand.execute().print(); outputWriter.write(result); outputWriter.flush(); outputWriter.close(); return; } else if (COMMANDS.EXECUTE_SQL.equalsIgnoreCase(command)) { ExecuteSqlCommand executeSqlCommand = (ExecuteSqlCommand) CommandFactory.getInstance().getCommand( COMMANDS.EXECUTE_SQL); executeSqlCommand.setDatabase(database); executeSqlCommand.setSql(getCommandParam("sql", null)); executeSqlCommand.setSqlFile(getCommandParam("sqlFile", null)); executeSqlCommand.setDelimiter(getCommandParam("delimiter", ";")); Writer outputWriter = getOutputWriter(); outputWriter.write(executeSqlCommand.execute().print()); outputWriter.flush(); outputWriter.close(); return; } else if (COMMANDS.SNAPSHOT_REFERENCE.equalsIgnoreCase(command)) { SnapshotCommand snapshotCommand = (SnapshotCommand) CommandFactory.getInstance() .getCommand(COMMANDS.SNAPSHOT); Database referenceDatabase = createReferenceDatabaseFromCommandParams(commandParams, fileOpener); snapshotCommand.setDatabase(referenceDatabase); snapshotCommand.setSchemas(getSchemaParams(database)); snapshotCommand.setSerializerFormat(getCommandParam(OPTIONS.SNAPSHOT_FORMAT, null)); Writer outputWriter = getOutputWriter(); outputWriter.write(snapshotCommand.execute().print()); outputWriter.flush(); outputWriter.close(); return; } Liquibase liquibase = new Liquibase(changeLogFile, fileOpener, database); ChangeExecListener listener = ChangeExecListenerUtils.getChangeExecListener( liquibase.getDatabase(), liquibase.getResourceAccessor(), changeExecListenerClass, changeExecListenerPropertiesFile); liquibase.setChangeExecListener(listener); if (database != null) { database.setCurrentDateTimeFunction(currentDateTimeFunction); } for (Map.Entry<String, Object> entry : changeLogParameters.entrySet()) { liquibase.setChangeLogParameter(entry.getKey(), entry.getValue()); } if (COMMANDS.LIST_LOCKS.equalsIgnoreCase(command)) { liquibase.reportLocks(System.err); return; } else if (COMMANDS.RELEASE_LOCKS.equalsIgnoreCase(command)) { LockService lockService = LockServiceFactory.getInstance().getLockService(database); lockService.forceReleaseLock(); Scope.getCurrentScope().getUI().sendMessage(String.format( coreBundle.getString("successfully.released.database.change.log.locks"), liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL() ) ); return; } else if (COMMANDS.TAG.equalsIgnoreCase(command)) { liquibase.tag(getCommandArgument()); Scope.getCurrentScope().getUI().sendMessage(String.format( coreBundle.getString("successfully.tagged"), liquibase.getDatabase() .getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL() ) ); return; } else if (COMMANDS.TAG_EXISTS.equalsIgnoreCase(command)) { String tag = commandParams.iterator().next(); boolean exists = liquibase.tagExists(tag); if (exists) { Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("tag.exists"), tag, liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL() ) ); } else { Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("tag.does.not.exist"), tag, liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL() ) ); } return; } else if (COMMANDS.ROLLBACK_ONE_CHANGE_SET.equals(command)) { Map<String, Object> argsMap = new HashMap<>(); loadChangeSetInfoToMap(argsMap); LiquibaseCommand liquibaseCommand = createLiquibaseCommand(database, liquibase, COMMANDS.ROLLBACK_ONE_CHANGE_SET, argsMap); liquibaseCommand.execute(); return; } else if (COMMANDS.ROLLBACK_ONE_CHANGE_SET_SQL.equals(command)) { Writer outputWriter = getOutputWriter(); Map<String, Object> argsMap = new HashMap<>(); loadChangeSetInfoToMap(argsMap); argsMap.put("outputWriter", outputWriter); argsMap.put("force", true); LiquibaseCommand liquibaseCommand = createLiquibaseCommand(database, liquibase, COMMANDS.ROLLBACK_ONE_CHANGE_SET, argsMap); liquibaseCommand.execute(); outputWriter.flush(); outputWriter.close(); return; } else if (COMMANDS.ROLLBACK_ONE_UPDATE.equals(command)) { Map<String, Object> argsMap = new HashMap<>(); argsMap.put("deploymentId", getCommandParam(OPTIONS.DEPLOYMENT_ID, null)); LiquibaseCommand liquibaseCommand = createLiquibaseCommand(database, liquibase, COMMANDS.ROLLBACK_ONE_UPDATE, argsMap); liquibaseCommand.execute(); return; } else if (COMMANDS.ROLLBACK_ONE_UPDATE_SQL.equals(command)) { Writer outputWriter = getOutputWriter(); Map<String, Object> argsMap = new HashMap<>(); argsMap.put("deploymentId", getCommandParam(OPTIONS.DEPLOYMENT_ID, null)); argsMap.put("outputWriter", outputWriter); argsMap.put("force", true); LiquibaseCommand liquibaseCommand = createLiquibaseCommand(database, liquibase, COMMANDS.ROLLBACK_ONE_UPDATE, argsMap); liquibaseCommand.execute(); outputWriter.flush(); outputWriter.close(); return; } else if (COMMANDS.DROP_ALL.equals(command)) { DropAllCommand dropAllCommand = (DropAllCommand) CommandFactory.getInstance().getCommand (COMMANDS.DROP_ALL); dropAllCommand.setDatabase(liquibase.getDatabase()); dropAllCommand.setSchemas(getSchemaParams(database)); Scope.getCurrentScope().getUI().sendMessage(dropAllCommand.execute().print()); return; } else if (COMMANDS.STATUS.equalsIgnoreCase(command)) { boolean runVerbose = false; if (commandParams.contains("--" + OPTIONS.VERBOSE)) { runVerbose = true; } liquibase.reportStatus(runVerbose, new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); return; } else if (COMMANDS.UNEXPECTED_CHANGESETS.equalsIgnoreCase(command)) { boolean runVerbose = false; if (commandParams.contains("--" + OPTIONS.VERBOSE)) { runVerbose = true; } liquibase.reportUnexpectedChangeSets(runVerbose, contexts, getOutputWriter()); return; } else if (COMMANDS.VALIDATE.equalsIgnoreCase(command)) { try { liquibase.validate(); } catch (ValidationFailedException e) { e.printDescriptiveError(System.err); return; } Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("no.validation.errors.found")); return; } else if (COMMANDS.CLEAR_CHECKSUMS.equalsIgnoreCase(command)) { liquibase.clearCheckSums(); return; } else if (COMMANDS.CALCULATE_CHECKSUM.equalsIgnoreCase(command)) { CheckSum checkSum = null; checkSum = liquibase.calculateCheckSum(commandParams.iterator().next()); Scope.getCurrentScope().getUI().sendMessage(checkSum.toString()); return; } else if (COMMANDS.DB_DOC.equalsIgnoreCase(command)) { if (commandParams.isEmpty()) { throw new CommandLineParsingException(coreBundle.getString("dbdoc.requires.output.directory")); } if (changeLogFile == null) { throw new CommandLineParsingException(coreBundle.getString("dbdoc.requires.changelog.parameter")); } liquibase.generateDocumentation(commandParams.iterator().next(), contexts); return; } try { if (COMMANDS.UPDATE.equalsIgnoreCase(command)) { liquibase.update(new Contexts(contexts), new LabelExpression(labels)); } else if (COMMANDS.CHANGELOG_SYNC.equalsIgnoreCase(command)) { liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels)); } else if (COMMANDS.CHANGELOG_SYNC_SQL.equalsIgnoreCase(command)) { liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); } else if (COMMANDS.MARK_NEXT_CHANGESET_RAN.equalsIgnoreCase(command)) { liquibase.markNextChangeSetRan(new Contexts(contexts), new LabelExpression(labels)); } else if (COMMANDS.MARK_NEXT_CHANGESET_RAN_SQL.equalsIgnoreCase(command)) { liquibase.markNextChangeSetRan(new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); } else if (COMMANDS.UPDATE_COUNT.equalsIgnoreCase(command)) { liquibase.update(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels)); } else if (COMMANDS.UPDATE_COUNT_SQL.equalsIgnoreCase(command)) { liquibase.update(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); } else if (COMMANDS.UPDATE_TO_TAG.equalsIgnoreCase(command)) { if ((commandParams == null) || commandParams.isEmpty()) { throw new CommandLineParsingException( String.format(coreBundle.getString("command.requires.tag"), COMMANDS.UPDATE_TO_TAG)); } liquibase.update(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression (labels)); } else if (COMMANDS.UPDATE_TO_TAG_SQL.equalsIgnoreCase(command)) { if ((commandParams == null) || commandParams.isEmpty()) { throw new CommandLineParsingException( String.format(coreBundle.getString("command.requires.tag"), COMMANDS.UPDATE_TO_TAG_SQL)); } liquibase.update(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression (labels), getOutputWriter()); } else if (COMMANDS.UPDATE_SQL.equalsIgnoreCase(command)) { liquibase.update(new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); } else if (COMMANDS.ROLLBACK.equalsIgnoreCase(command)) { if (getCommandArgument() == null) { throw new CommandLineParsingException( String.format(coreBundle.getString("command.requires.tag"), COMMANDS.ROLLBACK)); } liquibase.rollback(getCommandArgument(), getCommandParam(COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels)); } else if (COMMANDS.ROLLBACK_TO_DATE.equalsIgnoreCase(command)) { if (getCommandArgument() == null) { throw new CommandLineParsingException( String.format(coreBundle.getString("command.requires.timestamp"), COMMANDS.ROLLBACK_TO_DATE)); } liquibase.rollback(new ISODateFormat().parse(getCommandArgument()), getCommandParam (COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels)); } else if (COMMANDS.ROLLBACK_COUNT.equalsIgnoreCase(command)) { liquibase.rollback(Integer.parseInt(getCommandArgument()), getCommandParam (COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels)); } else if (COMMANDS.ROLLBACK_SQL.equalsIgnoreCase(command)) { if (getCommandArgument() == null) { throw new CommandLineParsingException( String.format(coreBundle.getString("command.requires.tag"), COMMANDS.ROLLBACK_SQL)); } liquibase.rollback(getCommandArgument(), getCommandParam(COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); } else if (COMMANDS.ROLLBACK_TO_DATE_SQL.equalsIgnoreCase(command)) { if (getCommandArgument() == null) { throw new CommandLineParsingException( String.format(coreBundle.getString("command.requires.timestamp"), COMMANDS.ROLLBACK_TO_DATE_SQL)); } liquibase.rollback(new ISODateFormat().parse(getCommandArgument()), getCommandParam (COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression (labels), getOutputWriter()); } else if (COMMANDS.ROLLBACK_COUNT_SQL.equalsIgnoreCase(command)) { if (getCommandArgument() == null) { throw new CommandLineParsingException( String.format(coreBundle.getString("command.requires.count"), COMMANDS.ROLLBACK_COUNT_SQL)); } liquibase.rollback(Integer.parseInt(getCommandArgument()), getCommandParam (COMMANDS.ROLLBACK_SCRIPT, null), new Contexts(contexts), new LabelExpression(labels), getOutputWriter() ); } else if (COMMANDS.FUTURE_ROLLBACK_SQL.equalsIgnoreCase(command)) { liquibase.futureRollbackSQL(new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); } else if (COMMANDS.FUTURE_ROLLBACK_COUNT_SQL.equalsIgnoreCase(command)) { if (getCommandArgument() == null) { throw new CommandLineParsingException( String.format(coreBundle.getString("command.requires.count"), COMMANDS.FUTURE_ROLLBACK_COUNT_SQL)); } liquibase.futureRollbackSQL(Integer.parseInt(getCommandArgument()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); } else if (COMMANDS.FUTURE_ROLLBACK_FROM_TAG_SQL.equalsIgnoreCase(command)) { if (getCommandArgument() == null) { throw new CommandLineParsingException( String.format(coreBundle.getString("command.requires.tag"), COMMANDS.FUTURE_ROLLBACK_FROM_TAG_SQL)); } liquibase.futureRollbackSQL(getCommandArgument(), new Contexts(contexts), new LabelExpression (labels), getOutputWriter()); } else if (COMMANDS.UPDATE_TESTING_ROLLBACK.equalsIgnoreCase(command)) { liquibase.updateTestingRollback(new Contexts(contexts), new LabelExpression(labels)); } else if (COMMANDS.HISTORY.equalsIgnoreCase(command)) { HistoryCommand historyCommand = (HistoryCommand) CommandFactory.getInstance().getCommand("history"); historyCommand.setDatabase(database); historyCommand.setOutputStream(new PrintStream(getOutputStream())); historyCommand.execute(); } else { throw new CommandLineParsingException( String.format(coreBundle.getString("command.unknown"), command)); } } catch (ParseException ignored) { throw new CommandLineParsingException( coreBundle.getString("timeformat.invalid")); } } finally { try { if (database != null) { database.rollback(); database.close(); } } catch (DatabaseException e) { Scope.getCurrentScope().getLog(getClass()).warning( coreBundle.getString("problem.closing.connection"), e); } } } private boolean isLicenseableCommand(String formatValue) { return COMMANDS.ROLLBACK_ONE_CHANGE_SET.equalsIgnoreCase(command) || COMMANDS.ROLLBACK_ONE_CHANGE_SET_SQL.equalsIgnoreCase(command) || COMMANDS.ROLLBACK_ONE_UPDATE.equalsIgnoreCase(command) || COMMANDS.ROLLBACK_ONE_UPDATE_SQL.equalsIgnoreCase(command) || (COMMANDS.DIFF.equalsIgnoreCase(command) && formatValue != null && ! formatValue.toLowerCase().equals("txt")); } private void loadChangeSetInfoToMap(Map<String, Object> argsMap) throws CommandLineParsingException { argsMap.put("changeSetId", getCommandParam(OPTIONS.CHANGE_SET_ID, null)); argsMap.put("changeSetAuthor", getCommandParam(OPTIONS.CHANGE_SET_AUTHOR, null)); argsMap.put("changeSetPath", getCommandParam(OPTIONS.CHANGE_SET_PATH, null)); } private boolean isFormattedDiff() throws CommandLineParsingException { String formatValue = getCommandParam(OPTIONS.FORMAT, "txt"); return ! formatValue.equalsIgnoreCase("txt") && ! formatValue.isEmpty(); } private String getSchemaParams(Database database) throws CommandLineParsingException { String schemaParams = getCommandParam(OPTIONS.SCHEMAS, schemas); if (schemaParams == null || schemaParams.isEmpty()) { return database.getDefaultSchema().getSchemaName(); } return schemaParams; } private LiquibaseCommand createLiquibaseCommand(Database database, Liquibase liquibase, String commandName, Map<String, Object> argsMap) throws LiquibaseException { argsMap.put("rollbackScript", rollbackScript); argsMap.put("changeLogFile", changeLogFile); argsMap.put("database", database); argsMap.put("liquibase", liquibase); if (!commandParams.contains("--help")) { argsMap.put("changeLog", liquibase.getDatabaseChangeLog()); } ChangeLogParameters clp = new ChangeLogParameters(database); for (Map.Entry<String, Object> entry : changeLogParameters.entrySet()) { clp.set(entry.getKey(), entry.getValue()); } argsMap.put("changeLogParameters", clp); if (this.commandParams.contains("--force")) { argsMap.put("force", true); } if (this.commandParams.contains("--help")) { argsMap.put("help", true); } LiquibaseCommand liquibaseCommand = CommandFactory.getInstance().getCommand(commandName); AbstractSelfConfiguratingCommand configuratingCommand = (AbstractSelfConfiguratingCommand) liquibaseCommand; configuratingCommand.configure(argsMap); return liquibaseCommand; } /** * Return the first "parameter" from the command line that does NOT have the form of parameter=value. A parameter * is a command line argument that follows the main action (e.g. update/rollback/...). Example: * For the main action "updateToTagSQL &lt;tag&gt;", &lt;tag&gt; would be the command argument. * * @return the command argument, if one is given. Otherwise null. */ private String getCommandArgument() { for (String param : commandParams) { if (!param.contains("=")) { return param; } } return null; } /** * Returns the value for a command line parameter of the form parameterName=value, or defaultValue if that * parameter has not been specified by the user. * * @param paramName name of the parameter * @param defaultValue return value if parameter is not given * @return the user-specified value for paramName, or defaultValue * @throws CommandLineParsingException if a parameter on the command line is un-parsable */ private String getCommandParam(String paramName, String defaultValue) throws CommandLineParsingException { for (String param : commandParams) { if (!param.contains("=")) { continue; } String[] splitArg = splitArg(param); String attributeName = splitArg[0]; String value = splitArg[1]; if (attributeName.equalsIgnoreCase(paramName)) { return value; } } return defaultValue; } private Database createReferenceDatabaseFromCommandParams( Set<String> commandParams, ResourceAccessor resourceAccessor) throws CommandLineParsingException, DatabaseException { String refDriver = referenceDriver; String refUrl = referenceUrl; String refUsername = referenceUsername; String refPassword = referencePassword; String defSchemaName = this.referenceDefaultSchemaName; String defCatalogName = this.referenceDefaultCatalogName; for (String param : commandParams) { String[] splitArg = splitArg(param); String attributeName = splitArg[0]; String value = splitArg[1]; if (OPTIONS.REFERENCE_DRIVER.equalsIgnoreCase(attributeName)) { refDriver = value; } else if (OPTIONS.REFERENCE_URL.equalsIgnoreCase(attributeName)) { refUrl = value; } else if (OPTIONS.REFERENCE_USERNAME.equalsIgnoreCase(attributeName)) { refUsername = value; } else if (OPTIONS.REFERENCE_PASSWORD.equalsIgnoreCase(attributeName)) { refPassword = value; } else if (OPTIONS.REFERENCE_DEFAULT_CATALOG_NAME.equalsIgnoreCase(attributeName)) { defCatalogName = value; } else if (OPTIONS.REFERENCE_DEFAULT_SCHEMA_NAME.equalsIgnoreCase(attributeName)) { defSchemaName = value; } else if (OPTIONS.DATA_OUTPUT_DIRECTORY.equalsIgnoreCase(attributeName)) { dataOutputDirectory = value; } } if (refUrl == null) { throw new CommandLineParsingException( String.format(coreBundle.getString("option.required"), "--referenceUrl")); } return CommandLineUtils.createDatabaseObject(resourceAccessor, refUrl, refUsername, refPassword, refDriver, defCatalogName, defSchemaName, Boolean.parseBoolean(outputDefaultCatalog), Boolean.parseBoolean (outputDefaultSchema), null, null, this.propertyProviderClass, this.liquibaseCatalogName, this.liquibaseSchemaName, this.databaseChangeLogTableName, this.databaseChangeLogLockTableName); } private OutputStream getOutputStream() throws IOException { if (outputFile != null) { FileOutputStream fileOut; try { fileOut = new FileOutputStream(outputFile, false); return fileOut; } catch (IOException e) { Scope.getCurrentScope().getLog(getClass()).severe(String.format( coreBundle.getString("could.not.create.output.file"), outputFile)); throw e; } } else { return System.out; } } private Writer getOutputWriter() throws IOException { String charsetName = LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class) .getOutputEncoding(); return new OutputStreamWriter(getOutputStream(), charsetName); } /** * Determines if this program is executed on a Microsoft Windows-type of operating system. * * @return true if running under some variant of MS Windows, false otherwise. */ public boolean isWindows() { return System.getProperty("os.name").startsWith("Windows "); } @SuppressWarnings("HardCodedStringLiteral") private enum FILE_SUFFIXES { ; private static final String FILE_SUFFIX_EAR = ".ear"; private static final String WAR_FILE_SUFFIX = ".war"; } @SuppressWarnings("HardCodedStringLiteral") private enum COMMANDS { ; private static final String CALCULATE_CHECKSUM = "calculateCheckSum"; private static final String CHANGELOG_SYNC = "changelogSync"; private static final String CHANGELOG_SYNC_SQL = "changelogSyncSQL"; private static final String CLEAR_CHECKSUMS = "clearCheckSums"; private static final String DB_DOC = "dbDoc"; private static final String DIFF = "diff"; private static final String DIFF_CHANGELOG = "diffChangeLog"; private static final String DROP_ALL = "dropAll"; private static final String EXECUTE_SQL = "executeSql"; private static final String FUTURE_ROLLBACK_COUNT_SQL = "futureRollbackCountSQL"; private static final String FUTURE_ROLLBACK_FROM_TAG_SQL = "futureRollbackFromTagSQL"; private static final String FUTURE_ROLLBACK_SQL = "futureRollbackSQL"; private static final String FUTURE_ROLLBACK_TO_TAG_SQL = "futureRollbackToTagSQL"; private static final String GENERATE_CHANGELOG = "generateChangeLog"; private static final String HELP = OPTIONS.HELP; private static final String HISTORY = "history"; private static final String LIST_LOCKS = "listLocks"; private static final String MARK_NEXT_CHANGESET_RAN = "markNextChangeSetRan"; private static final String MARK_NEXT_CHANGESET_RAN_SQL = "markNextChangeSetRanSQL"; private static final String MIGRATE = "migrate"; private static final String MIGRATE_SQL = "migrateSQL"; private static final String RELEASE_LOCKS = "releaseLocks"; private static final String ROLLBACK_ONE_CHANGE_SET = "rollbackOneChangeSet"; private static final String ROLLBACK_ONE_CHANGE_SET_SQL = "rollbackOneChangeSetSQL"; private static final String ROLLBACK_ONE_UPDATE = "rollbackOneUpdate"; private static final String ROLLBACK_ONE_UPDATE_SQL = "rollbackOneUpdateSQL"; private static final String FORMATTED_DIFF = "formattedDiff"; private static final String ROLLBACK = "rollback"; private static final String ROLLBACK_COUNT = "rollbackCount"; private static final String ROLLBACK_COUNT_SQL = "rollbackCountSQL"; private static final String ROLLBACK_SCRIPT = "rollbackScript"; private static final String ROLLBACK_SQL = "rollbackSQL"; private static final String ROLLBACK_TO_DATE = "rollbackToDate"; private static final String ROLLBACK_TO_DATE_SQL = "rollbackToDateSQL"; private static final String SNAPSHOT = "snapshot"; private static final String SNAPSHOT_REFERENCE = "snapshotReference"; private static final String STATUS = "status"; private static final String TAG = "tag"; private static final String TAG_EXISTS = "tagExists"; private static final String UNEXPECTED_CHANGESETS = "unexpectedChangeSets"; private static final String UPDATE = "update"; private static final String UPDATE_COUNT = "updateCount"; private static final String UPDATE_COUNT_SQL = "updateCountSQL"; private static final String UPDATE_SQL = "updateSQL"; private static final String UPDATE_TESTING_ROLLBACK = "updateTestingRollback"; private static final String UPDATE_TO_TAG = "updateToTag"; private static final String UPDATE_TO_TAG_SQL = "updateToTagSQL"; private static final String VALIDATE = "validate"; } @SuppressWarnings("HardCodedStringLiteral") private enum OPTIONS { ; private static final String VERBOSE = "verbose"; private static final String CHANGELOG_FILE = "changeLogFile"; private static final String DATA_OUTPUT_DIRECTORY = "dataOutputDirectory"; private static final String DIFF_TYPES = "diffTypes"; private static final String CHANGE_SET_ID = "changeSetId"; private static final String CHANGE_SET_AUTHOR = "changeSetAuthor"; private static final String CHANGE_SET_PATH = "changeSetPath"; private static final String DEPLOYMENT_ID = "deploymentId"; private static final String OUTPUT_FILE = "outputFile"; private static final String FORCE = "force"; private static final String FORMAT = "format"; private static final String ROLLBACK_SCRIPT = "rollbackScript"; private static final String EXCLUDE_OBJECTS = "excludeObjects"; private static final String INCLUDE_CATALOG = "includeCatalog"; private static final String INCLUDE_OBJECTS = "includeObjects"; private static final String INCLUDE_SCHEMA = "includeSchema"; private static final String INCLUDE_TABLESPACE = "includeTablespace"; private static final String OUTPUT_SCHEMAS_AS = "outputSchemasAs"; private static final String REFERENCE_DEFAULT_CATALOG_NAME = "referenceDefaultCatalogName"; private static final String REFERENCE_DEFAULT_SCHEMA_NAME = "referenceDefaultSchemaName"; private static final String REFERENCE_DRIVER = "referenceDriver"; // SONAR confuses this constant name with a hard-coded password: @SuppressWarnings("squid:S2068") private static final String REFERENCE_PASSWORD = "referencePassword"; private static final String REFERENCE_SCHEMAS = "referenceSchemas"; private static final String REFERENCE_URL = "referenceUrl"; private static final String REFERENCE_USERNAME = "referenceUsername"; private static final String SCHEMAS = "schemas"; private static final String URL = "url"; private static final String HELP = "help"; private static final String VERSION = "version"; private static final String SNAPSHOT_FORMAT = "snapshotFormat"; private static final String LOG_FILE = "logFile"; private static final String LOG_LEVEL = "logLevel"; } }
package edu.pdx.cs410J.di; import com.google.inject.Inject; import com.google.inject.Singleton; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.logging.Logger; /** * Logs all calls to the rest services */ @Singleton public class RestLoggingFilter implements Filter { private final Logger logger; private final CreditCardDatabase cards; @Inject public RestLoggingFilter(Logger logger, CreditCardDatabase cards) { this.logger = logger; this.cards = cards; } public void init( FilterConfig config ) throws ServletException { // Initialize some credit cards for testing purposes. This probably isn't the best place to do this. for (int i = 1; i <= 10; i++) { CreditCard card = new CreditCard(String.valueOf(i)); cards.setBalance( card, 100.0 ); } } public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { long begin = System.currentTimeMillis(); StringBuilder description = new StringBuilder("Request from "); description.append(request.getRemoteAddr()).append(":").append(request.getRemotePort()); if (request instanceof HttpServletRequest) { HttpServletRequest http = (HttpServletRequest) request; description.append(" for ").append( http.getMethod() ).append(" ").append(http.getRequestURI()); } logger.info("Begin " + description); chain.doFilter( request, response ); long delta = System.currentTimeMillis() - begin; logger.info("End (" + delta + " ms) " + description); } public void destroy() { } }
/* * Copyright (c) Fundacion Jala. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ package org.fundacionjala.enforce.sonarqube.apex.api.grammar.buildersource; import org.sonar.sslr.grammar.LexerfulGrammarBuilder; import static org.fundacionjala.enforce.sonarqube.apex.api.ApexKeyword.*; import static org.fundacionjala.enforce.sonarqube.apex.api.ApexPunctuator.*; import static org.fundacionjala.enforce.sonarqube.apex.api.ApexTokenType.*; import static org.fundacionjala.enforce.sonarqube.apex.api.grammar.ApexGrammarRuleKey.*; import static com.sonar.sslr.api.GenericTokenType.IDENTIFIER; /** * This class contains constructors for SOQL rules and its sub rules. * */ public class SOQLExpressions { public static void create(LexerfulGrammarBuilder grammarBuilder) { query(grammarBuilder); selectSentence(grammarBuilder); aggregateMethod(grammarBuilder); dateMethods(grammarBuilder); dateLiteralsWithInteger(grammarBuilder); dateLiterals(grammarBuilder); typeField(grammarBuilder); soqlName(grammarBuilder); nameChar(grammarBuilder); fromSentence(grammarBuilder); aliasStatement(grammarBuilder); withSentence(grammarBuilder); whereSentence(grammarBuilder); fieldExpression(grammarBuilder); simpleExpression(grammarBuilder); filteringExpressions(grammarBuilder); operatorToComparisson(grammarBuilder); conditionalSOQLExpression(grammarBuilder); andSOQLExpression(grammarBuilder); orSOQLExpression(grammarBuilder); limitSentence(grammarBuilder); orderBySentence(grammarBuilder); groupBySentence(grammarBuilder); groupByTypesSentence(grammarBuilder); soqlExternalVariable(grammarBuilder); havingSentence(grammarBuilder); whereSentenceExpression(grammarBuilder); //soqlStringSet(grammarBuilder); //soqlFilterExpressionSet(grammarBuilder); } /** * It is responsible for setting the rule for NAME_CHAR. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void nameChar(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(NAME_CHAR).is( grammarBuilder.firstOf( IDENTIFIER, DOT, UNDERSCORE )); } /** * It is responsible for setting the rule for SOQL_NAME. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void soqlName(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(SOQL_NAME).is( grammarBuilder.firstOf(IDENTIFIER, ALLOWED_KEYWORDS_AS_SOBJECT_NAME), grammarBuilder.zeroOrMore(NAME_CHAR)); } /** * It is responsible for setting the rule for query. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void query(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(QUERY_EXPRESSION).is( SELECT_SENTENCE, FROM_SENTENCE, grammarBuilder.optional(WITH_SENTENCE), grammarBuilder.optional(WHERE_SENTENCE), grammarBuilder.optional(GROUP_BY_SENTENCE), grammarBuilder.optional(HAVING_SENTENCE), grammarBuilder.optional(ORDER_BY_SENTENCE), grammarBuilder.optional(LIMIT_SENTENCE), grammarBuilder.optional(FOR, UPDATE) ); } /** * It is responsible for setting the rule for select sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void selectSentence(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(SELECT_SENTENCE).is( SELECT, grammarBuilder.firstOf(AGGREGATE_EXPR, FIELD, DATE_METHOD_EXPR), grammarBuilder.zeroOrMore( COMMA, grammarBuilder.firstOf(AGGREGATE_EXPR, FIELD, DATE_METHOD_EXPR)), grammarBuilder.zeroOrMore(COMMA, LPAREN, QUERY_EXPRESSION, RPAREN)); } /** * It is responsible for setting the rule for all type of Aggregate Methods. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void aggregateMethod(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(AGGREGATE_EXPR).is( grammarBuilder.firstOf(COUNT, AVG, MAX, MIN, SUM, COUNT_DISTINCT), LPAREN, grammarBuilder.optional(SOQL_NAME), RPAREN, grammarBuilder.optional(SOQL_NAME)); } /** * It is responsible for setting the rule for All Date Methods available for SOQL Query. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void dateMethods(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(DATE_METHOD_EXPR).is( grammarBuilder.firstOf( CALENDAR_MONTH, CALENDAR_QUARTER, CALENDAR_YEAR, DAY_IN_MONTH, DAY_IN_WEEK, DAY_IN_YEAR, DAY_ONLY, FISCAL_MONTH, FISCAL_QUARTER, FISCAL_YEAR, HOUR_IN_DAY, WEEK_IN_MONTH, WEEK_IN_YEAR), LPAREN, grammarBuilder.optional(SOQL_NAME, STRING), RPAREN, grammarBuilder.optional(SOQL_NAME)); } /** * It is responsible for setting the rule for All Date Literals with integer values available for SOQL Query. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void dateLiteralsWithInteger(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(DATE_LITERALS_WITH_NUMBERS_EXPR).is( grammarBuilder.firstOf( NEXT_N_FISCAL_YEARS, LAST_N_FISCAL_YEARS, NEXT_N_FISCAL_QUARTERS, LAST_N_FISCAL_QUARTERS, LAST_N_DAYS, NEXT_N_DAYS, NEXT_N_WEEKS, LAST_N_WEEKS, NEXT_N_MONTHS, LAST_N_MONTHS, NEXT_N_QUARTERS, LAST_N_QUARTERS, NEXT_N_YEARS, LAST_N_YEARS), COLON, grammarBuilder.firstOf(SOQL_NAME, INTEGER_LITERAL)); } /** * It is responsible for setting the rule for All Date Literals available for SOQL Query. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void dateLiterals(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(DATE_LITERALS_EXPR).is( grammarBuilder.firstOf( YESTERDAY, TODAY, TOMORROW, LAST_WEEK, THIS_WEEK, NEXT_WEEK, LAST_MONTH, THIS_MONTH, NEXT_MONTH, THIS_QUARTER, LAST_QUARTER, NEXT_QUARTER, THIS_YEAR, LAST_YEAR, NEXT_YEAR, THIS_FISCAL_QUARTER, NEXT_FISCAL_QUARTER, LAST_FISCAL_QUARTER, LAST_90_DAYS, NEXT_90_DAYS, THIS_FISCAL_YEAR, LAST_FISCAL_YEAR, NEXT_FISCAL_YEAR)); } /** * It is responsible for setting the rules for field. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void typeField(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(FIELD).is(SOQL_NAME); } /** * It is responsible for setting the rule for from sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void fromSentence(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(FROM_SENTENCE).is(FROM, grammarBuilder.firstOf( SOQL_NAME, GROUP) , grammarBuilder.optional(ALIASSTATEMENT)); } /** * It is responsible for setting the rule for optional 'as' sentence in * from. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void aliasStatement(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(ALIASSTATEMENT).is(AS, SOQL_NAME); } /** * It is responsible for setting the rule for with sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void withSentence(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(WITH_SENTENCE).is( WITH, SIMPLE_EXPRESSION); } /** * It is responsible for setting the rule for where sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void whereSentence(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(WHERE_SENTENCE).is( WHERE, WHERE_SENTENCE_EXPRESSION ); } /** * It is responsible for setting the rule for where sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void whereSentenceExpression(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(WHERE_SENTENCE_EXPRESSION).is( grammarBuilder.firstOf( grammarBuilder.sequence( LPAREN, SIMPLE_EXPRESSION, grammarBuilder.zeroOrMore(CONDITIONAL_SOQL_EXPRESSION), RPAREN, grammarBuilder.zeroOrMore(CONDITIONAL_SOQL_EXPRESSION) ), grammarBuilder.sequence( SIMPLE_EXPRESSION, grammarBuilder.zeroOrMore(CONDITIONAL_SOQL_EXPRESSION) ) ) ); } /** * It is responsible for setting the rule for conditional expressions in * where sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void conditionalSOQLExpression(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(CONDITIONAL_SOQL_EXPRESSION).is( grammarBuilder.firstOf( AND_SOQL_EXPRESSION, OR_SOQL_EXPRESSION )); } /** * It is responsible for setting the rule for operators in where sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void operatorToComparisson(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(OPERATORS).is( grammarBuilder.firstOf( ASSIGN, GT, GEQUT, LT, LEQUT, LIKE, NOTEQUALS, CLS_NOTEQUALS, IN )); } /** * It is responsible for setting the rule for FIELD expression in where * sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void fieldExpression(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(FIELD_EXPRESSION).is( //grammarBuilder.optional(NOT_SOQL), grammarBuilder.firstOf(SOQL_NAME, DATE_METHOD_EXPR, AGGREGATE_EXPR), grammarBuilder.optional(NOT_SOQL), OPERATORS, grammarBuilder.firstOf( STRING, INTEGER_LITERAL, SOQL_EXTERNAL_VARIABLE, BOOLEAN_LITERAL, NULL, DATE_LITERALS_EXPR, DATE_LITERALS_WITH_NUMBERS_EXPR)); } /** * It is responsible for setting the rule for SOQL External Variable in where * sentence. External Variable can be any variable, method like: * Where id =:userId * Where id =:getId() * Where id =: userInfo.GetUserId() * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void soqlExternalVariable(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(SOQL_EXTERNAL_VARIABLE).is( COLON, grammarBuilder.firstOf(NAME, SOQL_NAME), grammarBuilder.optional(LPAREN, grammarBuilder.optional(grammarBuilder.firstOf(STRING, INTEGER_LITERAL)), RPAREN), grammarBuilder.optional(LBRACKET, grammarBuilder.firstOf(SOQL_NAME, INTEGER_LITERAL), RBRACKET), grammarBuilder.zeroOrMore( DOT, SOQL_NAME, grammarBuilder.optional(LPAREN, grammarBuilder.optional(grammarBuilder.firstOf(STRING, INTEGER_LITERAL)), RPAREN) ) ); } /** * It is responsible for setting the rule for operators in where sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void filteringExpressions(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(FILTERING_EXPRESSION).is( SOQL_NAME, grammarBuilder.optional(NOT_SOQL), grammarBuilder.firstOf( IN, INCLUDES, EXCLUDES), LPAREN, grammarBuilder.firstOf(SOQL_NAME, QUERY_EXPRESSION, STRING), grammarBuilder.zeroOrMore(COMMA, grammarBuilder.firstOf(SOQL_NAME, STRING)), RPAREN ); } /** * It is responsible for setting the rule for SIMPLE expression in where * sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void simpleExpression(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(SIMPLE_EXPRESSION).is( grammarBuilder.firstOf( FIELD_EXPRESSION, FILTERING_EXPRESSION ) ); } /** * It is responsible for setting the rule for AND expression in where * sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void andSOQLExpression(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(AND_SOQL_EXPRESSION).is( AND_SOQL, WHERE_SENTENCE_EXPRESSION); } /** * It is responsible for setting the rule for OR expression in where * sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void orSOQLExpression(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(OR_SOQL_EXPRESSION).is( OR_SOQL, WHERE_SENTENCE_EXPRESSION); } /** * It is responsible for setting the rule for limit sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void limitSentence(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(LIMIT_SENTENCE).is( LIMIT, grammarBuilder.optional(COLON), grammarBuilder.firstOf(SOQL_NAME, INTEGER_LITERAL), grammarBuilder.optional(LPAREN, RPAREN), grammarBuilder.optional(OFFSET, INTEGER_LITERAL) ); } /** * It is responsible for setting the rule for order by sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void orderBySentence(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(ORDER_BY_SENTENCE).is( ORDER, BY, //SOQL_NAME, grammarBuilder.firstOf( SOQL_NAME, AGGREGATE_EXPR), grammarBuilder.optional( grammarBuilder.firstOf(ASC, DES), grammarBuilder.optional( NULLS, grammarBuilder.firstOf(FIRST, LAST))), grammarBuilder.zeroOrMore( COMMA, //SOQL_NAME, grammarBuilder.firstOf( SOQL_NAME, AGGREGATE_EXPR), grammarBuilder.optional( grammarBuilder.firstOf(ASC, DES), grammarBuilder.optional( NULLS, grammarBuilder.firstOf(FIRST, LAST))) ) ); } /** * It is responsible for setting the rule for group by sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void groupBySentence(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(GROUP_BY_SENTENCE).is( GROUP, BY, grammarBuilder.firstOf( SOQL_NAME, GROUP_BY_TYPES, DATE_METHOD_EXPR, AGGREGATE_EXPR ), grammarBuilder.zeroOrMore(COMMA, grammarBuilder.firstOf( SOQL_NAME, GROUP_BY_TYPES, DATE_METHOD_EXPR, AGGREGATE_EXPR )) ); } /** * It is responsible for setting the rule for group by types sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void groupByTypesSentence(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(GROUP_BY_TYPES).is( grammarBuilder.firstOf(CUBE, ROLLUP), LPAREN, SOQL_NAME, grammarBuilder.zeroOrMore(COMMA, SOQL_NAME), RPAREN ); } /** * It is responsible for setting the rule for where sentence. * * @param grammarBuilder ApexGrammarBuilder parameter. */ private static void havingSentence(LexerfulGrammarBuilder grammarBuilder) { grammarBuilder.rule(HAVING_SENTENCE).is(HAVING, //grammarBuilder.optional(LPAREN), SIMPLE_EXPRESSION, grammarBuilder.zeroOrMore(CONDITIONAL_SOQL_EXPRESSION)//, //grammarBuilder.optional(RPAREN) ); } }
package com.honeybee.service; import java.util.List; import com.honeybee.domain.Criteria; import com.honeybee.domain.EnrollListVO; import com.honeybee.domain.MeetVO; import com.honeybee.domain.ThumbVO; public interface MeetService { public void register(MeetVO meet); //게시물 등록 public MeetVO get(Long mno); //게시물 읽어오기 public boolean modify(MeetVO meet); //게시물 수정 public boolean remove(Long mno); //게시물 삭제 public List<MeetVO> getList(); //게시물 전체 갯수 가져오기 //public MeetVO getMyList(String id); UserMapper참조 public List<MeetVO> getList(Criteria cri); //페이징 리스트 가져오기 public List<MeetVO> getListWithCat(Criteria cri); //페이징, 카테고리 리스트 가져오기 public int getTotal(Criteria cri); //게시물 전체 갯수 가져오기(with criteria 페이징 조건) public int getTotalWithCat(Criteria cri); //게시물 전체 갯수 가져오기(with category) public List<MeetVO> getListTest(String id); //내가 속한 모임 리스트 가져오기 public List<MeetVO> getNick(String id); //닉네임 가져오기 public String getCategoryName(Long mno); //해당 모임게시물의 카테고리 이름 가져오기 public List<MeetVO> getListWithCategory(String cid); //내가 개설한 모임을 카테고리별로 가져오기 public boolean views(Long mno); //조회수 카운팅 public boolean thumbs(ThumbVO vo); // 찜수 카운팅 public void insertThumbList(ThumbVO vo); //table thumb_list insert public boolean deleteThumbList(ThumbVO vo); public ThumbVO checkThumbList(String thumbno); //찜 되어있는지 체크 public int applyUpdate(Long mno);//모임게시물에서 신청하면 신청인원 update public int deleteUpdate(EnrollListVO vo); public int updateImg(MeetVO vo); //모임 썸네일 업데이트 public MeetVO getImg(Long mno); //모임 썸네일 가져오기 public String getCid(Long mno, String cid3); //카테고리 이름에 따른 cid가져오기 }
import org.apache.spark.api.java.JavaRDD; import org.apache.spark.sql.*; import static org.apache.spark.sql.functions.col; public class SparkSql { public static void main(String[] args){ //创建一个基本的SparkSession,它是使用所有Spark SQL功能的入口点 SparkSession spark = SparkSession .builder() .appName("Java Spark SQL basic example") .master("local[*]") .config("spark.some.config.option", "some-value") .getOrCreate(); //读取json文件,显示DataFrame内容 Dataset<Row> df = spark.read().json("E:/workspace/bigdata/spark/spark/examples/src/main/resources/people.json"); df.show(); // 树形格式打印schema df.printSchema(); // 选择“name”列 df.select("name").show(); // 选择所有数据, 但对“age”列执行+1操作 df.select(col("name"), col("age").plus(1)).show(); // 选择年龄“age”大于21的people df.filter(col("age").gt(21)).show(); // 根据年龄“age”分组并计数 df.groupBy("age").count().show(); // 注册DataFrame为一个SQL的临时视图 df.createOrReplaceTempView("people"); Dataset<Row> sqlDF = spark.sql("SELECT * FROM people"); sqlDF.show(); // 通过一个文本文件创建Person对象的RDD JavaRDD<People> peopleRDD = spark.read() .textFile("E:/workspace/bigdata/spark/spark/examples/src/main/resources/people.txt") .javaRDD() .map(line -> { String[] parts = line.split(","); People person = new People(); person.setName(parts[0]); person.setAge(Integer.parseInt(parts[1].trim())); return person; }); // 对JavaBeans的RDD指定schema得到DataFrame Dataset<Row> peopleDF = spark.createDataFrame(peopleRDD, People.class); // 注册该DataFrame为临时视图 peopleDF.createOrReplaceTempView("people"); // 执行SQL语句 Dataset<Row> teenagersDF = spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19"); // 结果中的列可以通过属性的下标获取 Encoder<String> stringEncoder = Encoders.STRING(); Dataset<String> teenagerNamesByIndexDF = teenagersDF.map( row -> "Name: " + row.getString(0), stringEncoder); teenagerNamesByIndexDF.show(); // 或者通过属性的名字获取 Dataset<String> teenagerNamesByFieldDF = teenagersDF.map( row -> "Name: " + row.<String>getAs("name"), stringEncoder); teenagerNamesByFieldDF.show(); } }
package com.vaadin.flow; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.remote.DesiredCapabilities; import com.vaadin.flow.testutil.ChromeBrowserTest; import com.vaadin.testbench.parallel.BrowserUtil; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; public class VerifyBrowserVersionIT extends ChromeBrowserTest { @Test public void verifyUserAgent() { open(); DesiredCapabilities desiredCapabilities = getDesiredCapabilities(); String userAgent = findElement(By.id("userAgent")).getText(); String browserIdentifier; if (BrowserUtil.isChrome(getDesiredCapabilities())) { // Chrome version does not necessarily match the desired version // because of auto updates... browserIdentifier = getExpectedUserAgentString( getDesiredCapabilities()) + "81"; } else if (BrowserUtil.isFirefox(getDesiredCapabilities())) { browserIdentifier = getExpectedUserAgentString( getDesiredCapabilities()) + "58"; } else { browserIdentifier = getExpectedUserAgentString(desiredCapabilities) + desiredCapabilities.getVersion(); } assertThat(userAgent, containsString(browserIdentifier)); } private String getExpectedUserAgentString(DesiredCapabilities dCap) { if (BrowserUtil.isIE(dCap)) { // IE11 return "Trident/7.0; rv:"; } else if (BrowserUtil.isFirefox(dCap)) { return "Firefox/"; } else if (BrowserUtil.isChrome(dCap)) { return "Chrome/"; } throw new UnsupportedOperationException( "Test is being run on unknown browser."); } }
/* * 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.flink.runtime.leaderretrieval; import org.apache.flink.api.common.time.Deadline; import org.apache.flink.core.testutils.EachCallbackWrapper; import org.apache.flink.runtime.leaderelection.LeaderInformation; import org.apache.flink.runtime.testutils.CommonTestUtils; import org.apache.flink.runtime.util.TestingFatalErrorHandlerExtension; import org.apache.flink.runtime.util.ZooKeeperUtils; import org.apache.flink.runtime.zookeeper.ZooKeeperExtension; import org.apache.flink.util.TestLoggerExtension; import org.apache.flink.util.function.BiConsumerWithException; import org.apache.flink.util.function.FunctionWithException; import org.apache.flink.shaded.curator5.org.apache.curator.framework.CuratorFramework; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.time.Duration; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for the error handling in case of a suspended connection to the ZooKeeper instance when * retrieving the leader information. */ @ExtendWith(TestLoggerExtension.class) class ZooKeeperLeaderRetrievalConnectionHandlingTest { @RegisterExtension private final TestingFatalErrorHandlerExtension fatalErrorHandlerResource = new TestingFatalErrorHandlerExtension(); @RegisterExtension private final EachCallbackWrapper<ZooKeeperExtension> zooKeeperExtension = new EachCallbackWrapper<>(new ZooKeeperExtension()); @Nullable private CuratorFramework zooKeeperClient; @BeforeEach public void before() throws Exception { zooKeeperClient = zooKeeperExtension .getCustomExtension() .getZooKeeperClient( fatalErrorHandlerResource.getTestingFatalErrorHandler()); zooKeeperClient.blockUntilConnected(); } private ZooKeeperExtension getZooKeeper() { return zooKeeperExtension.getCustomExtension(); } @Test public void testConnectionSuspendedHandlingDuringInitialization() throws Exception { testWithQueueLeaderElectionListener( queueLeaderElectionListener -> ZooKeeperUtils.createLeaderRetrievalDriverFactory(zooKeeperClient) .createLeaderRetrievalDriver( queueLeaderElectionListener, fatalErrorHandlerResource.getTestingFatalErrorHandler()), (leaderRetrievalDriver, queueLeaderElectionListener) -> { // do the testing assertThat(queueLeaderElectionListener.next(Duration.ofMillis(50))) .as("No results are expected, yet, since no leader was elected.") .isNotPresent(); getZooKeeper().restart(); // QueueLeaderElectionListener will be notified with an empty leader when ZK // connection is suspended final String secondAddress = queueLeaderElectionListener.next().getLeaderAddress(); assertThat(secondAddress) .as("The next result is expected to be null.") .isNull(); }); } @Test public void testConnectionSuspendedHandling() throws Exception { testWithQueueLeaderElectionListener( queueLeaderElectionListener -> new ZooKeeperLeaderRetrievalDriver( zooKeeperClient, "/testConnectionSuspendedHandling", queueLeaderElectionListener, ZooKeeperLeaderRetrievalDriver.LeaderInformationClearancePolicy .ON_SUSPENDED_CONNECTION, fatalErrorHandlerResource.getTestingFatalErrorHandler()), (leaderRetrievalDriver, queueLeaderElectionListener) -> { final String leaderAddress = "localhost"; writeLeaderInformationToZooKeeper( leaderRetrievalDriver.getConnectionInformationPath(), leaderAddress, UUID.randomUUID()); // do the testing String firstAddress = queueLeaderElectionListener.next().getLeaderAddress(); assertThat(firstAddress) .as( "The first result is expected to be the initially set leader address.") .isEqualTo(leaderAddress); getZooKeeper().restart(); String secondAddress = queueLeaderElectionListener.next().getLeaderAddress(); assertThat(secondAddress) .as("The next result is expected to be null.") .isNull(); }); } @Test public void testSuspendedConnectionDoesNotClearLeaderInformationIfClearanceOnLostConnection() throws Exception { testWithQueueLeaderElectionListener( queueLeaderElectionListener -> new ZooKeeperLeaderRetrievalDriver( zooKeeperClient, "/testConnectionSuspendedHandling", queueLeaderElectionListener, ZooKeeperLeaderRetrievalDriver.LeaderInformationClearancePolicy .ON_LOST_CONNECTION, fatalErrorHandlerResource.getTestingFatalErrorHandler()), (leaderRetrievalDriver, queueLeaderElectionListener) -> { final String leaderAddress = "localhost"; writeLeaderInformationToZooKeeper( leaderRetrievalDriver.getConnectionInformationPath(), leaderAddress, UUID.randomUUID()); // do the testing String firstAddress = queueLeaderElectionListener.next().getLeaderAddress(); assertThat(firstAddress) .as( "The first result is expected to be the initially set leader address.") .isEqualTo(leaderAddress); getZooKeeper().close(); // make sure that no new leader information is published assertThat(queueLeaderElectionListener.next(Duration.ofMillis(100L))) .isNotPresent(); }); } @Test public void testSameLeaderAfterReconnectTriggersListenerNotification() throws Exception { testWithQueueLeaderElectionListener( queueLeaderElectionListener -> new ZooKeeperLeaderRetrievalDriver( zooKeeperClient, "/testSameLeaderAfterReconnectTriggersListenerNotification", queueLeaderElectionListener, ZooKeeperLeaderRetrievalDriver.LeaderInformationClearancePolicy .ON_SUSPENDED_CONNECTION, fatalErrorHandlerResource.getTestingFatalErrorHandler()), (leaderRetrievalDriver, queueLeaderElectionListener) -> { final String leaderAddress = "foobar"; final UUID sessionId = UUID.randomUUID(); writeLeaderInformationToZooKeeper( leaderRetrievalDriver.getConnectionInformationPath(), leaderAddress, sessionId); // pop new leader queueLeaderElectionListener.next(); getZooKeeper().stop(); queueLeaderElectionListener.next(); getZooKeeper().restart(); // new old leader information should be announced final LeaderInformation connectionReconnect = queueLeaderElectionListener.next(); assertThat(connectionReconnect.getLeaderAddress()).isEqualTo(leaderAddress); }); } private void writeLeaderInformationToZooKeeper( String retrievalPath, String leaderAddress, UUID sessionId) throws Exception { final byte[] data = createLeaderInformation(leaderAddress, sessionId); if (zooKeeperClient.checkExists().forPath(retrievalPath) != null) { zooKeeperClient.setData().forPath(retrievalPath, data); } else { zooKeeperClient.create().creatingParentsIfNeeded().forPath(retrievalPath, data); } } private byte[] createLeaderInformation(String leaderAddress, UUID sessionId) throws IOException { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeUTF(leaderAddress); oos.writeObject(sessionId); oos.flush(); return baos.toByteArray(); } } @Test public void testNewLeaderAfterReconnectTriggersListenerNotification() throws Exception { testWithQueueLeaderElectionListener( queueLeaderElectionListener -> new ZooKeeperLeaderRetrievalDriver( zooKeeperClient, "/testNewLeaderAfterReconnectTriggersListenerNotification", queueLeaderElectionListener, ZooKeeperLeaderRetrievalDriver.LeaderInformationClearancePolicy .ON_SUSPENDED_CONNECTION, fatalErrorHandlerResource.getTestingFatalErrorHandler()), (leaderRetrievalDriver, queueLeaderElectionListener) -> { final String leaderAddress = "foobar"; final UUID sessionId = UUID.randomUUID(); writeLeaderInformationToZooKeeper( leaderRetrievalDriver.getConnectionInformationPath(), leaderAddress, sessionId); // pop new leader queueLeaderElectionListener.next(); getZooKeeper().stop(); queueLeaderElectionListener.next(); getZooKeeper().restart(); final String newLeaderAddress = "barfoo"; final UUID newSessionId = UUID.randomUUID(); writeLeaderInformationToZooKeeper( leaderRetrievalDriver.getConnectionInformationPath(), newLeaderAddress, newSessionId); // check that we find the new leader information eventually CommonTestUtils.waitUntilCondition( () -> { final LeaderInformation afterConnectionReconnect = queueLeaderElectionListener.next(); return afterConnectionReconnect.getLeaderAddress() != null && afterConnectionReconnect .getLeaderAddress() .equals(newLeaderAddress); }, Deadline.fromNow(Duration.ofSeconds(30L))); }); } private void testWithQueueLeaderElectionListener( FunctionWithException< QueueLeaderElectionListener, ZooKeeperLeaderRetrievalDriver, Exception> driverFactoryMethod, BiConsumerWithException< ZooKeeperLeaderRetrievalDriver, QueueLeaderElectionListener, Exception> testCallback) throws Exception { final QueueLeaderElectionListener queueLeaderElectionListener = new QueueLeaderElectionListener(1); ZooKeeperLeaderRetrievalDriver leaderRetrievalDriver = null; try { leaderRetrievalDriver = driverFactoryMethod.apply(queueLeaderElectionListener); testCallback.accept(leaderRetrievalDriver, queueLeaderElectionListener); } finally { queueLeaderElectionListener.clearUnhandledEvents(); if (leaderRetrievalDriver != null) { leaderRetrievalDriver.close(); } } } private static class QueueLeaderElectionListener implements LeaderRetrievalEventHandler { private final BlockingQueue<LeaderInformation> queue; public QueueLeaderElectionListener(int expectedCalls) { this.queue = new ArrayBlockingQueue<>(expectedCalls); } @Override public void notifyLeaderAddress(LeaderInformation leaderInformation) { try { queue.put(leaderInformation); } catch (InterruptedException e) { throw new IllegalStateException(e); } } public LeaderInformation next() { try { return queue.take(); } catch (InterruptedException e) { throw new IllegalStateException(e); } } public Optional<LeaderInformation> next(Duration timeout) { try { return Optional.ofNullable( this.queue.poll(timeout.toMillis(), TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { throw new IllegalStateException(e); } } /** * Clears any unhandled events. This is useful in cases where there was an unplanned * reconnect after the test passed to prepare the shutdown. Outstanding events might cause * an {@link InterruptedException} during shutdown, otherwise. */ public void clearUnhandledEvents() { while (!queue.isEmpty()) { queue.poll(); } } } }
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cloudhsmv2.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.cloudhsmv2.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CloudHsmServiceException JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CloudHsmServiceExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller { private CloudHsmServiceExceptionUnmarshaller() { super(com.amazonaws.services.cloudhsmv2.model.CloudHsmServiceException.class, "CloudHsmServiceException"); } @Override public com.amazonaws.services.cloudhsmv2.model.CloudHsmServiceException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception { com.amazonaws.services.cloudhsmv2.model.CloudHsmServiceException cloudHsmServiceException = new com.amazonaws.services.cloudhsmv2.model.CloudHsmServiceException( null); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return cloudHsmServiceException; } private static CloudHsmServiceExceptionUnmarshaller instance; public static CloudHsmServiceExceptionUnmarshaller getInstance() { if (instance == null) instance = new CloudHsmServiceExceptionUnmarshaller(); return instance; } }
package com.josephgritchen.songsofworship; import android.content.Intent; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.WindowManager; import android.widget.Toast; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; public class Main2Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); ActionBar actionBar = getSupportActionBar(); actionBar.setTitle("SETTINGS"); //Keeps android screen on while reading through getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu2, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.item0: //DO YOUR FUNCTIONALITY HERE return true; case R.id.item1: //DO YOUR FUNCTIONALITY HERE case R.id.item2: //DO YOUR FUNCTIONALITY HERE default: return super.onOptionsItemSelected(item); } } }
package derpibooru.derpy.ui.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import java.util.List; public abstract class RecyclerViewPaginationAdapter<TItem, TViewHolder extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<TViewHolder> { private List<TItem> mItems; private Context mContext; protected RecyclerViewPaginationAdapter(Context context, List<TItem> items) { mContext = context; mItems = items; } public List<TItem> getItems() { return mItems; } public void resetItems(List<TItem> newItems) { super.notifyItemRangeRemoved(0, mItems.size()); mItems = newItems; super.notifyItemRangeInserted(0, mItems.size() - 1); } public void appendItems(List<TItem> newItems) { int oldItemCount = mItems.size(); mItems.addAll(newItems); int newItemCount = mItems.size() - 1; super.notifyItemRangeInserted(oldItemCount, newItemCount); } public void appendItemAtPosition(int position, TItem item) { mItems.add(position, item); super.notifyItemInserted(position); } protected Context getContext() { return mContext; } @Override public int getItemCount() { return mItems.size(); } }
package edu.utexas.tacc.tapis.shared.notifications; public enum NotificationLevel { INFO, WARNING, ERROR }
/* * 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.spark.util.kvstore; import java.util.List; public class IntKeyType { @KVIndex public int key; @KVIndex("id") public String id; public List<String> values; @Override public boolean equals(Object o) { if (o instanceof IntKeyType) { IntKeyType other = (IntKeyType) o; return key == other.key && id.equals(other.id) && values.equals(other.values); } return false; } @Override public int hashCode() { return id.hashCode(); } }
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.miwok; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import java.util.ArrayList; public class ColorsActivity extends AppCompatActivity { ArrayList<Word> words = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_colors); setContentView(R.layout.activity_numbers); words.add(new Word("red", "weṭeṭṭi", R.drawable.color_red)); words.add(new Word("green", "chokokki", R.drawable.color_green)); words.add(new Word("brown", "ṭakaakki", R.drawable.color_brown)); words.add(new Word("gray", "ṭopoppi", R.drawable.color_gray)); words.add(new Word("black", "kululli", R.drawable.color_black)); words.add(new Word("white", "kelelli", R.drawable.color_white)); words.add(new Word("dusty yellow", "ṭopiisә", R.drawable.color_dusty_yellow)); words.add(new Word("mustard yellow", "chiwiiṭә", R.drawable.color_mustard_yellow)); CustomAdapter itemsAdapter = new CustomAdapter(this, words, R.color.category_colors); ListView listView = (ListView) findViewById(R.id.list_view); listView.setAdapter(itemsAdapter); } }
/** * * @author kmcgerald (at) myrobotlab.org * * This file is part of MyRobotLab (http://myrobotlab.org). * * MyRobotLab is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 2 of the License, or (at your option) any later * version (subject to the "Classpath" exception as provided in the LICENSE.txt * file that accompanied this code). * * MyRobotLab is distributed in the hope that it will be useful or fun, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * All libraries in thirdParty bundle are subject to their own license * requirements - please refer to http://myrobotlab.org/libraries for details. * * Enjoy ! * * */ package org.myrobotlab.control; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JLabel; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.service.GUIService; import org.myrobotlab.service._TemplateService; import org.slf4j.Logger; public class MqttGUI extends ServiceGUI implements ActionListener { static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(MqttGUI.class.getCanonicalName()); private JTextField timeTextField = new JTextField(30); private JTextField topicTextField = new JTextField(30); // final JTextArea messageConsole; // final JScrollPane messageScrollPane; private JTextField messageTextField = new JTextField(100); public MqttGUI(final String boundServiceName, final GUIService myService, final JTabbedPane tabs) { super(boundServiceName, myService, tabs); // messageConsole = new JTextArea(); // messageScrollPane = new JScrollPane(messageConsole); } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub } @Override public void attachGUI() { subscribe("publishMqttMessage", "displayData", String[].class); } @Override public void detachGUI() { unsubscribe("publishMqttMessage", "displayData", String[].class); } public void displayData(String[] tokens) { timeTextField.setText(tokens[0]); topicTextField.setText(tokens[1]); // messageConsole.append(tokens[2]); messageTextField.setText(tokens[2]); } public void getState(_TemplateService template) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { } }); } @Override public void init() { gc.gridheight = 8; gc.gridx = 0; gc.gridy = 0; display.add(new JLabel("Time:"), gc); ++gc.gridx; display.add(timeTextField, gc); gc.gridx = 0; gc.gridy += 42; display.add(new JLabel("Topic:"), gc); ++gc.gridx; display.add(topicTextField, gc); gc.gridx = 0; gc.gridy += 42; display.add(new JLabel("Messages:"), gc); ++gc.gridx; // display.add(messageConsole, gc); display.add(messageTextField, gc); gc.gridx = 0; gc.gridy += 42; } }
/** * 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. */ /* Generated By:JJTree: Do not edit this line. DynamicSerDeThrows.java */ package org.apache.hadoop.hive.serde2.dynamic_type; public class DynamicSerDeThrows extends SimpleNode { public DynamicSerDeThrows(int id) { super(id); } public DynamicSerDeThrows(thrift_grammar p, int id) { super(p, id); } }
package org.innovateuk.ifs.application.controller; import org.innovateuk.ifs.BaseControllerIntegrationTest; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.application.repository.ApplicationRepository; import org.innovateuk.ifs.application.resource.ApplicationCountSummaryPageResource; import org.innovateuk.ifs.application.resource.ApplicationCountSummaryResource; import org.innovateuk.ifs.application.resource.ApplicationCountSummaryResource.Sort; import org.innovateuk.ifs.application.resource.ApplicationState; import org.innovateuk.ifs.assessment.period.domain.AssessmentPeriod; import org.innovateuk.ifs.assessment.period.repository.AssessmentPeriodRepository; import org.innovateuk.ifs.category.repository.InnovationAreaRepository; import org.innovateuk.ifs.competition.repository.CompetitionRepository; import org.innovateuk.ifs.user.domain.ProcessRole; import org.innovateuk.ifs.user.mapper.UserMapper; import org.innovateuk.ifs.user.repository.ProcessRoleRepository; import org.innovateuk.ifs.user.resource.ProcessRoleType; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; import static java.util.Optional.empty; import static java.util.Optional.ofNullable; import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication; import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.id; import static org.innovateuk.ifs.user.builder.ProcessRoleBuilder.newProcessRole; import static org.junit.Assert.assertEquals; public class ApplicationCountSummaryControllerIntegrationTest extends BaseControllerIntegrationTest<ApplicationCountSummaryController> { @Autowired private CompetitionRepository competitionRepository; @Autowired private ProcessRoleRepository processRoleRepository; @Autowired private InnovationAreaRepository innovationAreaRepository; @Autowired private ApplicationRepository applicationRepository; @Autowired private AssessmentPeriodRepository assessmentPeriodRepository; @Autowired private UserMapper userMapper; @Autowired @Override protected void setControllerUnderTest(ApplicationCountSummaryController controller) { this.controller = controller; } @Test public void applicationCountSummariesByCompetitionId() { Long competitionId = 1L; loginCompAdmin(); ApplicationCountSummaryPageResource counts = controller.getApplicationCountSummariesByCompetitionId(competitionId,0,3, empty()).getSuccess(); assertEquals(5, counts.getTotalElements()); assertEquals(0, counts.getNumber()); assertEquals(2, counts.getTotalPages()); assertEquals(3, counts.getContent().size()); } @Test public void applicationCountSummariesByCompetitionIdFiltered() { Long competitionId = 1L; loginCompAdmin(); ApplicationCountSummaryPageResource counts = controller.getApplicationCountSummariesByCompetitionId(competitionId, 0, 6, ofNullable("3")).getSuccess(); assertEquals(1, counts.getTotalElements()); assertEquals(0, counts.getNumber()); assertEquals(1, counts.getTotalPages()); ApplicationCountSummaryResource summaryResource = counts.getContent().get(0); assertEquals(3L, (long) summaryResource.getId()); assertEquals("Mobile Phone Data for Logistics Analytics", summaryResource.getName()); assertEquals("Empire Ltd", summaryResource.getLeadOrganisation()); assertEquals(3, summaryResource.getAssessors()); assertEquals(2, summaryResource.getAccepted()); assertEquals(2, summaryResource.getSubmitted()); } @Test public void getApplicationCountSummariesByCompetitionIdAndAssessorId() { Long competitionId = 1L; long assessorId = 20L; loginCompAdmin(); List<AssessmentPeriod> assessmentPeriods = assessmentPeriodRepository.findByCompetitionId(competitionId); AssessmentPeriod assessmentPeriod = assessmentPeriods.get(0); Application application = newApplication() .with(id(null)) .withApplicationState(ApplicationState.SUBMITTED) .withName("Warp Drive") .withCompetition(competitionRepository.findById(competitionId).get()) .withAssessmentPeriod(assessmentPeriod) .build(); application.getApplicationProcess().setProcessState(ApplicationState.SUBMITTED); applicationRepository.save(application); ProcessRole processRole = newProcessRole() .with(id(null)) .withApplication(application) .withRole(ProcessRoleType.LEADAPPLICANT) .withOrganisationId(3L) .withUser(userMapper.mapToDomain(getSteveSmith())) .build(); processRoleRepository.save(processRole); flushAndClearSession(); ApplicationCountSummaryPageResource counts = controller.getApplicationCountSummariesByCompetitionIdAndAssessorId(competitionId, assessorId, assessmentPeriod.getId(), 0, 6, Sort.APPLICATION_NUMBER, "").getSuccess(); assertEquals(6, counts.getTotalElements()); assertEquals(0, counts.getNumber()); assertEquals(1, counts.getTotalPages()); ApplicationCountSummaryResource summaryResource = counts.getContent().stream().filter(row -> row.getName().equals(application.getName())).findAny().get(); assertEquals((long) application.getId(), (long) summaryResource.getId()); assertEquals("Warp Drive", summaryResource.getName()); assertEquals("Empire Ltd", summaryResource.getLeadOrganisation()); assertEquals(0, summaryResource.getAssessors()); assertEquals(0, summaryResource.getAccepted()); assertEquals(0, summaryResource.getSubmitted()); } }
/* Java program to push zeroes to back of array */ import java.io.*; class PushZero { // Function which pushes all zeros to end of an array. static void pushZerosToEnd( int arr[], int n) { int count = 0 ; // Count of non-zero elements // Traverse the array. If element encountered is // non-zero, then replace the element at index 'count' // with this element for ( int i = 0 ; i < n; i++) if (arr[i] != 0 ) arr[count++] = arr[i]; // here count is // incremented // Now all non-zero elements have been shifted to // front and 'count' is set as index of first 0. // Make all elements 0 from count to end. while (count < n) arr[count++] = 0 ; } /*Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = { 1 , 9 , 8 , 4 , 0 , 0 , 2 , 7 , 0 , 6 , 0 , 9 }; int n = arr.length; pushZerosToEnd(arr, n); System.out.println( "Array after pushing zeros to the back: " ); for ( int i= 0 ; i<n; i++) System.out.print(arr[i]+ " " ); } } /* This code is contributed by Devesh Agrawal */
package com.demo; import android.app.Application; import com.facebook.react.ReactApplication; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import com.facebook.soloader.SoLoader; import java.util.Arrays; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage() ); } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.aas.model.v20150701; import com.aliyuncs.AcsResponse; import com.aliyuncs.aas.transform.v20150701.CreateAliyunAccountWithBindHidResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class CreateAliyunAccountWithBindHidResponse extends AcsResponse { private String requestId; private String pK; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getPK() { return this.pK; } public void setPK(String pK) { this.pK = pK; } @Override public CreateAliyunAccountWithBindHidResponse getInstance(UnmarshallerContext context) { return CreateAliyunAccountWithBindHidResponseUnmarshaller.unmarshall(this, context); } }
package equipment; import sprite.Player; public class T2SpeedRing extends Item { public T2SpeedRing(Player player) { super(player, "src/Rings/T2SpdRing.png", "ring", true); speed = 8; equipItem(); } public String getInfo() { return "Increases Max Speed \nof Character by 8)"; } }
package cat.nyaa.infiniteinfernal.loot; import cat.nyaa.nyaacore.configuration.ISerializable; import org.bukkit.inventory.ItemStack; public interface ILootItem extends ISerializable { ItemStack getItemStack(); String getName(); String toNbt(); int getWeight(int level); boolean isDynamic(); void setDynamic(boolean dynamic); }
package com.kowaisugoi.game.graphics; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; /** * A transition is a type of animation which plays between rooms * At some point during the animation, it fires a callback which triggers a room change */ public interface Transition { public void draw(SpriteBatch batch); public void draw(ShapeRenderer renderer); public void update(float delta); public void play(); }