hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
f1538348dc5558d12c0f694a6b82d38d8d66582b
1,833
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tenant.example.web; import com.tenant.example.dto.UsuariosDTO; import com.tenant.example.service.UsuariosService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * * @author jhon */ @RestController @RequestMapping("/api/v.1/usuarios") public class UsuariosController { @Autowired private UsuariosService usuariosService; public UsuariosController(UsuariosService usuariosService) { this.usuariosService = usuariosService; } @GetMapping() public ResponseEntity<?> getAll() { List<UsuariosDTO> res = usuariosService.getAll(); if (res != null) { return ResponseEntity.ok(res); } return ResponseEntity.noContent().build(); } @PostMapping() public ResponseEntity<?> agregar(@RequestBody UsuariosDTO usu) { UsuariosDTO res = usuariosService.guardarUsuario(usu); return ResponseEntity.ok(res); } @DeleteMapping("{id}") public ResponseEntity<?> eliminar(@PathVariable("id") Integer id) { UsuariosDTO res = usuariosService.eliminarUsuario(id); return ResponseEntity.ok(res); } }
31.067797
79
0.740862
ee22a2a8bb180db9dd2c839c1060e5e16fd06f69
47
test itpjcore win search missing type reference
47
47
0.87234
9ae3e6c2b084c106b74849da8123507d69497009
2,727
package com.apachetune.core; import com.apachetune.core.utils.BooleanValue; import org.junit.Test; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.Fail.fail; /** * FIXDOC * * @author <a href="mailto:progmonster@gmail.com">Aleksey V. Katorgin</a> * @version 1.0 */ public class GenericWorkItemPropertyChangeListenerTest extends WorkItemAbstractTest { @Test public void testPropertyChangeEvent() { final PropertyChangeTestWorkItem workItem = new PropertyChangeTestWorkItem(); getRootWorkItem().addChildWorkItem(workItem); final BooleanValue isRaised = new BooleanValue(); workItem.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { isRaised.value = true; assertThat(evt.getSource()).isEqualTo(workItem); assertThat(evt.getPropertyName()).isEqualTo("fakeProperty"); assertThat(evt.getOldValue()).isEqualTo("fakeOldValue"); assertThat(evt.getNewValue()).isEqualTo("fakeNewValue"); } }); workItem.initialize(); workItem.fireEvent(); assertThat(isRaised.value).isTrue(); } @Test public void testRemoveListener() { final PropertyChangeTestWorkItem workItem = new PropertyChangeTestWorkItem(); getRootWorkItem().addChildWorkItem(workItem); PropertyChangeListener listener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { fail(); } }; workItem.addPropertyChangeListener(listener); workItem.removePropertyChangeListener(listener); workItem.initialize(); workItem.fireEvent(); } @Test public void testRemoveAllListeners() { final PropertyChangeTestWorkItem workItem = new PropertyChangeTestWorkItem(); getRootWorkItem().addChildWorkItem(workItem); PropertyChangeListener listener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { fail(); } }; workItem.addPropertyChangeListener(listener); workItem.removeAllPropertyChangeListeners(); workItem.initialize(); workItem.fireEvent(); } } class PropertyChangeTestWorkItem extends SimpleWorkItem { public PropertyChangeTestWorkItem() { super("TEST_WORK_ITEM"); } public void fireEvent() { firePropertyChangeEvent("fakeProperty", "fakeOldValue", "fakeNewValue"); } }
29.967033
85
0.675468
6be24809d38e6e753ee16267a48dd01572a63423
2,355
package org.gbif.registry.ws.security.jwt; import org.gbif.registry.ws.security.jwt.JwtConfiguration.GbifClaims; import java.util.Date; import java.util.Optional; import java.util.regex.Pattern; import javax.ws.rs.core.HttpHeaders; import com.sun.jersey.spi.container.ContainerRequest; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; public class JwtUtils { //Patterns that catches case insensitive versions of word 'bearer' private static final Pattern BEARER_PATTERN = Pattern.compile("(?i)bearer"); private JwtUtils() {} /** * Generates a JWT with the configuration specified. * <p> * It always sets the following fields: * <ul> * <li>expiration: takes the time from the {@link JwtConfiguration}</li> * <li>Issued time: sets the current time when the token is issued</li> * <li>Issuer: takes the issuer from the {@link JwtConfiguration}</li> * <li>Username claim: custom claim to store the username received as a parameter</li> * <li>signature: signs the token using {@link SignatureAlgorithm#HS256} and the key specified in the {@link JwtConfiguration}</li> * </ul> */ public static String generateJwt(String username, JwtConfiguration config) { return Jwts.builder() .setExpiration(new Date(System.currentTimeMillis() + config.getExpiryTimeInMs())) .setIssuedAt(new Date(System.currentTimeMillis())) .setIssuer(config.getIssuer()) .claim(GbifClaims.USERNAME, username) .signWith(SignatureAlgorithm.HS256, config.getSigningKey()) .compact(); } /** * Tries to find the token in the {@link HttpHeaders#AUTHORIZATION} header. */ public static Optional<String> findTokenInRequest(ContainerRequest containerRequest) { // check header first return Optional.ofNullable(containerRequest.getHeaderValue(HttpHeaders.AUTHORIZATION)) .filter(JwtUtils::containsBearer) .map(JwtUtils::removeBearer); } /** * Removes 'bearer' token, leading an trailing whitespaces. * * @param token to be clean * * @return a token without whitespaces and the word 'bearer' */ private static String removeBearer(String token) { return BEARER_PATTERN.matcher(token).replaceAll("").trim(); } private static boolean containsBearer(String header) { return BEARER_PATTERN.matcher(header).find(); } }
34.130435
133
0.72569
80b24cd22494b0a962802871eca4c1e16f7ea721
2,687
package com.nike.cerberus.auth.connector.okta.statehandlers; import com.nike.cerberus.auth.connector.AuthData; import com.nike.cerberus.auth.connector.AuthMfaDevice; import com.nike.cerberus.auth.connector.AuthResponse; import com.nike.cerberus.auth.connector.AuthStatus; import com.okta.authn.sdk.client.AuthenticationClient; import com.okta.authn.sdk.resource.AuthenticationResponse; import com.okta.authn.sdk.resource.Factor; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; /** * Initial state handler to handle relevant states during authentication. */ public class InitialLoginStateHandler extends AbstractOktaStateHandler { public InitialLoginStateHandler(AuthenticationClient client, CompletableFuture<AuthResponse> authenticationResponseFuture) { super(client, authenticationResponseFuture); } /** * Handles MFA required state * @param mfaRequiredResponse - Authentication response from the Completable Future */ @Override public void handleMfaRequired(AuthenticationResponse mfaRequiredResponse) { handleMfaResponse(mfaRequiredResponse); } /** * Handles MFA enroll state, when a user is not enrolled in any MFA factors. * @param mfaEnroll - Authentication response from the Completable Future */ @Override public void handleMfaEnroll(AuthenticationResponse mfaEnroll) { handleMfaResponse(mfaEnroll); } /** * Handles MFA states by determining valid user MFA factors. * @param mfaResponse - Authentication response from the Completable Future */ private void handleMfaResponse(AuthenticationResponse mfaResponse) { final String userId = mfaResponse.getUser().getId(); final String userLogin = mfaResponse.getUser().getLogin(); final AuthData authData = new AuthData() .setUserId(userId) .setUsername(userLogin); final AuthResponse authResponse = new AuthResponse().setData(authData); authData.setStateToken(mfaResponse.getStateToken()); authResponse.setStatus(AuthStatus.MFA_REQUIRED); final List<Factor> factors = mfaResponse.getFactors() .stream() .filter(this::isSupportedFactor) .collect(Collectors.toList()); validateUserFactors(factors); factors.forEach(factor -> authData.getDevices().add(new AuthMfaDevice() .setId(factor.getId()) .setName(getDeviceName(factor)) .setRequiresTrigger(isTriggerRequired(factor)))); authenticationResponseFuture.complete(authResponse); } }
36.808219
128
0.717901
002d03b13cb37fd611e5a1ac2b570302c2a8263b
1,428
package io.digdag.standards.operator; import java.nio.file.Path; import com.google.inject.Inject; import io.digdag.client.config.Config; import io.digdag.spi.TaskRequest; import io.digdag.spi.TaskResult; import io.digdag.spi.Operator; import io.digdag.spi.OperatorFactory; import io.digdag.util.BaseOperator; public class IfOperatorFactory implements OperatorFactory { @Inject public IfOperatorFactory() { } public String getType() { return "if"; } @Override public Operator newTaskExecutor(Path workspacePath, TaskRequest request) { return new IfOperator(workspacePath, request); } private static class IfOperator extends BaseOperator { public IfOperator(Path workspacePath, TaskRequest request) { super(workspacePath, request); } @Override public TaskResult runTask() { Config params = request.getConfig(); Config doConfig = request.getConfig().getNested("_do"); boolean condition = params.get("_command", boolean.class); if (condition) { return TaskResult.defaultBuilder(request) .subtaskConfig(doConfig) .build(); } else { return TaskResult.defaultBuilder(request) .build(); } } } }
24.20339
76
0.604342
0ee6c3554beedaaaca38f9a16783894c480e4b1c
12,228
package com.example.android.newsapp; import android.annotation.SuppressLint; import android.app.LoaderManager; import android.content.AsyncTaskLoader; import android.content.Context; import android.content.Intent; import android.content.Loader; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<String> { private ListView list_view; ArrayList<HashMap<String, String>> newsList; ArrayList<HashMap<String, Drawable>> imageList; private static NewsAdapter mAdapter; private static List<String> webPages = new ArrayList<>(); TextView warningTV; ImageView warningIV; private static final int NEWS_LOADER_ID = 1; private String author; private static String webUrl; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); newsList = new ArrayList<>(); imageList = new ArrayList<>(); list_view = findViewById(R.id.list); warningTV = findViewById(R.id.warning); warningIV = findViewById(R.id.warning_image); ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { LoaderManager loaderManager = getLoaderManager(); Loader<String> loader = loaderManager.getLoader(NEWS_LOADER_ID); if (loader == null) { loaderManager.initLoader(NEWS_LOADER_ID, null, this); } else { loaderManager.restartLoader(NEWS_LOADER_ID, null, this); } } else { View loadingIndicator = findViewById(R.id.progress_bar); loadingIndicator.setVisibility(View.GONE); warningTV.setText(getString(R.string.noInternet)); list_view.setEmptyView(warningTV); warningIV.setImageResource(R.drawable.ic_no_internet); list_view.setEmptyView(warningIV); } list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { // Convert the String URL into a URI object (to pass into the Intent constructor) Uri newsUri = Uri.parse(webPages.get(position)); // Create a new intent to view the news URI Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri); PackageManager packageManager = getPackageManager(); List<ResolveInfo> activities = packageManager.queryIntentActivities(websiteIntent, PackageManager.MATCH_DEFAULT_ONLY); boolean isIntentSafe = activities.size() > 0; if (isIntentSafe) { // Send the intent to launch a new activity startActivity(websiteIntent); } newsList.clear(); imageList.clear(); webPages.clear(); } }); } @SuppressLint("StaticFieldLeak") @Override public Loader<String> onCreateLoader(int i, Bundle bundle) { // TODO: Create a new loader for the given URL return new AsyncTaskLoader<String>(this) { String resultFromHttp; @Override public String loadInBackground() { HttpHandler handler = new HttpHandler(); String url = "http://content.guardianapis.com/search?order-by=newest&show-tags=contributor&page-size=20&api-key=9e7553cb-4f7d-42c4-86dc-7d8942aef35d&show-fields=thumbnail"; String jsonString = ""; try { jsonString = handler.makeHttpRequest(createUrl(url)); } catch (IOException e) { return null; } if (jsonString != null) { try { JSONObject jsonObject = new JSONObject(jsonString); JSONObject response = jsonObject.getJSONObject(getString(R.string.response)); JSONArray results = response.getJSONArray(getString(R.string.results)); // looping through all Contacts for (int i = 0; i < results.length(); i++) { try { JSONObject article = results.getJSONObject(i); String title = article.getString(getString(R.string.webTitle)); String date = article.getString(getString(R.string.webPublicationDate)); String section = article.getString(getString(R.string.sectionName)); webUrl = article.getString(getString(R.string.webUrl)); JSONObject field = article.getJSONObject(getString(R.string.fields)); String thumbnail = field.getString(getString(R.string.thumbnail)); Drawable image = LoadImageFromWebOperations(thumbnail); JSONArray tags = article.getJSONArray(getString(R.string.tags)); for (int j = 0; j < tags.length(); j++) { try { JSONObject authorInfo = tags.getJSONObject(j); author = authorInfo.getString(getString(R.string.webTitle)); } catch (final JSONException e) { e.printStackTrace(); } } HashMap<String, String> result = new HashMap<>(); // add each child node to HashMap key => value result.put(getString(R.string.title), title); result.put(getString(R.string.webPublicationDate), date); result.put(getString(R.string.sectionName), section); result.put(getString(R.string.author), author); HashMap<String, Drawable> iv = new HashMap<>(); iv.put(getString(R.string.thumbnail), image); // adding a news to our news list newsList.add(result); imageList.add(iv); runOnUiThread(new Runnable() { @Override public void run() { try { webPages.add(webUrl); mAdapter = new NewsAdapter(MainActivity.this, newsList, imageList); if(mAdapter!=null) { mAdapter.notifyDataSetChanged(); } list_view.setAdapter(mAdapter); View loadingIndicator = findViewById(R.id.progress_bar); loadingIndicator.setVisibility(View.GONE); }catch(IllegalStateException e){ e.printStackTrace(); } } }); } catch (final JSONException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), getString(R.string.parsingError) + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } } catch (final JSONException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), getString(R.string.parsingError) + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } else { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), getString(R.string.notGetJson), Toast.LENGTH_LONG).show(); } }); } return null; } private URL createUrl(String stringUrl) { URL url; try { url = new URL(stringUrl); } catch (MalformedURLException exception) { return null; } return url; } private Drawable LoadImageFromWebOperations(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); return Drawable.createFromStream(is, getString(R.string.thumbnail)); } catch (Exception e) { return null; } } @Override protected void onStartLoading() { if (resultFromHttp != null) { //To skip loadInBackground call deliverResult(resultFromHttp); } else { forceLoad(); } } }; } @SuppressLint("ResourceType") public void onLoadFinished(Loader<String> loader, String data) { // TODO: Update the UI with the result if (newsList != null && !newsList.isEmpty()) { warningIV.setVisibility(View.GONE); View loadingIndicator = findViewById(R.id.progress_bar); loadingIndicator.setVisibility(View.GONE); } else { View loadingIndicator = findViewById(R.id.progress_bar); loadingIndicator.setVisibility(View.GONE); warningTV.setText(getString(R.string.noNews)); list_view.setEmptyView(warningTV); list_view.setEmptyView(warningIV); } } @Override public void onLoaderReset(Loader<String> loader) { // TODO: Loader reset, so we can clear out our existing data. newsList.clear(); imageList.clear(); webPages.clear(); } public void onResume() { newsList.clear(); imageList.clear(); webPages.clear(); super.onResume(); } }
40.091803
188
0.508587
7d6fdd7de0083cea05a9c6e7cb6b9dd316b6849c
1,025
package me.vrekt.fortnitexmpp.party.implementation.request.authentication; import me.vrekt.fortnitexmpp.party.implementation.Party; import me.vrekt.fortnitexmpp.party.implementation.request.PartyRequest; import me.vrekt.fortnitexmpp.party.implementation.request.RequestBuilder; import me.vrekt.fortnitexmpp.party.type.PartyType; import javax.json.Json; /** * A acknowledgement request acknowledging you can join a party. */ public final class PartyJoinAcknowledged implements PartyRequest { private final String payload; /** * Initialize the request. * * @param party the party */ public PartyJoinAcknowledged(final Party party) { final var type = PartyType.PARTY_JOIN_ACKNOWLEDGED; this.payload = RequestBuilder.buildRequest( Json.createObjectBuilder() .add("partyId", party.partyId()).build(), type).toString(); } @Override public String payload() { return payload; } }
30.147059
84
0.686829
76c7a45fdb0459586efb85bb43c08f68cb9d23ad
3,406
package xyz.corman.velt; import java.util.HashMap; import java.util.List; import java.util.Map; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.EnvironmentAccess; import org.graalvm.polyglot.HostAccess; public class ContextCreation { public static void graalJSRequire(String moduleFolder, Map<String, String> options) { // Enable CommonJS experimental support. //options.put("js.commonjs-require", "true"); // (optional) folder where the Npm modules to be loaded are located. //options.put("js.commonjs-require-cwd", moduleFolder); // (optional) initialization script to pre-define globals. //options.put("js.commonjs-global-properties", "globals"); // (optional) Java jars as a comma separated list. //options.put("jvm.classpath", classpath.stream().collect(Collectors.joining(","))); // (optional) Node.js built-in replacements as a comma separated list. /*options.put( "js.commonjs-core-modules-replacements", "timers:core/intervals,fs:core/filesystem,events:core/emitter,path:core/paths,domain:core/domains,os:core/osmod,punycode:core/punycodes," + "tty:core/ttymod,assert:core/assertions,buffer:core/buffers,util:core/utils,querystring:core/querystrings," + "string_decoder:core/string_decode,url:core/urls,console:core/consolemod,http:core/httpmod,https:core/httpsmod," + "stream:core/streams,zlib:browserify-zlib,process:core/process" );*/ /*options.put( "js.commonjs-core-modules-replacements", "timers:lib/timers,fs:lib/fs,events:lib/events,path:lib/path,domain:lib/domain,os:lib/os,punycode:lib/punycode,tty:lib/tty,assert:lib/assert," + "buffer:lib/buffer,util:lib/util,querystring:lib/querystring,string_decoder:lib/string_decoder,url:lib/url,console:lib/console,http:lib/http," + "https:lib/https,stream:lib/stream,zlib:lib/zlib,process:lib/process" );*/ } public static Context createSecureContext(Map<String, String> options) { HostAccess hostAccess = HostAccess.newBuilder(HostAccess.NONE) .targetTypeMapping(Double.class, Float.class, null, x -> x.floatValue()) .build(); Context context = Context.newBuilder("js") .allowExperimentalOptions(false) .allowIO(false) .allowCreateProcess(false) .allowCreateThread(false) .allowHostClassLookup(c -> { return false; }) .allowNativeAccess(false) .allowEnvironmentAccess(EnvironmentAccess.NONE) .options(options) .build(); return context; } public static Context createContext(Map<String, String> options) { HostAccess hostAccess = HostAccess.newBuilder(HostAccess.ALL) .targetTypeMapping(Double.class, Float.class, null, x -> x.floatValue()) .build(); Context context = Context.newBuilder("js") .allowExperimentalOptions(true) .allowIO(true) .allowHostAccess(hostAccess) .allowHostClassLookup(c -> true) .allowNativeAccess(true) .allowCreateThread(true) .allowCreateProcess(true) .options(options) .build(); return context; } public static Context createContext() { return createContext(new HashMap<String, String>()); } public static Context createContext(String moduleFolder, List<String> classpath) { Map<String, String> options = new HashMap<String, String>(); graalJSRequire(moduleFolder, options); return createContext(options); } }
43.666667
147
0.7202
f0d8257ebb50e07c67459edc21b58894ec21cd69
2,752
package org.corpus_tools.annis.gui.visualizers.iframe; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.vaadin.server.VaadinSession; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import java.util.List; import javax.servlet.ServletContext; import org.corpus_tools.annis.gui.AnnisUI; import org.corpus_tools.annis.gui.VisualizationToggle; import org.corpus_tools.annis.gui.visualizers.VisualizerInput; import org.corpus_tools.annis.gui.visualizers.iframe.CorefVisualizer; import org.corpus_tools.salt.common.SDocument; import org.corpus_tools.salt.common.SDocumentGraph; import org.corpus_tools.salt.common.SToken; import org.corpus_tools.salt.common.SaltProject; import org.corpus_tools.salt.samples.SampleGenerator; import org.jsoup.Jsoup; import org.jsoup.select.Elements; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class CorefVisualizerTest { private CorefVisualizer vis; private AnnisUI ui; private VisualizerInput visInput; private VisualizationToggle visToggle; private VaadinSession session; private ServletContext servletContext; @BeforeEach void setup() { vis = new CorefVisualizer(); // Init mocks visInput = mock(VisualizerInput.class); visToggle = mock(VisualizationToggle.class); ui = mock(AnnisUI.class); session = mock(VaadinSession.class); servletContext = mock(ServletContext.class); when(visInput.getUI()).thenReturn(ui); when(ui.getSession()).thenReturn(session); when(ui.getServletContext()).thenReturn(servletContext); } @Test void tokenGenerated() { // Use the example document from Salt SaltProject project = SampleGenerator.createSaltProject(); SDocument doc = project.getCorpusGraphs().get(0).getDocuments().get(0); SDocumentGraph graph = doc.getDocumentGraph(); when(visInput.getDocument()).thenReturn(doc); // Create the resource as string ByteArrayOutputStream outStream = new ByteArrayOutputStream(); vis.writeOutput(visInput, outStream); String content = new String(outStream.toByteArray(), StandardCharsets.UTF_8); assertNotNull(content); // Parse the HTML and check that all token have been generated as td cell Elements tokenElements = Jsoup.parse(content).select("table.token td"); List<SToken> tokens = graph.getSortedTokenByText(); assertEquals(tokens.size(), tokenElements.size()); for (int i = 0; i < tokens.size(); i++) { SToken tok = tokens.get(i); assertEquals(graph.getText(tok), tokenElements.get(i).text().trim()); } } }
33.560976
81
0.763081
3b002621b74cb056ab8572ef83b02147e83ff7c4
6,352
package com.hbm.packet; import java.io.IOException; import com.hbm.items.ModItems; import com.hbm.items.machine.ItemAssemblyTemplate; import com.hbm.items.machine.ItemCassette; import com.hbm.items.machine.ItemChemistryTemplate; import com.hbm.items.machine.ItemForgeFluidIdentifier; import com.hbm.lib.Library; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; public class ItemFolderPacket implements IMessage { ItemStack stack; PacketBuffer buffer; public ItemFolderPacket() { } public ItemFolderPacket(ItemStack stack) { buffer = new PacketBuffer(Unpooled.buffer()); buffer.writeCompoundTag(stack.writeToNBT(new NBTTagCompound())); } @Override public void fromBytes(ByteBuf buf) { if (buffer == null) { buffer = new PacketBuffer(Unpooled.buffer()); } buffer.writeBytes(buf); try { stack = new ItemStack(buffer.readCompoundTag()); } catch(IOException e) { e.printStackTrace(); } } @Override public void toBytes(ByteBuf buf) { if (buffer == null) { buffer = new PacketBuffer(Unpooled.buffer()); } buf.writeBytes(buffer); } public static class Handler implements IMessageHandler<ItemFolderPacket, IMessage> { @Override public IMessage onMessage(ItemFolderPacket m, MessageContext ctx) { EntityPlayer p = ctx.getServerHandler().player; if(m.stack == null) return null; p.getServer().addScheduledTask(() -> { if(p.getHeldItemMainhand().getItem() != ModItems.template_folder && p.getHeldItemOffhand().getItem() != ModItems.template_folder) return; ItemStack stack = m.stack; if(p.capabilities.isCreativeMode) { p.inventory.addItemStackToInventory(stack.copy()); return; } if(stack.getItem() instanceof ItemForgeFluidIdentifier) { if(Library.hasInventoryOreDict(p.inventory, "plateIron") && Library.hasInventoryItem(p.inventory, Items.DYE)) { Library.consumeInventoryItem(p.inventory, ModItems.plate_iron); Library.consumeInventoryItem(p.inventory, Items.DYE); if(!p.inventory.addItemStackToInventory(stack.copy())) p.dropItem(stack, true); } } if(stack.getItem() instanceof ItemAssemblyTemplate) { if(Library.hasInventoryItem(p.inventory, Items.PAPER) && Library.hasInventoryItem(p.inventory, Items.DYE)) { Library.consumeInventoryItem(p.inventory, Items.PAPER); Library.consumeInventoryItem(p.inventory, Items.DYE); if(!p.inventory.addItemStackToInventory(stack.copy())) p.dropItem(stack, true); } } if(stack.getItem() instanceof ItemChemistryTemplate) { if(Library.hasInventoryItem(p.inventory, Items.PAPER) && Library.hasInventoryItem(p.inventory, Items.DYE)) { Library.consumeInventoryItem(p.inventory, Items.PAPER); Library.consumeInventoryItem(p.inventory, Items.DYE); if(!p.inventory.addItemStackToInventory(stack.copy())) p.dropItem(stack, true); } } if(stack.getItem() instanceof ItemCassette) { if(Library.hasInventoryItem(p.inventory, ModItems.plate_polymer) && Library.hasInventoryItem(p.inventory, ModItems.plate_steel)) { Library.consumeInventoryItem(p.inventory, ModItems.plate_polymer); Library.consumeInventoryItem(p.inventory, ModItems.plate_steel); if(!p.inventory.addItemStackToInventory(stack.copy())) p.dropItem(stack, true); } } if(stack.getItem() == ModItems.stamp_stone_plate || stack.getItem() == ModItems.stamp_stone_wire || stack.getItem() == ModItems.stamp_stone_circuit) { if(Library.hasInventoryItem(p.inventory, ModItems.stamp_stone_flat)) { Library.consumeInventoryItem(p.inventory, ModItems.stamp_stone_flat); if(!p.inventory.addItemStackToInventory(stack.copy())) p.dropItem(stack, true); } } if(stack.getItem() == ModItems.stamp_iron_plate || stack.getItem() == ModItems.stamp_iron_wire || stack.getItem() == ModItems.stamp_iron_circuit) { if(Library.hasInventoryItem(p.inventory, ModItems.stamp_iron_flat)) { Library.consumeInventoryItem(p.inventory, ModItems.stamp_iron_flat); if(!p.inventory.addItemStackToInventory(stack.copy())) p.dropItem(stack, true); } } if(stack.getItem() == ModItems.stamp_steel_plate || stack.getItem() == ModItems.stamp_steel_wire || stack.getItem() == ModItems.stamp_steel_circuit) { if(Library.hasInventoryItem(p.inventory, ModItems.stamp_steel_flat)) { Library.consumeInventoryItem(p.inventory, ModItems.stamp_steel_flat); if(!p.inventory.addItemStackToInventory(stack.copy())) p.dropItem(stack, true); } } if(stack.getItem() == ModItems.stamp_titanium_plate || stack.getItem() == ModItems.stamp_titanium_wire || stack.getItem() == ModItems.stamp_titanium_circuit) { if(Library.hasInventoryItem(p.inventory, ModItems.stamp_titanium_flat)) { Library.consumeInventoryItem(p.inventory, ModItems.stamp_titanium_flat); if(!p.inventory.addItemStackToInventory(stack.copy())) p.dropItem(stack, true); } } if(stack.getItem() == ModItems.stamp_obsidian_plate || stack.getItem() == ModItems.stamp_obsidian_wire || stack.getItem() == ModItems.stamp_obsidian_circuit) { if(Library.hasInventoryItem(p.inventory, ModItems.stamp_obsidian_flat)) { Library.consumeInventoryItem(p.inventory, ModItems.stamp_obsidian_flat); if(!p.inventory.addItemStackToInventory(stack.copy())) p.dropItem(stack, true); } } if(stack.getItem() == ModItems.stamp_schrabidium_plate || stack.getItem() == ModItems.stamp_schrabidium_wire || stack.getItem() == ModItems.stamp_schrabidium_circuit) { if(Library.hasInventoryItem(p.inventory, ModItems.stamp_schrabidium_flat)) { Library.consumeInventoryItem(p.inventory, ModItems.stamp_schrabidium_flat); if(!p.inventory.addItemStackToInventory(stack.copy())) p.dropItem(stack, true); } } }); return null; } } }
40.202532
172
0.728747
c80a6b01e6a46d152e8b863e7c073bd12f7dfc41
443
package org.edu.nju.dao; import java.util.List; import org.edu.nju.model.Commodity; public class CommodityDao { public Commodity getCommodityByCatalog(String s) { // TODO Auto-generated method stub return null; } public List<Commodity> getAllCommodity() { // TODO Auto-generated method stub return null; } public Commodity getCommodityById(String commodityId) { // TODO Auto-generated method stub return null; } }
15.821429
56
0.733634
33227a29128b5b80b4a2c03db7e7ff32c88dc789
24,726
package com.bitdubai.fermat_cbp_plugin.layer.network_service.negotiation_transmission.developer.bitdubai.version_1.database; import com.bitdubai.fermat_api.FermatException; import com.bitdubai.fermat_api.layer.all_definition.components.enums.PlatformComponentType; import com.bitdubai.fermat_api.layer.all_definition.exceptions.InvalidParameterException; import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterOperator; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseFilterType; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableFilter; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction; import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantInsertRecordException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseTransactionFailedException; import com.bitdubai.fermat_cbp_api.all_definition.enums.NegotiationTransactionType; import com.bitdubai.fermat_cbp_api.all_definition.enums.NegotiationTransmissionState; import com.bitdubai.fermat_cbp_api.all_definition.enums.NegotiationTransmissionType; import com.bitdubai.fermat_cbp_api.layer.network_service.negotiation_transmission.interfaces.NegotiationTransmission; import com.bitdubai.fermat_cbp_plugin.layer.network_service.negotiation_transmission.developer.bitdubai.version_1.exceptions.CantGetNegotiationTransmissionException; import com.bitdubai.fermat_cbp_plugin.layer.network_service.negotiation_transmission.developer.bitdubai.version_1.exceptions.CantInitializeDatabaseException; import com.bitdubai.fermat_cbp_plugin.layer.network_service.negotiation_transmission.developer.bitdubai.version_1.exceptions.CantRegisterSendNegotiationTransmissionException; import com.bitdubai.fermat_cbp_plugin.layer.network_service.negotiation_transmission.developer.bitdubai.version_1.exceptions.CantReadRecordDataBaseException; import com.bitdubai.fermat_cbp_plugin.layer.network_service.negotiation_transmission.developer.bitdubai.version_1.structure.NegotiationTransmissionImpl; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; /** * Created by Yordin Alayn on 26.11.15. */ public class NegotiationTransmissionNetworkServiceDatabaseDao { private PluginDatabaseSystem pluginDatabaseSystem; private UUID pluginId; private Database database; public NegotiationTransmissionNetworkServiceDatabaseDao(PluginDatabaseSystem pluginDatabaseSystem, UUID pluginId, Database database) { this.pluginDatabaseSystem = pluginDatabaseSystem; this.pluginId = pluginId; this.database = database; } /*INITIALIZE DATABASE*/ public void initialize() throws CantInitializeDatabaseException { try { database = this.pluginDatabaseSystem.openDatabase(this.pluginId, NegotiationTransmissionNetworkServiceDatabaseConstants.DATA_BASE_NAME); } catch (DatabaseNotFoundException e) { try { NegotiationTransmissionNetworkServiceDatabaseFactory databaseFactory = new NegotiationTransmissionNetworkServiceDatabaseFactory(pluginDatabaseSystem); database = databaseFactory.createDatabase(pluginId, pluginId.toString()); } catch (CantCreateDatabaseException f) { throw new CantInitializeDatabaseException(CantCreateDatabaseException.DEFAULT_MESSAGE, f, "", "There is a problem and i cannot create the database."); } catch (Exception z) { throw new CantInitializeDatabaseException(CantOpenDatabaseException.DEFAULT_MESSAGE, z, "", "Generic Exception."); } } catch (CantOpenDatabaseException e) { throw new CantInitializeDatabaseException(CantOpenDatabaseException.DEFAULT_MESSAGE, e, "", "Exception not handled by the plugin, there is a problem and i cannot open the database."); } catch (Exception e) { throw new CantInitializeDatabaseException(CantOpenDatabaseException.DEFAULT_MESSAGE, e, "", "Generic Exception."); } } Database getDataBase() { return database; } DatabaseTable getDatabaseTable() { return getDataBase().getTable(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); } /*REGISTER NEW SEND NEGOTIATION TRANSMISSION*/ public void registerSendNegotiatioTransmission(NegotiationTransmission negotiationTransmission,NegotiationTransmissionState negotiationTransmissionState) throws CantRegisterSendNegotiationTransmissionException{ try { DatabaseTable table = this.database.getTable(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); DatabaseTableRecord record = table.getEmptyRecord(); loadRecordAsSendNegotiatioTransmission(record,negotiationTransmission,negotiationTransmissionState); table.insertRecord(record); } catch (CantInsertRecordException e){ throw new CantRegisterSendNegotiationTransmissionException (CantRegisterSendNegotiationTransmissionException.DEFAULT_MESSAGE + ". CAN'T REGISTER IN DATABSE A NEGOTIATION TRANSMISSION", e, "ERROR SEND CONFIRM TO CRYPTO BROKER", ""); } catch (Exception e){ throw new CantRegisterSendNegotiationTransmissionException(e.getMessage(), FermatException.wrapException(e), "CAN'T CREATE REGISTER NEGOTIATION TRANSMISSION TO CRYPTO BROKER", "ERROR SEND CONFIRM TO CRYPTO BROKER, UNKNOWN FAILURE."); } } /*UPDATE REGISTER SEND NEGOTIATION TRANSMISSION*/ public void updateRegisterSendNegotiatioTransmission(NegotiationTransmission negotiationTransmission) throws CantRegisterSendNegotiationTransmissionException { if (negotiationTransmission == null) { throw new IllegalArgumentException("The entity is required, can not be null"); } try { DatabaseTable table = this.database.getTable(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); DatabaseTableRecord record = table.getEmptyRecord(); loadRecordAsSendNegotiatioTransmission(record,negotiationTransmission); DatabaseTransaction transaction = getDataBase().newTransaction(); transaction.addRecordToUpdate(getDatabaseTable(), record); getDataBase().executeTransaction(transaction); } catch (DatabaseTransactionFailedException e) { StringBuffer contextBuffer = new StringBuffer(); contextBuffer.append("Table Name: " + NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); throw new CantRegisterSendNegotiationTransmissionException (CantRegisterSendNegotiationTransmissionException.DEFAULT_MESSAGE + ". CAN'T UPDATE REGISTER IN DATABSE A NEGOTIATION TRANSMISSION", e, contextBuffer.toString(), "The record do not exist"); } } /*CONFIRM RECEPTION*/ public void confirmReception(UUID transmissionId) throws CantRegisterSendNegotiationTransmissionException { try { // NegotiationTransmission negotiationTransmission = getNegotiationTransmissionRecord(transmissionId); // negotiationTransmission.confirmRead(); // updateRegisterSendNegotiatioTransmission(negotiationTransmission); NegotiationTransmissionState state = NegotiationTransmissionState.CONFIRM_NEGOTIATION; this.changeState(transmissionId, state); } catch (CantRegisterSendNegotiationTransmissionException e) { StringBuffer contextBuffer = new StringBuffer(); contextBuffer.append("Table Name: " + NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); throw new CantRegisterSendNegotiationTransmissionException (CantRegisterSendNegotiationTransmissionException.DEFAULT_MESSAGE + ". CAN'T CONFIRM RECEPTION IN REGISTER OF DATABSE NEGOTIATION TRANSMISSION", e, contextBuffer.toString(), "The record do not exist"); } } /** * Method that list the all entities on the data base. The valid value of * the key are the att of the <code>TemplateNetworkServiceDatabaseConstants</code> * * @param filters * @return List<FermatMessage> * @throws CantRegisterSendNegotiationTransmissionException */ public List<NegotiationTransmission> findAll(Map<String, Object> filters) throws CantReadRecordDataBaseException { if (filters == null || filters.isEmpty()) { throw new IllegalArgumentException("The filters are required, can not be null or empty"); } List<NegotiationTransmission> list = null; List<DatabaseTableFilter> filtersTable = new ArrayList<>(); try { DatabaseTable table = this.database.getTable(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); for (String key : filters.keySet()) { DatabaseTableFilter newFilter = table.getEmptyTableFilter(); newFilter.setType(DatabaseFilterType.EQUAL); newFilter.setColumn(key); newFilter.setValue((String) filters.get(key)); filtersTable.add(newFilter); } table.setFilterGroup(filtersTable, null, DatabaseFilterOperator.OR); // table.setStringFilter(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_ID_COLUMN_NAME, "23", DatabaseFilterType.EQUAL); table.loadToMemory(); List<DatabaseTableRecord> records = table.getRecords(); list = new ArrayList<>(); list.clear(); for (DatabaseTableRecord record : records) { NegotiationTransmission outgoingTemplateNetworkServiceMessage = constructNegotiationTransmission(record); list.add(outgoingTemplateNetworkServiceMessage); } } catch (CantLoadTableToMemoryException e) { StringBuffer contextBuffer = new StringBuffer(); contextBuffer.append("Table Name: " + NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); throw new CantReadRecordDataBaseException (CantRegisterSendNegotiationTransmissionException.DEFAULT_MESSAGE, e, contextBuffer.toString(), "The data no exist"); } catch (InvalidParameterException e) { throw new CantReadRecordDataBaseException (CantRegisterSendNegotiationTransmissionException.DEFAULT_MESSAGE, e, "", "Invalid parameter"); } return list; } /** * Method that update an CryptoTransmissionMetadata in the data base. * * @throws CantRegisterSendNegotiationTransmissionException */ public void changeState(UUID transmissionId, NegotiationTransmissionState negotiationTransmissionState) throws CantRegisterSendNegotiationTransmissionException { if (transmissionId == null) { throw new IllegalArgumentException("The entity is required, can not be null"); } try { NegotiationTransmission negotiationTransmission = getNegotiationTransmissionRecord(transmissionId); negotiationTransmission.setTransmissionState(negotiationTransmissionState); DatabaseTable table = this.database.getTable(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); DatabaseTableRecord record = table.getEmptyRecord(); //1- Create the record to the entity loadRecordAsSendNegotiatioTransmission(record, negotiationTransmission); //2.- Create a new transaction and execute DatabaseTransaction transaction = getDataBase().newTransaction(); transaction.addRecordToUpdate(getDatabaseTable(), record); getDataBase().executeTransaction(transaction); } catch (DatabaseTransactionFailedException databaseTransactionFailedException) { StringBuffer contextBuffer = new StringBuffer(); contextBuffer.append("Table Name: " + NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); throw new CantRegisterSendNegotiationTransmissionException (CantRegisterSendNegotiationTransmissionException.DEFAULT_MESSAGE, databaseTransactionFailedException, contextBuffer.toString(), "The data no exist"); } catch (CantGetNegotiationTransmissionException e) { e.printStackTrace(); } } public void changeState(NegotiationTransmission negotiationTransmission) throws CantRegisterSendNegotiationTransmissionException { if (negotiationTransmission == null) { throw new IllegalArgumentException("The entity is required, can not be null"); } try { DatabaseTable table = this.database.getTable(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); DatabaseTableRecord record = table.getEmptyRecord(); /* * 1- Create the record to the entity */ loadRecordAsSendNegotiatioTransmission(record, negotiationTransmission); /* * 2.- Create a new transaction and execute */ DatabaseTransaction transaction = getDataBase().newTransaction(); transaction.addRecordToUpdate(getDatabaseTable(), record); getDataBase().executeTransaction(transaction); } catch (DatabaseTransactionFailedException databaseTransactionFailedException) { StringBuffer contextBuffer = new StringBuffer(); contextBuffer.append("Table Name: " + NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TABLE_NAME); throw new CantRegisterSendNegotiationTransmissionException (CantRegisterSendNegotiationTransmissionException.DEFAULT_MESSAGE, databaseTransactionFailedException, contextBuffer.toString(), "The data no exist"); } } public NegotiationTransmission getNegotiationTransmissionRecord(UUID transmissionId) throws CantGetNegotiationTransmissionException { if (transmissionId == null) throw new CantGetNegotiationTransmissionException("",null, "requestId, can not be null",""); try { DatabaseTable databaseTable = getDatabaseTable(); databaseTable.addUUIDFilter(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_ID_COLUMN_NAME, transmissionId, DatabaseFilterType.EQUAL); databaseTable.loadToMemory(); List<DatabaseTableRecord> records = databaseTable.getRecords(); if (!records.isEmpty()) return constructNegotiationTransmission(records.get(0)); else throw new CantGetNegotiationTransmissionException(null, "RequestID: "+transmissionId, "Cannot find an address exchange request with the given request id."); } catch (CantLoadTableToMemoryException exception) { throw new CantGetNegotiationTransmissionException("",exception, "Exception not handled by the plugin, there is a problem in database and i cannot load the table.",""); } catch (InvalidParameterException exception) { throw new CantGetNegotiationTransmissionException("",exception, "Check the cause.",""); } } /*PRIVATE*/ private NegotiationTransmission constructNegotiationTransmission(DatabaseTableRecord record) throws InvalidParameterException{ NegotiationTransmission negotiationTransmission = null; UUID transmissionId = record.getUUIDValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_ID_COLUMN_NAME); UUID transactionId = record.getUUIDValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSACTION_ID_COLUMN_NAME); UUID negotiationId = record.getUUIDValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_NEGOTIATION_ID_COLUMN_NAME); NegotiationTransactionType transactionType = NegotiationTransactionType.getByCode(record.getStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_NEGOTIATION_TRANSACTION_TYPE_COLUMN_NAME)); String publicKeyActorSend = record.getStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_PUBLIC_KEY_ACTOR_SEND_COLUMN_NAME); PlatformComponentType actorSendType = PlatformComponentType.getByCode(record.getStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_ACTOR_SEND_TYPE_COLUMN_NAME)); String publicKeyActorReceive = record.getStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_PUBLIC_KEY_ACTOR_RECEIVE_COLUMN_NAME); PlatformComponentType actorReceiveType = PlatformComponentType.getByCode(record.getStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_ACTOR_RECEIVE_TYPE_COLUMN_NAME)); NegotiationTransmissionType transmissionType = NegotiationTransmissionType.getByCode(record.getStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_TYPE_COLUMN_NAME)); NegotiationTransmissionState transmissionState = NegotiationTransmissionState.getByCode(record.getStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_STATE_COLUMN_NAME)); long timestamp = record.getLongValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TIMESTAMP_COLUMN_NAME); negotiationTransmission = new NegotiationTransmissionImpl( transmissionId, transactionId, negotiationId, transactionType, publicKeyActorSend, actorSendType, publicKeyActorReceive, actorReceiveType, transmissionType, transmissionState, timestamp ); return negotiationTransmission; } private void loadRecordAsSendNegotiatioTransmission(DatabaseTableRecord record, NegotiationTransmission negotiationTransmission) { record.setUUIDValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_ID_COLUMN_NAME, negotiationTransmission.getTransmissionId()); record.setUUIDValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSACTION_ID_COLUMN_NAME, negotiationTransmission.getTransactionId()); record.setUUIDValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_NEGOTIATION_ID_COLUMN_NAME, negotiationTransmission.getNegotiationId()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_NEGOTIATION_TRANSACTION_TYPE_COLUMN_NAME, negotiationTransmission.getTransmissionType().getCode()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_PUBLIC_KEY_ACTOR_SEND_COLUMN_NAME, negotiationTransmission.getPublicKeyActorSend()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_ACTOR_SEND_TYPE_COLUMN_NAME, negotiationTransmission.getActorSendType().getCode()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_PUBLIC_KEY_ACTOR_RECEIVE_COLUMN_NAME, negotiationTransmission.getPublicKeyActorReceive()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_ACTOR_RECEIVE_TYPE_COLUMN_NAME, negotiationTransmission.getActorReceiveType().getCode()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_TYPE_COLUMN_NAME, negotiationTransmission.getTransmissionType().getCode()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_STATE_COLUMN_NAME, negotiationTransmission.getTransmissionState().getCode()); record.setLongValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TIMESTAMP_COLUMN_NAME, negotiationTransmission.getTimestamp()); } private void loadRecordAsSendNegotiatioTransmission(DatabaseTableRecord record, NegotiationTransmission negotiationTransmission, NegotiationTransmissionState negotiationTransmissionState) { record.setUUIDValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_ID_COLUMN_NAME, negotiationTransmission.getTransmissionId()); record.setUUIDValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSACTION_ID_COLUMN_NAME, negotiationTransmission.getTransactionId()); record.setUUIDValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_NEGOTIATION_ID_COLUMN_NAME, negotiationTransmission.getNegotiationId()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_NEGOTIATION_TRANSACTION_TYPE_COLUMN_NAME, negotiationTransmission.getTransmissionType().getCode()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_PUBLIC_KEY_ACTOR_SEND_COLUMN_NAME, negotiationTransmission.getPublicKeyActorSend()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_ACTOR_SEND_TYPE_COLUMN_NAME, negotiationTransmission.getActorSendType().getCode()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_PUBLIC_KEY_ACTOR_RECEIVE_COLUMN_NAME, negotiationTransmission.getPublicKeyActorReceive()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_ACTOR_RECEIVE_TYPE_COLUMN_NAME, negotiationTransmission.getActorReceiveType().getCode()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_TYPE_COLUMN_NAME, negotiationTransmission.getTransmissionType().getCode()); record.setStringValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TRANSMISSION_STATE_COLUMN_NAME, negotiationTransmissionState.getCode()); record.setLongValue(NegotiationTransmissionNetworkServiceDatabaseConstants.NEGOTIATION_TRANSMISSION_NETWORK_SERVICE_TIMESTAMP_COLUMN_NAME, negotiationTransmission.getTimestamp()); } }
73.153846
272
0.788765
40b022824ee4d5977561cfd233840f2973934818
465
package com.redhat.uxl.services.service.dto; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; import lombok.Data; /** * The type Learning locker node dto. */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class LearningLockerNodeDTO implements Serializable { @JsonProperty("_id") private String id; private LearningLockerStatementDTO statement; }
23.25
61
0.804301
0cd4e20f9f64f6fc7acc400070ed9831d45232da
1,041
package pal.api.core; public class Node { public int id = 0; public int r = 0; public Node parent = null; public Node left = null; public Node right = null; public boolean isLeft = false; public boolean isRed = false; public Node( int r, int s ) { this( null, r, s, false, 0 ); } public Node(Node parent, int r, int s, boolean isLeftChild, int id) { this.id = id; this.r = r; this.parent = parent; this.isLeft = isLeftChild; if( r<s ) { this.left = new Node( this , r+1 , s , true , id+1 ); this.right = new Node( this , r+1 , s , false , left.right().id+1 ); } } public Node right() { return isLeaf() ? this : right.right(); } public boolean isLeaf() { return this.left==null; } public String toString() { return isLeaf()?"[" + id + "]" : ("[" + id + "](" + left + "," + right + ")"); } }
26.025
86
0.471662
52b9557f1b63165dc9730096e8cfc9957e0ab037
1,109
package com.wxb.mall.order.listener; import com.rabbitmq.client.Channel; import com.wxb.common.to.mq.SecKillOrderTo; import com.wxb.mall.order.service.OrderService; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; /** * <p>Title: OrderSecKillListener</p> * Description: * date:2020/7/9 20:23 */ @RabbitListener(queues = "order.seckill.order.queue") @Component public class OrderSecKillListener { @Autowired private OrderService orderService; @RabbitHandler public void listener(SecKillOrderTo secKillOrderTo, Channel channel, Message message) throws IOException { try { // 创建秒杀单的信息 orderService.createSecKillOrder(secKillOrderTo); channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); } catch (Exception e) { channel.basicReject(message.getMessageProperties().getDeliveryTag(),true); } } }
29.972973
107
0.796213
6e6a641e12c16480bb7b603a9e0a02490b78f387
825
package com.daxton.fancycore.api.fancyclient.json.hub; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; public class HubJson { //物件表 private Map<String, String> object_list = new HashMap<>(); public HubJson(){ } public HubJson(Map<String, String> object_list){ this.object_list = object_list; } public void addObject(String type, String data){ object_list.put(type, data); } //把字串轉成HubJson public static HubJson readJSON(String string) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); return gson.fromJson(string, HubJson.class); } public Map<String, String> getObject_list() { return object_list; } public void setObject_list(Map<String, String> object_list) { this.object_list = object_list; } }
20.625
62
0.73697
5421dfa9fd999982643fc013194a4df1e981bce4
2,799
/* * Copyright 2019-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.data.cassandra.core; import static org.assertj.core.api.Assertions.*; import java.time.Duration; import java.time.Instant; import com.datastax.oss.driver.api.core.CqlIdentifier; import org.junit.jupiter.api.Test; import org.springframework.data.cassandra.core.query.Query; import com.datastax.oss.driver.api.core.DefaultConsistencyLevel; /** * Unit tests for {@link DeleteOptions}. * * @author Mark Paluch */ class DeleteOptionsUnitTests { @Test // DATACASS-575, DATACASS-708, DATACASS-767 void shouldConfigureDeleteOptions() { Instant now = Instant.ofEpochSecond(1234); DeleteOptions deleteOptions = DeleteOptions.builder() // .ttl(10) // .timestamp(now) // .withIfExists() // .executionProfile("foo") // .serialConsistencyLevel(DefaultConsistencyLevel.LOCAL_ONE) // .keyspace(CqlIdentifier.fromCql("my_keyspace")) .build(); assertThat(deleteOptions.getTtl()).isEqualTo(Duration.ofSeconds(10)); assertThat(deleteOptions.getTimestamp()).isEqualTo(now.toEpochMilli() * 1000); assertThat(deleteOptions.isIfExists()).isTrue(); assertThat(deleteOptions.getIfCondition()).isNull(); assertThat(deleteOptions.getKeyspace()).isEqualTo(CqlIdentifier.fromCql("my_keyspace")); } @Test // DATACASS-575 void buildDeleteOptionsMutate() { DeleteOptions deleteOptions = DeleteOptions.builder() // .ttl(10) // .timestamp(1519222753) // .withIfExists() // .build(); DeleteOptions mutated = deleteOptions.mutate().ttl(20).timestamp(1519000753).build(); assertThat(mutated).isNotNull(); assertThat(mutated).isNotSameAs(deleteOptions); assertThat(mutated.getTtl()).isEqualTo(Duration.ofSeconds(20)); assertThat(mutated.getTimestamp()).isEqualTo(1519000753); assertThat(mutated.isIfExists()).isTrue(); assertThat(mutated.getIfCondition()).isNull(); } @Test // DATACASS-575 void shouldApplyFilterCondition() { DeleteOptions deleteOptions = DeleteOptions.builder() // .withIfExists() // .ifCondition(Query.empty()) // .build(); assertThat(deleteOptions.isIfExists()).isFalse(); assertThat(deleteOptions.getIfCondition()).isEqualTo(Query.empty()); } }
31.449438
90
0.738478
277dbe2967cdb6ab5fd02b983058e3bede9c0ab5
2,432
/******************************************************************************* * Copyright SemanticBits, Northwestern University and Akaza Research * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caaers/LICENSE.txt for details. ******************************************************************************/ package gov.nih.nci.cabig.caaers.rules.common; import gov.nih.nci.cabig.caaers.rules.RulesTestCase; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import org.springframework.core.io.ClassPathResource; import com.semanticbits.rules.utils.XMLUtil; public class XMLUtilTest extends RulesTestCase { @Override public Class<? extends RulesTestCase> getTestClass() { return XMLUtilTest.class; } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testUnmarshal() throws Exception { String xml = getCommonFileContext("test_rule2.xml"); //System.out.println(xml); Object p = XMLUtil.unmarshal(xml); assertNotNull("Object cannot be null", p); assertTrue(true); } public void testMarshal() throws Exception { String xml = getCommonFileContext("test_rule2.xml"); Object p = XMLUtil.unmarshal(xml); assertNotNull("Object cannot be null", p); String xml2 = XMLUtil.marshal(p); assertTrue("completed", true); assertTrue(true); } public void testUnmarshalToPackage() throws Exception { String xml = getCommonFileContext("test_rule.xml"); org.drools.rule.Package p = XMLUtil.unmarshalToPackage(xml); assertNotNull("Package cannot be null", p); } private String getCommonFileContext(String fileName) throws Exception { File testFile = new ClassPathResource("/gov/nih/nci/cabig/caaers/rules/common/" + fileName).getFile(); BufferedReader ds = new BufferedReader(new FileReader(testFile)); String line = null; StringBuffer xml = new StringBuffer(); while ((line = ds.readLine()) != null) { xml.append(line); } assertTrue("Content of the xml should not be null", xml.toString().length() > 0); return xml.toString(); } }
34.253521
111
0.60773
ad4742878f3348e555aa4d450dd33769dd7ba3f5
1,971
package com.redis.spring.batch.builder; import com.redis.spring.batch.RedisItemReader; import com.redis.spring.batch.support.AbstractValueReader.ValueReaderFactory; import com.redis.spring.batch.support.KeyValue; import com.redis.spring.batch.support.ScanKeyItemReader; import com.redis.spring.batch.support.ValueReader; import io.lettuce.core.AbstractRedisClient; public class ScanRedisItemReaderBuilder<T extends KeyValue<String, ?>, R extends ValueReader<String, T>> extends RedisItemReaderBuilder<T, R, ScanRedisItemReaderBuilder<T, R>> { private String match = ScanKeyItemReader.DEFAULT_SCAN_MATCH; private long count = ScanKeyItemReader.DEFAULT_SCAN_COUNT; private String type; public ScanRedisItemReaderBuilder(AbstractRedisClient client, ValueReaderFactory<String, String, T, R> valueReaderFactory) { super(client, valueReaderFactory); } public ScanRedisItemReaderBuilder<T, R> match(String match) { this.match = match; return this; } public ScanRedisItemReaderBuilder<T, R> count(long count) { this.count = count; return this; } public ScanRedisItemReaderBuilder<T, R> type(String type) { this.type = type; return this; } public RedisItemReader<String, T> build() { ScanKeyItemReader<String, String> keyReader = new ScanKeyItemReader<>(connectionSupplier(), sync()); keyReader.setCount(count); keyReader.setMatch(match); keyReader.setType(type); return configure(new RedisItemReader<>(jobRepository, transactionManager, keyReader, valueReader())); } public LiveRedisItemReaderBuilder<T, R> live() { LiveRedisItemReaderBuilder<T, R> live = new LiveRedisItemReaderBuilder<>(client, valueReaderFactory); live.keyPatterns(match); live.jobRepository(jobRepository); live.transactionManager(transactionManager); live.chunkSize(chunkSize); live.threads(threads); live.valueQueueCapacity(valueQueueCapacity); live.queuePollTimeout(queuePollTimeout); live.skipPolicy(skipPolicy); return live; } }
33.40678
104
0.787925
5885955d272412d34f2c155337227971d1c64490
6,470
package io.github.vmzakharov.ecdataframe.dataframe; import org.eclipse.collections.impl.factory.Lists; import org.junit.Test; public class DataFrameLookupJoinTest { @Test public void simpleLookup() { DataFrame clients = new DataFrame("clients") .addStringColumn("Id").addStringColumn("Name").addStringColumn("Country ISO") .addRow("1", "Alice", "BM") .addRow("3", "Carl", "XX") .addRow("4", "Doris", "NZ") ; DataFrame countries = new DataFrame("countries") .addStringColumn("ISO Code").addStringColumn("Country Name") .addRow("BM", "Bermuda") .addRow("NZ", "New Zealand") .addRow("UZ", "Uzbekistan") ; clients.lookup( DfJoin.to(countries) .match("Country ISO", "ISO Code") .select("Country Name") ); DataFrameUtil.assertEquals( new DataFrame("clients") .addStringColumn("Id").addStringColumn("Name").addStringColumn("Country ISO").addStringColumn("Country Name") .addRow("1", "Alice", "BM", "Bermuda") .addRow("3", "Carl", "XX", null) .addRow("4", "Doris", "NZ", "New Zealand") , clients ); } @Test public void lookupWithDefaults() { DataFrame clients = new DataFrame("clients") .addStringColumn("Id").addStringColumn("Name").addStringColumn("Country ISO") .addRow("1", "Alice", "BM") .addRow("2", "Bob", "BM") .addRow("3", "Carl", "XX") .addRow("4", "Doris", "NZ") .addRow("5", "Evan", "UZ") ; DataFrame countries = new DataFrame("countries") .addStringColumn("ISO Code").addStringColumn("Name") .addRow("BM", "Bermuda") .addRow("NZ", "New Zealand") .addRow("UZ", "Uzbekistan") ; clients.lookup( DfJoin.to(countries) .match("Country ISO", "ISO Code") .select("Name", "Country Name") .ifAbsent("Not found") ); DataFrameUtil.assertEquals( new DataFrame("clients") .addStringColumn("Id").addStringColumn("Name").addStringColumn("Country ISO").addStringColumn("Country Name") .addRow("1", "Alice", "BM", "Bermuda") .addRow("2", "Bob", "BM", "Bermuda") .addRow("3", "Carl", "XX", "Not found") .addRow("4", "Doris", "NZ", "New Zealand") .addRow("5", "Evan", "UZ", "Uzbekistan"), clients ); } @Test public void multiColumnLookupMultiColumnSelect() { DataFrame clients = new DataFrame("clients") .addStringColumn("Id").addStringColumn("User").addStringColumn("Country ISO").addLongColumn("Code") .addRow("1", "Alice", "BM", 1) .addRow("4", "Doris", "NZ", 1) .addRow("5", "Evan", "UZ", 2) ; DataFrame countries = new DataFrame("countries") .addStringColumn("ISO Code").addLongColumn("Code").addStringColumn("Name").addLongColumn("Number") .addRow("BM", 1, "Bermuda", 60) .addRow("NZ", 1, "New Zealand", 554) .addRow("UZ", 2, "Uzbekistan", 860) ; DataFrame enriched = clients.lookup( DfJoin.to(countries) .match(Lists.immutable.of("Country ISO", "Code"), Lists.immutable.of("ISO Code", "Code")) .select(Lists.immutable.of("Name", "Number")) ); DataFrameUtil.assertEquals( new DataFrame("clients") .addStringColumn("Id").addStringColumn("User").addStringColumn("Country ISO").addLongColumn("Code") .addStringColumn("Name").addLongColumn("Number") .addRow("1", "Alice", "BM", 1, "Bermuda", 60) .addRow("4", "Doris", "NZ", 1, "New Zealand", 554) .addRow("5", "Evan", "UZ", 2, "Uzbekistan", 860), enriched ); } @Test public void multiColumnLookupMultiColumnSelectWithAliases() { DataFrame clients = new DataFrame("clients") .addStringColumn("Id").addStringColumn("Name").addStringColumn("Country ISO").addLongColumn("Code") .addRow("1", "Alice", "BM", 1) .addRow("3", "Carl", "XX", 1) .addRow("2", "Bob", "BM", 1) .addRow("4", "Doris", "NZ", 1) .addRow("5", "Evan", "UZ", 2) ; DataFrame countries = new DataFrame("countries") .addStringColumn("ISO Code").addLongColumn("Code").addStringColumn("Name").addLongColumn("Number") .addRow("BM", 1, "Bermuda", 60) .addRow("NO", 2, "Norway", 578) .addRow("NZ", 1, "New Zealand", 554) .addRow("UZ", 2, "Uzbekistan", 860) ; DataFrame enriched = clients.lookup( DfJoin.to(countries) .match(Lists.immutable.of("Country ISO", "Code"), Lists.immutable.of("ISO Code", "Code")) .select(Lists.immutable.of("Name", "Number"), Lists.immutable.of("Country Name", "Numeric Code")) .ifAbsent(Lists.immutable.of("Not found", -1)) ); DataFrameUtil.assertEquals( new DataFrame("clients") .addStringColumn("Id").addStringColumn("Name").addStringColumn("Country ISO").addLongColumn("Code") .addStringColumn("Country Name").addLongColumn("Numeric Code") .addRow("1", "Alice", "BM", 1, "Bermuda", 60) .addRow("3", "Carl", "XX", 1, "Not found", -1) .addRow("2", "Bob", "BM", 1, "Bermuda", 60) .addRow("4", "Doris", "NZ", 1, "New Zealand", 554) .addRow("5", "Evan", "UZ", 2, "Uzbekistan", 860), enriched ); } }
42.287582
133
0.478516
df2b195aae0b5b75647f9d7f242c1fbc2807a067
2,064
package ru.juliamelf.javaqa.addressbook.tests; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.juliamelf.javaqa.addressbook.model.ContactData; import java.util.Arrays; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by Julia on 6/27/2016. */ public class ContactDataTests extends TestBase { @BeforeMethod public void ensurePreconditions() { if(app.db().contacts().size() == 0) { app.contact().create(new ContactData() .withFirstName("Ivan").withMiddleName("Ivanovich").withLastName("Ivanov") .withCompany("Company").withFirstAddress("Arbat, 1").withGroup("test group"), true); } } @Test public void testContactData() { app.goTo().HomePage(); ContactData contact = app.contact().all().iterator().next(); ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact); assertThat(contact.getAllPhones(), equalTo(mergePhones(contactInfoFromEditForm))); assertThat(contact.getFirstAddress(), equalTo(contactInfoFromEditForm.getFirstAddress())); assertThat(contact.getAllEmails(), equalTo(mergeEmails(contactInfoFromEditForm))); } private String mergeEmails(ContactData contact) { return Arrays.asList(contact.getFirstEmail(), contact.getSecondEmail(), contact.getThirdEmail()) .stream().filter((s) -> !s.equals("")) .collect(Collectors.joining("\n")); } private String mergePhones(ContactData contact) { return Arrays.asList(contact.getHomePhone(), contact.getMobilePhone(), contact.getWorkPhone()) .stream().filter((s) -> ! s.equals("")) .map(ContactDataTests::cleaned) .collect(Collectors.joining("\n")); } public static String cleaned (String phone) { return phone.replaceAll("\\s", "").replaceAll("[-()]", ""); } }
36.857143
104
0.662306
92243b5ffde96b7b46f707cac59464ff3663dea6
3,281
/* * (c) Copyright IBM Corporation 2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.mq.samples.jms.spring.level204; import com.ibm.mq.samples.jms.spring.globals.data.OurData; import com.ibm.mq.samples.jms.spring.globals.handlers.OurDestinationResolver; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.context.annotation.Bean; import org.springframework.integration.dsl.*; import org.springframework.integration.jms.dsl.Jms; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.stereotype.Component; import javax.jms.ConnectionFactory; //@Component public class MessageProducer204 { protected final Log logger = LogFactory.getLog(getClass()); @Autowired private ConnectionFactory connectionFactory; @Value("${app.l204.queue.name1}") public String sendQueue; public MessageChannel datainput = null; @Bean public IntegrationFlow myOurDataFlow() { return IntegrationFlows.from(MessageChannels.direct("ourdatainput")) .log() .transform(Transformers.toJson()) .log() .<String>handle((payload, headers) -> { logger.info("Transformed payload looks like : " + payload); return payload; }) .handle(String.class, (payload, headers) -> { logger.info("Letting Spring take care of the conversion : " + payload); return payload; }) .handle(Jms.outboundAdapter(connectionFactory) .destination(sendQueue) .configureJmsTemplate(c -> c.destinationResolver(new OurDestinationResolver()))) .get(); } public void send(Message<OurData> builtMessage) { if (null != datainput) { datainput.send(builtMessage); } else { logger.warn("Not ready to send messages"); } } @Bean CommandLineRunner process(MessageChannel ourdatainput) { return args -> { logger.info("Sending initial message"); // Only way I could see of capturing the data input message channel // Tried to create it as a bean, but that didn't work. datainput = ourdatainput; datainput.send(MessageBuilder.withPayload(new OurData("Initializer")).build()); }; } }
36.455556
108
0.671137
cfe1321347ba7f0bf145094bea00df6a8bc10ebc
552
package com.jhbim.bimvr.system.config; import com.alipay.api.domain.Person; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author shuihu * @create 2019-09-24 9:49 */ @Configuration public class LogConfig { private static final Logger LOG = LoggerFactory.getLogger(LogConfig.class); @Bean public Person logMethod() { LOG.info("==========print log=========="); return new Person(); } }
24
79
0.702899
cbac4f1dff34b2accc36734b863145c5f97fb76a
4,064
package com.randallma.shukudai; import java.util.ArrayList; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class AssignmentsDataSource { private SQLiteDatabase db; private final SQLiteHelper dbHelper; public AssignmentsDataSource(Context context) { dbHelper = new SQLiteHelper(context); } public void open() throws SQLException { db = dbHelper.getWritableDatabase(); } public void close() { dbHelper.close(); } public void createAssignment(Assignment assignment) { ContentValues values = new ContentValues(); values.put(SQLiteHelper.COLUMN_DESCRIPTION, assignment.getDescription()); values.put(SQLiteHelper.COLUMN_DATE_DUE, assignment.getDateDue()); values.put(SQLiteHelper.COLUMN_DATE_ASSIGNED, assignment.getDateAssigned()); values.put(SQLiteHelper.COLUMN_IMAGE, assignment.getImageUri()); values.put(SQLiteHelper.COLUMN_SCHOOL_CLASS_ID, assignment.getSchoolClassId()); values.put(SQLiteHelper.COLUMN_ARCHIVED, 0); long insertId = db.insert(SQLiteHelper.TABLE_ASSIGNMENTS, null, values); Cursor cursor = db.query(SQLiteHelper.TABLE_ASSIGNMENTS, null, SQLiteHelper.COLUMN_ID + " = " + insertId, null, null, null, null); cursor.close(); } public void editAssignment(Assignment assignment) { ContentValues values = new ContentValues(); values.put(SQLiteHelper.COLUMN_DESCRIPTION, assignment.getDescription()); values.put(SQLiteHelper.COLUMN_DATE_DUE, assignment.getDateDue()); values.put(SQLiteHelper.COLUMN_DATE_ASSIGNED, assignment.getDateAssigned()); values.put(SQLiteHelper.COLUMN_IMAGE, assignment.getImageUri()); values.put(SQLiteHelper.COLUMN_SCHOOL_CLASS_ID, assignment.getSchoolClassId()); db.update(SQLiteHelper.TABLE_ASSIGNMENTS, values, SQLiteHelper.COLUMN_ID + "=?", new String[] { Long.toString(assignment.getId()) }); } public void deleteAssignment(Assignment assignment) { long id = assignment.getId(); Log.i(AssignmentsDataSource.class.getName(), "Assignment deleted with id: " + id); db.delete(SQLiteHelper.TABLE_ASSIGNMENTS, SQLiteHelper.COLUMN_ID + " = " + id, null); } public ArrayList<Assignment> getNewAssignments() { ArrayList<Assignment> assignments = new ArrayList<Assignment>(); Cursor cursor = db.query(SQLiteHelper.TABLE_ASSIGNMENTS, null, SQLiteHelper.COLUMN_ARCHIVED + " = 0", null, null, null, SQLiteHelper.COLUMN_ID + " DESC"); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Assignment assignment = cursorToAssignment(cursor); assignments.add(assignment); cursor.moveToNext(); } cursor.close(); return assignments; } public ArrayList<Assignment> getFilteredAssignments(Long schoolClassId) { ArrayList<Assignment> assignments = new ArrayList<Assignment>(); Cursor cursor = db.query(SQLiteHelper.TABLE_ASSIGNMENTS, null, SQLiteHelper.COLUMN_SCHOOL_CLASS_ID + " = ?", new String[] { Long.toString(schoolClassId) }, null, null, SQLiteHelper.COLUMN_ID + " DESC"); cursor.moveToFirst(); while (!cursor.isAfterLast()) { Assignment assignment = cursorToAssignment(cursor); assignments.add(assignment); cursor.moveToNext(); } cursor.close(); return assignments; } private Assignment cursorToAssignment(Cursor cursor) { Assignment assignment = new Assignment(); assignment.setId(cursor.getLong(0)); assignment.setDescription(cursor.getString(1)); assignment.setDateDue(cursor.getString(2)); assignment.setDateAssigned(cursor.getString(3)); assignment.setImageUri(cursor.getString(4)); Cursor schoolClassCursor = db.query(SQLiteHelper.TABLE_SCHOOL_CLASSES, null, SQLiteHelper.COLUMN_ID + " = ?", new String[] { Integer.toString(cursor.getInt(5)) }, null, null, null, null); schoolClassCursor.moveToFirst(); assignment.setSchoolClass(schoolClassCursor.getString(1)); assignment.setSchoolClassId(cursor.getInt(5)); return assignment; } }
32.512
75
0.755413
33720fb62f585cbea0d6570dae0de2d1116bc4ee
783
package org.skyscreamer.nevado.jms.destination; import javax.jms.JMSException; import javax.jms.Queue; import java.net.URL; /** * Created by IntelliJ IDEA. * User: Carter Page * Date: 3/22/12 * Time: 3:35 AM */ public class NevadoQueue extends NevadoDestination implements Queue { private String _queueUrl; public NevadoQueue(String name) { super(name); } protected NevadoQueue(Queue queue) throws JMSException { super(queue.getQueueName()); } public NevadoQueue(URL sqsURL) { super(sqsURL); } public String getQueueName() { return super.getName(); } public String getQueueUrl() { return _queueUrl; } public void setQueueUrl(String queueUrl) { _queueUrl = queueUrl; } }
19.575
69
0.655172
8d1da55680604fa3fcd91d0a968425d68d59221a
6,880
/* Copyright (c) 2012-2013, University of Edinburgh. * 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 University of Edinburgh nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * This software is derived from (and contains code from) QTItools and MathAssessEngine. * QTItools is (c) 2008, University of Southampton. * MathAssessEngine is (c) 2010, University of Edinburgh. */ package uk.ac.ed.ph.qtiworks.services; import uk.ac.ed.ph.qtiworks.domain.DomainEntityNotFoundException; import uk.ac.ed.ph.qtiworks.domain.entities.CandidateSession; import uk.ac.ed.ph.qtiworks.domain.entities.Delivery; import uk.ac.ed.ph.qtiworks.domain.entities.User; import uk.ac.ed.ph.qtiworks.services.dao.CandidateSessionDao; import uk.ac.ed.ph.qtiworks.services.domain.Privilege; import uk.ac.ed.ph.qtiworks.services.domain.PrivilegeException; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Top layer service providing some basic "proctoring" functionality for instructors * over the candidates for their deliveries. * <p> * All operations here check authorisation. * * @author David McKain */ @Service @Transactional(readOnly=false, propagation=Propagation.REQUIRED) public class AssessmentProctoringService { @Resource private IdentityService identityService; @Resource private AuditLogger auditLogger; @Resource private AssessmentManagementService assessmentManagementService; @Resource private DataDeletionService dataDeletionService; @Resource private CandidateSessionDao candidateSessionDao; @Resource private RequestTimestampContext requestTimestampContext; public CandidateSession lookupCandidateSession(final long xid) throws DomainEntityNotFoundException, PrivilegeException { final CandidateSession candidateSession = candidateSessionDao.requireFindById(xid); assertCallerMayProctor(candidateSession); return candidateSession; } private User assertCallerMayProctor(final CandidateSession candidateSession) throws PrivilegeException { final User caller = identityService.assertCurrentThreadUser(); final User assessmentOwner = candidateSession.getDelivery().getAssessment().getOwnerUser(); if (!assessmentOwner.equals(caller)) { throw new PrivilegeException(caller, Privilege.PROCTOR_SESSION, candidateSession); } return caller; } //------------------------------------------------- public void terminateCandidateSession(final long xid) throws PrivilegeException, DomainEntityNotFoundException { final CandidateSession candidateSession = lookupCandidateSession(xid); if (candidateSession.isTerminated()) { auditLogger.recordEvent("CandidateSession #" + xid + " already terminated"); } else { terminateCandidateSession(candidateSession); auditLogger.recordEvent("Terminated CandidateSession #" + xid); } } private void terminateCandidateSession(final CandidateSession candidateSession) { /* NB: We're relying on the fact that result XMLs are stored after each candidate * action, so we don't have to record a final final result here. */ if (!candidateSession.isTerminated()) { candidateSession.setTerminationTime(requestTimestampContext.getCurrentRequestTimestamp()); candidateSessionDao.update(candidateSession); } } public Delivery deleteCandidateSession(final long xid) throws PrivilegeException, DomainEntityNotFoundException { final CandidateSession candidateSession = lookupCandidateSession(xid); return deleteCandidateSession(candidateSession); } public Delivery deleteCandidateSession(final CandidateSession candidateSession) { final Delivery delivery = candidateSession.getDelivery(); dataDeletionService.deleteCandidateSession(candidateSession); auditLogger.recordEvent("Deleted CandidateSession #" + candidateSession.getId()); return delivery; } //------------------------------------------------- public int terminateCandidateSessionsForDelivery(final long did) throws PrivilegeException, DomainEntityNotFoundException { final Delivery delivery = assessmentManagementService.lookupDelivery(did); int terminatedCount = 0; for (final CandidateSession candidateSession : candidateSessionDao.getForDelivery(delivery)) { if (!candidateSession.isTerminated()) { terminateCandidateSession(candidateSession); terminatedCount++; } } auditLogger.recordEvent("Terminated remaining " + terminatedCount + " CandidateSessions for Delivery #" + did); return terminatedCount; } public int deleteCandidateSessionsForDelivery(final long did) throws PrivilegeException, DomainEntityNotFoundException { final Delivery delivery = assessmentManagementService.lookupDelivery(did); final int deletedCount = dataDeletionService.deleteCandidateSessions(delivery); auditLogger.recordEvent("Deleted all " + deletedCount + " CandidateSessions for Delivery #" + did); return deletedCount; } }
43.27044
119
0.734012
79f221a6be8f9590bff8c5dad9e084eda8cdbe92
465
package com.sergeev.itroi.entity; import com.sergeev.itroi.util.XML; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; @XmlType(name = XML.Ticket.SERVICE_TYPE, namespace = XML.Ticket.SCHEMA_URI) @XmlEnum public enum ServiceType { BUSINESS, ECONOMY, FIRST, PREMIUM; public static ServiceType fromValue(String v) { return valueOf(v); } public String value() { return name(); } }
18.6
75
0.690323
71aa78907d5e15a9c381b14ca99a52c3473eb961
8,222
package com.moemoe.lalala.view.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import com.flyco.tablayout.CommonTabLayout; import com.flyco.tablayout.listener.CustomTabEntity; import com.flyco.tablayout.listener.OnTabSelectListener; import com.moemoe.lalala.R; import com.moemoe.lalala.app.MoeMoeApplication; import com.moemoe.lalala.di.components.DaggerDepartComponent; import com.moemoe.lalala.di.modules.DepartModule; import com.moemoe.lalala.model.entity.BannerEntity; import com.moemoe.lalala.model.entity.DepartmentGroupEntity; import com.moemoe.lalala.model.entity.FeaturedEntity; import com.moemoe.lalala.model.entity.TabEntity; import com.moemoe.lalala.model.entity.TagSendEntity; import com.moemoe.lalala.presenter.DepartContract; import com.moemoe.lalala.presenter.DepartPresenter; import com.moemoe.lalala.utils.AndroidBug5497Workaround; import com.moemoe.lalala.utils.DialogUtils; import com.moemoe.lalala.utils.ErrorCodeUtils; import com.moemoe.lalala.utils.NoDoubleClickListener; import com.moemoe.lalala.utils.ViewUtils; import com.moemoe.lalala.view.adapter.TabFragmentPagerAdapter; import com.moemoe.lalala.view.fragment.BaseFragment; import com.moemoe.lalala.view.fragment.DepartmentFragment; import com.moemoe.lalala.view.fragment.LuntanFragment; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import butterknife.BindView; /** * Created by yi on 2016/12/2. */ public class DepartmentV3Activity extends BaseAppCompatActivity implements DepartContract.View { private final String EXTRA_NAME = "name"; @BindView(R.id.iv_back) ImageView IvBack; @BindView(R.id.pager_person_data) ViewPager mDataPager; @BindView(R.id.indicator_person_data) CommonTabLayout mPageIndicator; @BindView(R.id.rl_role_root) RelativeLayout mRoleRoot; @BindView(R.id.iv_menu_list) ImageView mIvMenu; @BindView(R.id.ll_comment_pannel) View mLlcomment; private TabFragmentPagerAdapter mAdapter; @Inject DepartPresenter mPresenter; private String roomId; private int mIsFollow; private DepartmentFragment departmentFragment; private LuntanFragment luntanFragment; @Override protected int getLayoutId() { return R.layout.ac_wall; } @Override protected void initViews(Bundle savedInstanceState) { if (savedInstanceState != null) { String FRAGMENTS_TAG = "android:support:fragments"; savedInstanceState.remove(FRAGMENTS_TAG); } DaggerDepartComponent.builder() .departModule(new DepartModule(this)) .netComponent(MoeMoeApplication.getInstance().getNetComponent()) .build() .inject(this); ViewUtils.setStatusBarLight(getWindow(), $(R.id.top_view)); AndroidBug5497Workaround.assistActivity(this); roomId = getIntent().getStringExtra(UUID); String title = getIntent().getStringExtra(EXTRA_NAME); clickEvent(roomId); mLlcomment.setVisibility(View.GONE); mRoleRoot.setVisibility(View.GONE); List<BaseFragment> fragmentList = new ArrayList<>(); departmentFragment = DepartmentFragment.newInstance(roomId, title); fragmentList.add(departmentFragment); luntanFragment = LuntanFragment.newInstance(roomId, title, true); // fragmentList.add(luntanFragment); List<String> titles = new ArrayList<>(); titles.add(title); // titles.add("讨论区"); String[] mTitles = {title}; ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>(); for (String mTitle : mTitles) { mTabEntities.add(new TabEntity(mTitle, R.drawable.ic_personal_bag, R.drawable.ic_personal_bag)); } mPageIndicator.setTabWidth(76); mPageIndicator.setIndicatorWidth(56); mAdapter = new TabFragmentPagerAdapter(getSupportFragmentManager(), fragmentList, titles); mDataPager.setAdapter(mAdapter); mPageIndicator.setTabData(mTabEntities); mPresenter.loadIsFollow(roomId); } /** * 添加标签 * * @param entity */ public void createLabel(TagSendEntity entity, int position) { createDialog(); if (mDataPager.getCurrentItem() == 1) { luntanFragment.createLabel(entity, position); } } /** * 社区详情-广场-item点赞 * * @param id * @param isLike * @param position */ public void likeDoc(String id, boolean isLike, int position) { if (mDataPager.getCurrentItem() == 1) { luntanFragment.likeDoc(id, isLike, position); } } @Override protected void initToolbar(Bundle savedInstanceState) { mIvMenu.setVisibility(View.VISIBLE); mIvMenu.setImageResource(R.drawable.btn_trends_search); mIvMenu.setOnClickListener(new NoDoubleClickListener() { @Override public void onNoDoubleClick(View v) { // if (DialogUtils.checkLoginAndShowDlg(DepartmentV3Activity.this) && mIsFollow != -1) { // mPresenter.followDepartment(roomId, mIsFollow == 0); // } if (DialogUtils.checkLoginAndShowDlg(DepartmentV3Activity.this)) { clickEvent("地图-搜索"); Intent i6 = new Intent(DepartmentV3Activity.this, AllSearchActivity.class); i6.putExtra("type", "all"); startActivity(i6); } } }); } @Override protected void initListeners() { IvBack.setOnClickListener(new NoDoubleClickListener() { @Override public void onNoDoubleClick(View v) { onBackPressed(); } }); mPageIndicator.setOnTabSelectListener(new OnTabSelectListener() { @Override public void onTabSelect(int position) { mDataPager.setCurrentItem(position); } @Override public void onTabReselect(int position) { } }); mDataPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { mPageIndicator.setCurrentTab(position); } @Override public void onPageScrollStateChanged(int state) { } }); } @Override protected void initData() { } @Override protected void onPause() { super.onPause(); pauseTime(); } @Override protected void onResume() { super.onResume(); startTime(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override protected void onDestroy() { if (mPresenter != null) mPresenter.release(); if (mAdapter != null) mAdapter.release(); stayEvent(roomId); super.onDestroy(); } @Override public void onFailure(int code, String msg) { ErrorCodeUtils.showErrorMsgByCode(this, code, msg); } @Override public void onBannerLoadSuccess(ArrayList<BannerEntity> bannerEntities) { } @Override public void onFeaturedLoadSuccess(ArrayList<FeaturedEntity> featuredEntities) { } @Override public void onDocLoadSuccess(Object entity, boolean pull) { } @Override public void onChangeSuccess(Object entity) { } @Override public void onFollowDepartmentSuccess(boolean follow) { mIsFollow = follow ? 0 : 1; mIvMenu.setSelected(follow); } @Override public void onSubmissionSuccess() { } @Override public void onLoadGroupSuccess(ArrayList<DepartmentGroupEntity> entity) { } @Override public void onJoinSuccess(String id, String name) { } }
29.469534
108
0.663099
2ee013952409be039356ef9adadc41c400da536f
10,779
package fun.lib.actor.core; import java.io.RandomAccessFile; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.codec.CharEncoding; import org.apache.commons.codec.Charsets; import fun.lib.actor.api.DFActorTcpDispatcher; import fun.lib.actor.api.DFTcpDecoder; import fun.lib.actor.api.cb.CbHttpServer; import fun.lib.actor.api.http.DFHttpDispatcher; import fun.lib.actor.api.http.DFHttpContentType; import fun.lib.actor.api.http.DFHttpHeader; import fun.lib.actor.api.http.DFHttpMethod; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.DefaultFileRegion; import io.netty.channel.FileRegion; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.codec.http.QueryStringDecoder; import io.netty.handler.codec.http.multipart.Attribute; import io.netty.handler.codec.http.multipart.FileUpload; import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder; import io.netty.handler.codec.http.multipart.InterfaceHttpData; import io.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType; import io.netty.handler.stream.ChunkedFile; import io.netty.util.ReferenceCountUtil; public final class DFHttpSvrHandler extends ChannelInboundHandlerAdapter{ private final int _actorIdDef; private final int _requestId; private final DFTcpDecoder _decoder; private final DFHttpDispatcher _dispatcher; private final CbHttpServer _svrHandler; // private volatile DFTcpChannelWrap _session = null; private volatile InetSocketAddress _addrRemote = null; protected DFHttpSvrHandler(int actorIdDef, int requestId, DFTcpDecoder decoder, DFHttpDispatcher dispatcher, CbHttpServer svrHandler) { _actorIdDef = actorIdDef; _requestId = requestId; _decoder = decoder; _dispatcher = dispatcher; _svrHandler = svrHandler; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { _addrRemote = (InetSocketAddress) ctx.channel().remoteAddress(); _session = new DFTcpChannelWrap(_addrRemote.getHostString(), _addrRemote.getPort(), ctx.channel(), DFActorDefine.TCP_DECODE_HTTP, null); _session.setOpenTime(System.currentTimeMillis()); // super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { _session.onClose(); _session = null; super.channelInactive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try{ if (msg instanceof FullHttpRequest) { DFHttpSvrReqWrap dfReq = null; int actorId = 0; Object msgWrap = null; // FullHttpRequest req = (FullHttpRequest) msg; final HttpMethod method = req.method(); final String uri = req.uri(); final boolean keepAlive = HttpUtil.isKeepAlive(req); // if(method.equals(HttpMethod.GET)){ HttpHeaders headers = req.headers(); // dfReq = new DFHttpSvrReqWrap(_session, uri, method, keepAlive, null, 0, null, false); //headers dfReq.setHeaders(headers); //values QueryStringDecoder decoder = new QueryStringDecoder(uri, Charsets.toCharset(CharEncoding.UTF_8)); Map<String,List<String>> mapAttr = decoder.parameters(); for(Map.Entry<String, List<String>> attr : mapAttr.entrySet()){ for(String val : attr.getValue()){ dfReq.addQueryData(attr.getKey(), val); } } // if(_decoder != null){ Object tmp = _decoder.onDecode(dfReq); if(tmp != null){ msgWrap = tmp; } } if(msgWrap == null){ //没有解码 msgWrap = dfReq; } // if(_dispatcher != null){ //通知分发 actorId = _dispatcher.onQueryMsgActorId(_requestId, _addrRemote, msgWrap); } }else if(method.equals(HttpMethod.POST)){ HttpHeaders headers = req.headers(); final String contentType = headers.get(DFHttpHeader.CONTENT_TYPE); final int contentLen = (int) HttpUtil.getContentLength(req); //data if(contentType != null && contentType.equalsIgnoreCase(DFHttpContentType.FORM)){ //表单请求 dfReq = new DFHttpSvrReqWrap(_session, uri, method, keepAlive, contentType,//==null?DFHttpContentType.UNKNOWN:contentType, contentLen, null, false); HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(req); List<InterfaceHttpData> parmList = decoder.getBodyHttpDatas(); for (InterfaceHttpData parm : parmList) { Attribute data = (Attribute) parm; dfReq.addQueryData(data.getName(), data.getValue()); } }else{ //application 请求 boolean isMultipart = false; Object appData = null; ByteBuf buf = req.content(); HttpPostRequestDecoder postDec = new HttpPostRequestDecoder(req); try{ if(postDec.isMultipart()){ // List<InterfaceHttpData> lsData = postDec.getBodyHttpDatas(); // for(InterfaceHttpData data : lsData){ // if(data.getHttpDataType() == HttpDataType.FileUpload){ // FileUpload fUp = (FileUpload) data; // String name = fUp.getName(); // String fileName = fUp.getFilename(); // String tmpType = fUp.getContentType(); // ByteBuf bufTmp = fUp.content(); // // } // } appData = new DFHttpMultiData(postDec); isMultipart = true; }else if(contentIsString(contentType)){ //String appData = buf.readCharSequence(buf.readableBytes(), Charset.forName("utf-8")); }else{ //raw bin appData = buf; if(buf != null){ buf.retain(); } } }finally{ // postDec.cleanFiles(); // postDec.destroy(); } dfReq = new DFHttpSvrReqWrap(_session, uri, method, keepAlive, contentType, //==null?DFHttpContentType.UNKNOWN:contentType, contentLen, appData, isMultipart); } //headers dfReq.setHeaders(headers); // if(_decoder != null){ Object tmp = _decoder.onDecode(dfReq); if(tmp != null){ msgWrap = tmp; } } if(msgWrap == null){ //没有解码 msgWrap = dfReq; } // if(_dispatcher != null){ //通知分发 actorId = _dispatcher.onQueryMsgActorId(_requestId, _addrRemote, msgWrap); } // if(HttpPostRequestDecoder.isMultipart(req)){ // }else{ // } }else{ //unsurpport method ctx.close(); } if(actorId == 0){ actorId = _actorIdDef; } // if(actorId != 0 && msgWrap != null){ //可以后续处理 if(DFActorManager.get().send(_requestId, actorId, 1, DFActorDefine.SUBJECT_NET, DFActorDefine.NET_TCP_MESSAGE, //DFActorDefine.NET_TCP_MESSAGE_CUSTOM, msgWrap, true, _session, actorId==_actorIdDef?_svrHandler:null, false) != 0){ //send to queue failed //处理失败 返回503 HttpResponseStatus.SERVICE_UNAVAILABLE _session.write(new DFHttpSvrRspWrap(503)); } }else{ //无法处理,返回404 HttpResponseStatus.NOT_FOUND _session.write(new DFHttpSvrRspWrap(404)); } }else{ //unsurpport request type ctx.close(); } }finally{ ReferenceCountUtil.release(msg); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } private boolean contentIsString(String contentType){ if(contentType != null && (contentType.equals(DFHttpContentType.JSON) || contentType.equals(DFHttpContentType.XML) || contentType.equals(DFHttpContentType.TEXT_PLAIN) || contentType.equals(DFHttpContentType.TEXT_HTML) )){ return true; } return false; } // // private static final byte[] CONTENT = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd' }; // private static final AsciiString CONTENT_TYPE = AsciiString.cached("Content-Type"); // private static final AsciiString CONTENT_LENGTH = AsciiString.cached("Content-Length"); // private static final AsciiString CONNECTION = AsciiString.cached("Connection"); // private static final AsciiString KEEP_ALIVE = AsciiString.cached("keep-alive"); // private static final String URI_FAVICON = "/favicon.ico"; // private void _ttt(ChannelHandlerContext ctx){ // FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, // HttpResponseStatus.OK, Unpooled.wrappedBuffer(CONTENT)); // response.headers().set(CONTENT_TYPE, "text/plain"); // response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); // // ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); //// if (!keepAlive) { //// ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); //// } else { //// response.headers().set(CONNECTION, KEEP_ALIVE); //// ctx.writeAndFlush(response); //// } // } }
40.829545
111
0.628537
f4010addd689c91d4cf7c2160cad4524e9f59291
2,292
package cmput301_17.includebucket; import android.content.Context; import android.content.SharedPreferences; import android.util.Base64; import com.google.gson.Gson; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Created by michelletagarino on 16-11-25. */ public class DriverRequestsFileManager { private static final String prefFile = "DRIVER_REQUESTS_FILE"; private static final String drKey = "DRIVER_REQUESTS_KEY"; private Context context; static private DriverRequestsFileManager requestListFileManager = null; public static void initManager(Context context) { if (requestListFileManager == null) { if (context == null) { throw new RuntimeException("Missing context for RequestListFileManager"); } requestListFileManager = new DriverRequestsFileManager(context); } } public static DriverRequestsFileManager getRequestListFileManager() { if (requestListFileManager == null) { throw new RuntimeException("Did not initialize Manager"); } return requestListFileManager; } public DriverRequestsFileManager(Context context) { this.context = context; } public RequestList loadRequestList() throws IOException, ClassNotFoundException { SharedPreferences settings = context.getSharedPreferences(prefFile, Context.MODE_PRIVATE); String requestListData = settings.getString(drKey, ""); if (requestListData.equals("")) { return new RequestList(); } else { Gson gson = new Gson(); RequestList requestList = gson.fromJson(requestListData, RequestList.class); return requestList; } } public void saveRequestList(RequestList rl) throws IOException { SharedPreferences settings = context.getSharedPreferences(prefFile, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); Gson gson = new Gson(); String json = gson.toJson(rl); editor.putString(drKey, json); editor.commit(); } }
30.157895
98
0.679319
28ceaad71f644252457eda33286d86ea33f5c300
1,843
/* * (C) Copyright 2017-2018 OpenVidu (https://openvidu.io/) * * 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.openvidu.load.test.utils; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; /** * Customized CountDownLatch to support external abortion * * @author Pablo Fuente (pablofuenteperez@gmail.com) */ public class CustomLatch { public class AbortedException extends Exception { private static final long serialVersionUID = 1L; public AbortedException(String errorMessage) { super(errorMessage); } } private CountDownLatch latch; private AtomicBoolean aborted = new AtomicBoolean(false); private String errorMessage = ""; public CustomLatch(int countDown) { this.latch = new CountDownLatch(countDown); } public void await() throws AbortedException { try { this.latch.await(); } catch (InterruptedException e) { e.printStackTrace(); if (aborted.get()) { throw new AbortedException(errorMessage); } } if (aborted.get()) { throw new AbortedException(errorMessage); } } public synchronized void abort(String errorMessage) { this.aborted.set(true); this.errorMessage = errorMessage; while (this.latch.getCount() > 0) { this.latch.countDown(); } } public void succeed() { latch.countDown(); } }
24.905405
75
0.72599
bc1d1acc43681f766288232d2903f651e9f7b92c
417
package com.xp.alert.v2; import com.xp.alert.v1.AlertRule; import com.xp.alert.v1.Notification; /** * @author zhaoxiaoping * @Description: 超时告警 * @Date 2020-5-25 **/ public class TimeoutAlertHandler extends AlertHandler { public TimeoutAlertHandler(AlertRule rule, Notification notification) { super(rule, notification); } @Override public void check(ApiStatInfo apiStatInfo) { } }
18.130435
55
0.71223
54090e3f8869381c50f0af3ae1fc6940991622f5
4,571
package com.dakare.streamlabs.config; import com.dakare.streamlabs.config.properties.BotConfigurationProperties; import com.dakare.streamlabs.config.properties.ImageAlertConfigurationProperties; import com.dakare.streamlabs.config.properties.StreamInfoConfigurationProperties; import com.dakare.streamlabs.config.properties.WeatherConfigurationProperties; import com.dakare.streamlabs.repository.AlertUsageRepository; import com.dakare.streamlabs.repository.ImageAlertRepository; import com.dakare.streamlabs.service.PircBotManager; import com.dakare.streamlabs.service.StreamStatusService; import com.dakare.streamlabs.service.StreamlabsAlertService; import com.dakare.streamlabs.service.StreamlabsPointsService; import com.dakare.streamlabs.service.command.CommandListenerAdapter; import com.dakare.streamlabs.service.command.CommandSender; import com.dakare.streamlabs.service.command.CommandSenderImpl; import com.dakare.streamlabs.service.command.listener.ImageAlertListener; import com.google.common.base.Preconditions; import org.apache.commons.lang3.StringUtils; import org.pircbotx.PircBotX; import org.pircbotx.cap.EnableCapHandler; import org.pircbotx.hooks.Listener; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.TaskScheduler; import org.springframework.web.client.RestTemplate; import java.util.List; @Configuration @EnableConfigurationProperties({BotConfigurationProperties.class, StreamInfoConfigurationProperties.class, ImageAlertConfigurationProperties.class, WeatherConfigurationProperties.class}) public class BotConfiguration { @Bean public PircBotX getBot(BotConfigurationProperties config, List<Listener> adapters) { Preconditions.checkArgument(StringUtils.isNotEmpty(config.getChannel()), "twitch bot channel configuration is missing in application.properties"); Preconditions.checkArgument(StringUtils.isNotEmpty(config.getName()), "twitch bot name configuration is missing in application.properties"); Preconditions.checkArgument(StringUtils.isNotEmpty(config.getServer()), "twitch bot server host configuration is missing in application.properties"); Preconditions.checkArgument(config.getPort() != 0, "twitch bot server port configuration is missing in application.properties"); Preconditions.checkArgument(StringUtils.isNotEmpty(config.getOauth()), "twitch bot oauth token is missing in application.properties"); org.pircbotx.Configuration botConfiguration = new org.pircbotx.Configuration.Builder() .setName(config.getName()) .addServer(config.getServer(), config.getPort()) .setServerPassword(config.getOauth()) .addListeners(adapters) .addAutoJoinChannel("#" + config.getChannel()) .setAutoReconnect(true) .addCapHandler(new EnableCapHandler("twitch.tv/tags")) .addCapHandler(new EnableCapHandler("twitch.tv/commands")) .buildConfiguration(); return new PircBotX(botConfiguration); } @Bean public PircBotManager pircBotManager(PircBotX bot) { return new PircBotManager(bot); } @Bean public CommandListenerAdapter commandListenerAdapter(ApplicationEventPublisher publisher) { return new CommandListenerAdapter(publisher); } @Bean public CommandSender commandSender(PircBotX pircBotX, BotConfigurationProperties botConfigurationProperties) { return new CommandSenderImpl(pircBotX, botConfigurationProperties); } @Bean public StreamStatusService streamStatusService(RestTemplate restTemplate, TaskScheduler taskScheduler, StreamInfoConfigurationProperties streamInfoConfigurationProperties, BotConfigurationProperties botConfigurationProperties) { return new StreamStatusService(restTemplate, taskScheduler, streamInfoConfigurationProperties, botConfigurationProperties); } @Bean public ImageAlertListener imageAlertListener(ImageAlertConfigurationProperties configurationProperties, ImageAlertRepository imageAlertRepository, StreamlabsAlertService streamlabsAlertService, AlertUsageRepository alertUsageRepository, StreamlabsPointsService streamlabsPointsService) { return new ImageAlertListener(streamlabsPointsService, configurationProperties, imageAlertRepository, streamlabsAlertService, alertUsageRepository); } }
47.123711
112
0.815139
1d0e97acd1be955e7da6fc5a53824887dacad96d
460
package controllers; import play.mvc.Controller; import play.mvc.Result; import views.html.index; import views.html.setFlash; public class Application extends Controller { public Result index() { response().setCookie("HELLO", "WORLD"); return ok(index.render("Your new application is ready.")); } public Result setFlash() { flash().put("sample", "value"); return redirect(routes.Application.index()); } }
20
66
0.663043
769ae24c2848f78b26ef371aba3faaed8f9a0a2b
1,117
package headfirst.designpatterns.templatemethod.list; import java.util.AbstractList; // AbstractList provides a skeletal implementation of the List interface // to minimize the effort required to implement this interface backed by // a "random access" data store (such as an array). // To implement an unmodifiable list, the programmer needs only to extend // this class and provide implementations for the get(int) and size() methods. // get(int index) is an abstract method in AbstractList // size() is an abstract method in AbstractCollection // subList(int fromIndex, int toIndex) returns a view of the portion of this list // between the specified fromIndex, inclusive, and toIndex, exclusive. public class MyStringList extends AbstractList<String> { private String[] myList; MyStringList(String[] strings) { myList = strings; } @Override public String get(int index) { return myList[index]; } @Override public String set(int index, String item) { String oldString = myList[index]; myList[index] = item; return oldString; } @Override public int size() { return myList.length; } }
31.914286
82
0.75291
1f9ebf83482d14bf5ab18b874174302f736d0e3a
3,792
/* * Copyright 2020 Jochen Wiedmann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jochenw.afw.core.io; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; /** Abstract base class for creating instances of {@link FileVisitor}. */ public abstract class AbstractFileVisitor extends SimpleFileVisitor<Path>{ final StringBuilder sb = new StringBuilder(); int level = 0; private final boolean baseDirIncludedInPath; protected AbstractFileVisitor(boolean pBaseDirIncludedInPath) { baseDirIncludedInPath = pBaseDirIncludedInPath; } @Override public FileVisitResult preVisitDirectory(Path pDir, BasicFileAttributes pAttrs) throws IOException { /** Add the current directories name to the path. */ if (level > 0 || baseDirIncludedInPath) { final String dirName = pDir.getFileName().toString(); if (sb.length() > 0) { sb.append('/'); } sb.append(dirName); } ++level; try { visitDirectory(sb.toString(), pDir, pAttrs); } catch (TerminationRequest tr) { return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path pFile, BasicFileAttributes pAttrs) throws IOException { final String fileName = pFile.getFileName().toString(); final int length = sb.length(); sb.append('/'); sb.append(fileName); final String path = sb.toString(); sb.setLength(length); visitFile(path, pFile, pAttrs); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path pDir, IOException pExc) throws IOException, TerminationRequest { /** Remove the current directories name to the path. */ --level; if (level > 0 || baseDirIncludedInPath) { } final int offset = sb.lastIndexOf("/"); if (offset == -1) { sb.setLength(0); } else { sb.setLength(offset); } if (pExc == null) { return FileVisitResult.CONTINUE; } else { throw pExc; } } /** * A method, which is being invoked, if the visitor encounters a subdirectory. * @param pPath The directories relative path. * @param pDir The directories path. * @param pAttrs The directories file attributes. * @throws IOException Visiting the directory failed. */ public void visitDirectory(String pPath, Path pDir, BasicFileAttributes pAttrs) throws IOException {} /** * A method, which is being invoked, if the visitor encounters a file. * @param pPath The directories relative path. * @param pFile The files path. * @param pAttrs The files file attributes. * @throws IOException Visiting the file failed. */ public abstract void visitFile(String pPath, Path pFile, BasicFileAttributes pAttrs) throws IOException; }
35.439252
116
0.649789
6f197d9972923165dce36737cb0c1a49269392af
840
package org.pkaq; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @Description: 应用配置启动入口. * @FileName: Booter.java * @Author: S.PKAQ * @Version: 1.0 * @Date: 2016年4月7日 上午9:28:07 */ @SpringBootApplication @Slf4j public class Booter implements CommandLineRunner { /** * 入口函数. * @param args args */ @Autowired public static void main(String[] args) { SpringApplication.run(Booter.class, args); } public void run(String... args) throws Exception { log.info(" --- --- --- [ web started ] --- --- --- "); } }
26.25
68
0.645238
395c55c9633743fd752c2b15296318d583c65f4f
268
package membersIfazeConstantDelete; import testing_lib.membersIfazeConstantDelete.MembersIfazeConstantDelete; public class Main implements MembersIfazeConstantDelete { public static void main(String[] args) { int test = MembersIfazeConstantDelete.FIELD1; } }
22.333333
73
0.828358
9672cfd11317fbb46a510f1f44086d34faeb8841
186
package com.cip.crane.restlet.resource; import org.restlet.resource.Get; /** * Created by kirinli on 14/11/23. */ public interface IGetUserId { @Get public int retrieve(); }
15.5
39
0.693548
073e1a49a7c5ce2ebead9d076c5b3bcc168c2d9a
1,748
/** * TLS-Attacker - A Modular Penetration Testing Framework for TLS * * Copyright 2014-2020 Ruhr University Bochum, Paderborn University, * and Hackmanit GmbH * * Licensed under Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package de.rub.nds.tlsattacker.core.protocol.handler.extension; import de.rub.nds.tlsattacker.core.protocol.message.extension.ClientCertificateUrlExtensionMessage; import de.rub.nds.tlsattacker.core.protocol.parser.extension.ClientCertificateUrlExtensionParser; import de.rub.nds.tlsattacker.core.protocol.preparator.extension.ClientCertificateUrlExtensionPreparator; import de.rub.nds.tlsattacker.core.protocol.serializer.extension.ClientCertificateUrlExtensionSerializer; import de.rub.nds.tlsattacker.core.state.TlsContext; public class ClientCertificateUrlExtensionHandler extends ExtensionHandler<ClientCertificateUrlExtensionMessage> { public ClientCertificateUrlExtensionHandler(TlsContext context) { super(context); } @Override public ClientCertificateUrlExtensionParser getParser(byte[] message, int pointer) { return new ClientCertificateUrlExtensionParser(pointer, message); } @Override public ClientCertificateUrlExtensionPreparator getPreparator(ClientCertificateUrlExtensionMessage message) { return new ClientCertificateUrlExtensionPreparator(context.getChooser(), message, getSerializer(message)); } @Override public ClientCertificateUrlExtensionSerializer getSerializer(ClientCertificateUrlExtensionMessage message) { return new ClientCertificateUrlExtensionSerializer(message); } @Override public void adjustTLSExtensionContext(ClientCertificateUrlExtensionMessage message) { } }
39.727273
114
0.808924
1c126a748f2039ede4f96d2fbb99c5f5b22d7e95
5,552
package com.oath.cyclops.util.box; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import com.oath.cyclops.types.foldable.To; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; /** * Class that represents a Closed Variable * In Java 8 because of the effectively final rule references to captured * variables can't be changed. * e.g. *<pre>{@code * char var = true; * Runnable r = () -> var =false; * }</pre> * * Won't compile because var is treated as if it is final. * This can be 'worked around' by using a wrapping object or array. * * e.g. * <pre>{@code * MutableChar var = MutableChar.of(true); * Runnable r = () -> var.set(false); * }</pre> * * @author johnmcclean * * @param <T> Type held inside closed var */ @AllArgsConstructor @NoArgsConstructor @ToString @EqualsAndHashCode public class MutableChar implements To<MutableChar>,Supplier<Character>, Consumer<Character> { private char var; /** * Create a Mutable variable, which can be mutated inside a Closure * * e.g. * <pre>{@code * MutableChar char = MutableChar.of('c'); * * char.mutate(n->'d')) * * System.out.println(num.getAsChar()); * //prints d * } </pre> * * @param var Initial value of Mutable * @return New Mutable instance */ public static <T> MutableChar of(final char var) { return new MutableChar( var); } /** * Construct a MutableChar that gets and sets an external value using the provided Supplier and Consumer * * e.g. * <pre> * {@code * MutableChar mutable = MutableChar.fromExternal(()->!this.value,val->!this.value); * } * </pre> * * * @param s Supplier of an external value * @param c Consumer that sets an external value * @return MutableChar that gets / sets an external (mutable) value */ public static MutableChar fromExternal(final Supplier<Character> s, final Consumer<Character> c) { return new MutableChar() { @Override public char getAsChar() { return s.get(); } @Override public Character get() { return getAsChar(); } @Override public MutableChar set(final char value) { c.accept(value); return this; } }; } /** * Use the supplied function to perform a lazy transform operation when getValue is called * <pre> * {@code * MutableChar mutable = MutableChar.fromExternal(()->!this.value,val->!this.value); * Mutable<Character> withOverride = mutable.mapOutput(b->{ * if(override) * return 'a'; * return b; * }); * * } * </pre> * * * @param fn Map function to be applied to the result when getValue is called * @return Mutable that lazily applies the provided function when getValue is called to the return value */ public <R> Mutable<R> mapOutputToObj(final Function<Character, R> fn) { final MutableChar host = this; return new Mutable<R>() { @Override public R get() { return fn.apply(host.get()); } }; } /** * Use the supplied function to perform a lazy transform operation when getValue is called * <pre> * {@code * MutableChar mutable = MutableChar.fromExternal(()->!this.value,val->!this.value); * Mutable<Character> withOverride = mutable.mapInput(b->{ * if(override) * return 'v'; * return b; * }); * * } * </pre> * * * @param fn Map function to be applied to the input when set is called * @return Mutable that lazily applies the provided function when set is called to the input value */ public <T1> Mutable<T1> mapInputToObj(final Function<T1, Character> fn) { final MutableChar host = this; return new Mutable<T1>() { @Override public Mutable<T1> set(final T1 value) { host.set(fn.apply(value)); return this; } }; } /** * @return Current value */ public char getAsChar() { return var; } /** * @param var New value * @return this object with mutated value */ public MutableChar set(final char var) { this.var = var; return this; } /** * @param varFn New value * @return this object with mutated value */ public MutableChar mutate(final CharFunction varFn) { return set(varFn.apply(get())); } public static interface CharFunction { char apply(char var); } @Override public void accept(final Character t) { set(t); } @Override public Character get() { return getAsChar(); } }
27.621891
108
0.53116
dbabf2835639d54bf7355de1b6312202d551e483
607
package cn.aezo.spring.base.annotation.combineannotation; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; 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; /** * Created by smalle on 2017/6/11. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration @ComponentScan public @interface WiselyConfiguration { String[] value() default {}; }
25.291667
60
0.812191
c2aa40f92659559da19efa7b4e80c1a44abc4083
2,638
/** * This file is part of the Java Machine Learning Library * * The Java Machine Learning Library 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. * * The Java Machine Learning Library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the Java Machine Learning Library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Copyright (c) 2006-2012, Thomas Abeel * * Project: http://java-ml.sourceforge.net/ * */ package net.sf.javaml.distance; import net.sf.javaml.core.Dataset; import net.sf.javaml.core.DenseInstance; import net.sf.javaml.core.Instance; import net.sf.javaml.tools.DatasetTools; /** * A normalized version of the Euclidean distance. This distance measure is * normalized in the interval [0,1]. * * High values denote low similar items (high distance) and low values denote * highly similar items (low distance). * * @author Thomas Abeel * */ public class NormalizedEuclideanDistance extends EuclideanDistance { /** * */ private static final long serialVersionUID = -6489071802740149683L; private Dataset data; public NormalizedEuclideanDistance(Dataset data) { super(); this.data = data; } public double measure(Instance i, Instance j) { Instance min = DatasetTools.minAttributes(data); Instance max = DatasetTools.maxAttributes(data); Instance normI = normalizeMidrange(0.5, 1, min, max, i); Instance normJ = normalizeMidrange(0.5, 1, min, max, j); return super.calculateDistance(normI, normJ) / Math.sqrt(i.noAttributes()); } private Instance normalizeMidrange(double normalMiddle, double normalRange, Instance min, Instance max, Instance instance) { double[] out = new double[instance.noAttributes()]; for (int i = 0; i < out.length; i++) { double range = Math.abs(max.value(i) - min.value(i)); double middle = Math.abs(max.value(i) + min.value(i)) / 2; out[i] = ((instance.value(i) - middle) / range) * normalRange + normalMiddle; } return new DenseInstance(out, instance); } }
35.173333
107
0.689158
79f61eeea60c01a26765af7066516d2d5b552f60
2,238
package com.pandocloud.freeiot.ui.device.config; import com.pandocloud.android.config.wifi.WifiConfigManager; import com.pandocloud.freeiot.R; import com.pandocloud.freeiot.ui.base.BaseActivity; import com.pandocloud.freeiot.utils.ActivityUtils; import com.pandocloud.freeiot.utils.BusinessUtils; import com.pandocloud.freeiot.utils.CommonUtils; import com.umeng.analytics.MobclickAgent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.MenuItem; import android.view.WindowManager; public class GateWayConfigActivity extends BaseActivity { private static final String TAG_CONFIG_FRAGMENT = "GateWayConfig"; private FragmentManager fm; private String tag; public static long startConfigTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_gateway_config); fm = getSupportFragmentManager(); if (savedInstanceState == null) { tag = TAG_CONFIG_FRAGMENT; fm.beginTransaction() .replace(android.R.id.content, new ApSsidConfigFragment(), tag) .commit(); } else { tag = savedInstanceState.getString("tag"); Fragment fragment = fm.findFragmentByTag(tag); fm.beginTransaction() .replace(android.R.id.content, fragment, tag) .commit(); } } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("tag", tag); } @Override public void onBackPressed() { if (CommonUtils.showingProgressDialog()) { CommonUtils.dismissDialog(); } BusinessUtils.checkWifi(this); ActivityUtils.animFinish(this, R.anim.slide_in_from_left, R.anim.slide_out_to_right); } @Override protected void onDestroy() { WifiConfigManager.stopConfig(); super.onDestroy(); } }
26.642857
88
0.723414
fee50d7d8613dc08b7ac3d5a1b4edc3106d301ef
592
package dsa.arrays; import static org.junit.Assert.assertEquals; import org.junit.Test; public class MatrixRotationTest { @Test public void testRotate() { int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int[][] expected = {{13, 9, 5, 1}, {14, 10, 6, 2}, {15, 11, 7, 3}, {16, 12, 8, 4}}; boolean success = MatrixRotation.rotate(matrix); assertEquals(true, success); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { assertEquals(expected[i][j], matrix[i][j]); } } } }
28.190476
88
0.555743
5365536b460db1e2c9620a72ed830f942189d440
77,109
/* * Copyright(C) 2014 syuu256\gmail.com. All Rights Reserved. */ package net._instanceof.commons.datasource.wrapper; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.Date; import java.sql.NClob; import java.sql.ParameterMetaData; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLType; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CallableStatementWrapper implements CallableStatement { private static Logger log = LoggerFactory.getLogger(CallableStatementWrapper.class); private final CallableStatement callableStatement; public CallableStatementWrapper(final CallableStatement callableStatement) { this.callableStatement = callableStatement; } private void d(final String sql) { log.debug("sql:" + sql); } /** * @param iface * @return * @throws SQLException * @see java.sql.Wrapper#unwrap(java.lang.Class) */ public <T> T unwrap(Class<T> iface) throws SQLException { return callableStatement.unwrap(iface); } /** * @param sql * @return * @throws SQLException * @see java.sql.Statement#executeQuery(java.lang.String) */ public ResultSet executeQuery(String sql) throws SQLException { return callableStatement.executeQuery(sql); } /** * @return * @throws SQLException * @see java.sql.PreparedStatement#executeQuery() */ public ResultSet executeQuery() throws SQLException { return callableStatement.executeQuery(); } /** * @param parameterIndex * @param sqlType * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(int, int) */ public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException { d("registerOutParameter(parameterIndex/sqlType):" + parameterIndex + ":" + sqlType); callableStatement.registerOutParameter(parameterIndex, sqlType); } /** * @param iface * @return * @throws SQLException * @see java.sql.Wrapper#isWrapperFor(java.lang.Class) */ public boolean isWrapperFor(Class<?> iface) throws SQLException { return callableStatement.isWrapperFor(iface); } /** * @param sql * @return * @throws SQLException * @see java.sql.Statement#executeUpdate(java.lang.String) */ public int executeUpdate(String sql) throws SQLException { return callableStatement.executeUpdate(sql); } /** * @return * @throws SQLException * @see java.sql.PreparedStatement#executeUpdate() */ public int executeUpdate() throws SQLException { return callableStatement.executeUpdate(); } /** * @param parameterIndex * @param sqlType * @throws SQLException * @see java.sql.PreparedStatement#setNull(int, int) */ public void setNull(int parameterIndex, int sqlType) throws SQLException { d("setNull(parameterIndex/sqlType):" + parameterIndex + ":" + sqlType); callableStatement.setNull(parameterIndex, sqlType); } /** * @throws SQLException * @see java.sql.Statement#close() */ public void close() throws SQLException { callableStatement.close(); } /** * @param parameterIndex * @param sqlType * @param scale * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(int, int, int) */ public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException { d("registerOutParameter(parameterIndex/sqlType/scale):" + parameterIndex + ":" + sqlType + ":" + scale); callableStatement.registerOutParameter(parameterIndex, sqlType, scale); } /** * @return * @throws SQLException * @see java.sql.Statement#getMaxFieldSize() */ public int getMaxFieldSize() throws SQLException { return callableStatement.getMaxFieldSize(); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setBoolean(int, boolean) */ public void setBoolean(int parameterIndex, boolean x) throws SQLException { callableStatement.setBoolean(parameterIndex, x); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setByte(int, byte) */ public void setByte(int parameterIndex, byte x) throws SQLException { callableStatement.setByte(parameterIndex, x); } /** * @param max * @throws SQLException * @see java.sql.Statement#setMaxFieldSize(int) */ public void setMaxFieldSize(int max) throws SQLException { callableStatement.setMaxFieldSize(max); } /** * @return * @throws SQLException * @see java.sql.CallableStatement#wasNull() */ public boolean wasNull() throws SQLException { return callableStatement.wasNull(); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setShort(int, short) */ public void setShort(int parameterIndex, short x) throws SQLException { callableStatement.setShort(parameterIndex, x); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getString(int) */ public String getString(int parameterIndex) throws SQLException { return callableStatement.getString(parameterIndex); } /** * @return * @throws SQLException * @see java.sql.Statement#getMaxRows() */ public int getMaxRows() throws SQLException { return callableStatement.getMaxRows(); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setInt(int, int) */ public void setInt(int parameterIndex, int x) throws SQLException { callableStatement.setInt(parameterIndex, x); } /** * @param max * @throws SQLException * @see java.sql.Statement#setMaxRows(int) */ public void setMaxRows(int max) throws SQLException { callableStatement.setMaxRows(max); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setLong(int, long) */ public void setLong(int parameterIndex, long x) throws SQLException { callableStatement.setLong(parameterIndex, x); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getBoolean(int) */ public boolean getBoolean(int parameterIndex) throws SQLException { return callableStatement.getBoolean(parameterIndex); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setFloat(int, float) */ public void setFloat(int parameterIndex, float x) throws SQLException { callableStatement.setFloat(parameterIndex, x); } /** * @param enable * @throws SQLException * @see java.sql.Statement#setEscapeProcessing(boolean) */ public void setEscapeProcessing(boolean enable) throws SQLException { callableStatement.setEscapeProcessing(enable); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getByte(int) */ public byte getByte(int parameterIndex) throws SQLException { return callableStatement.getByte(parameterIndex); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setDouble(int, double) */ public void setDouble(int parameterIndex, double x) throws SQLException { callableStatement.setDouble(parameterIndex, x); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getShort(int) */ public short getShort(int parameterIndex) throws SQLException { return callableStatement.getShort(parameterIndex); } /** * @return * @throws SQLException * @see java.sql.Statement#getQueryTimeout() */ public int getQueryTimeout() throws SQLException { return callableStatement.getQueryTimeout(); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setBigDecimal(int, java.math.BigDecimal) */ public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException { callableStatement.setBigDecimal(parameterIndex, x); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getInt(int) */ public int getInt(int parameterIndex) throws SQLException { return callableStatement.getInt(parameterIndex); } /** * @param seconds * @throws SQLException * @see java.sql.Statement#setQueryTimeout(int) */ public void setQueryTimeout(int seconds) throws SQLException { callableStatement.setQueryTimeout(seconds); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setString(int, java.lang.String) */ public void setString(int parameterIndex, String x) throws SQLException { d("setString:" + parameterIndex + ":" + x); callableStatement.setString(parameterIndex, x); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getLong(int) */ public long getLong(int parameterIndex) throws SQLException { return callableStatement.getLong(parameterIndex); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setBytes(int, byte[]) */ public void setBytes(int parameterIndex, byte[] x) throws SQLException { callableStatement.setBytes(parameterIndex, x); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getFloat(int) */ public float getFloat(int parameterIndex) throws SQLException { return callableStatement.getFloat(parameterIndex); } /** * @throws SQLException * @see java.sql.Statement#cancel() */ public void cancel() throws SQLException { callableStatement.cancel(); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getDouble(int) */ public double getDouble(int parameterIndex) throws SQLException { return callableStatement.getDouble(parameterIndex); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setDate(int, java.sql.Date) */ public void setDate(int parameterIndex, Date x) throws SQLException { callableStatement.setDate(parameterIndex, x); } /** * @return * @throws SQLException * @see java.sql.Statement#getWarnings() */ public SQLWarning getWarnings() throws SQLException { return callableStatement.getWarnings(); } /** * @param parameterIndex * @param scale * @return * @throws SQLException * @deprecated * @see java.sql.CallableStatement#getBigDecimal(int, int) */ public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException { return callableStatement.getBigDecimal(parameterIndex, scale); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setTime(int, java.sql.Time) */ public void setTime(int parameterIndex, Time x) throws SQLException { callableStatement.setTime(parameterIndex, x); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp) */ public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException { callableStatement.setTimestamp(parameterIndex, x); } /** * @throws SQLException * @see java.sql.Statement#clearWarnings() */ public void clearWarnings() throws SQLException { callableStatement.clearWarnings(); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getBytes(int) */ public byte[] getBytes(int parameterIndex) throws SQLException { return callableStatement.getBytes(parameterIndex); } /** * @param name * @throws SQLException * @see java.sql.Statement#setCursorName(java.lang.String) */ public void setCursorName(String name) throws SQLException { callableStatement.setCursorName(name); } /** * @param parameterIndex * @param x * @param length * @throws SQLException * @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, int) */ public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException { callableStatement.setAsciiStream(parameterIndex, x, length); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getDate(int) */ public Date getDate(int parameterIndex) throws SQLException { return callableStatement.getDate(parameterIndex); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getTime(int) */ public Time getTime(int parameterIndex) throws SQLException { return callableStatement.getTime(parameterIndex); } /** * @param parameterIndex * @param x * @param length * @throws SQLException * @deprecated * @see java.sql.PreparedStatement#setUnicodeStream(int, java.io.InputStream, int) */ public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException { callableStatement.setUnicodeStream(parameterIndex, x, length); } /** * @param sql * @return * @throws SQLException * @see java.sql.Statement#execute(java.lang.String) */ public boolean execute(String sql) throws SQLException { return callableStatement.execute(sql); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getTimestamp(int) */ public Timestamp getTimestamp(int parameterIndex) throws SQLException { return callableStatement.getTimestamp(parameterIndex); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getObject(int) */ public Object getObject(int parameterIndex) throws SQLException { return callableStatement.getObject(parameterIndex); } /** * @param parameterIndex * @param x * @param length * @throws SQLException * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, int) */ public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException { callableStatement.setBinaryStream(parameterIndex, x, length); } /** * @return * @throws SQLException * @see java.sql.Statement#getResultSet() */ public ResultSet getResultSet() throws SQLException { return callableStatement.getResultSet(); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getBigDecimal(int) */ public BigDecimal getBigDecimal(int parameterIndex) throws SQLException { return callableStatement.getBigDecimal(parameterIndex); } /** * @return * @throws SQLException * @see java.sql.Statement#getUpdateCount() */ public int getUpdateCount() throws SQLException { return callableStatement.getUpdateCount(); } /** * @throws SQLException * @see java.sql.PreparedStatement#clearParameters() */ public void clearParameters() throws SQLException { callableStatement.clearParameters(); } /** * @param parameterIndex * @param map * @return * @throws SQLException * @see java.sql.CallableStatement#getObject(int, java.util.Map) */ public Object getObject(int parameterIndex, Map<String, Class<?>> map) throws SQLException { return callableStatement.getObject(parameterIndex, map); } /** * @return * @throws SQLException * @see java.sql.Statement#getMoreResults() */ public boolean getMoreResults() throws SQLException { return callableStatement.getMoreResults(); } /** * @param parameterIndex * @param x * @param targetSqlType * @throws SQLException * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, int) */ public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException { callableStatement.setObject(parameterIndex, x, targetSqlType); } /** * @param direction * @throws SQLException * @see java.sql.Statement#setFetchDirection(int) */ public void setFetchDirection(int direction) throws SQLException { callableStatement.setFetchDirection(direction); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getRef(int) */ public Ref getRef(int parameterIndex) throws SQLException { return callableStatement.getRef(parameterIndex); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setObject(int, java.lang.Object) */ public void setObject(int parameterIndex, Object x) throws SQLException { callableStatement.setObject(parameterIndex, x); } /** * @return * @throws SQLException * @see java.sql.Statement#getFetchDirection() */ public int getFetchDirection() throws SQLException { return callableStatement.getFetchDirection(); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getBlob(int) */ public Blob getBlob(int parameterIndex) throws SQLException { return callableStatement.getBlob(parameterIndex); } /** * @param rows * @throws SQLException * @see java.sql.Statement#setFetchSize(int) */ public void setFetchSize(int rows) throws SQLException { callableStatement.setFetchSize(rows); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getClob(int) */ public Clob getClob(int parameterIndex) throws SQLException { return callableStatement.getClob(parameterIndex); } /** * @return * @throws SQLException * @see java.sql.Statement#getFetchSize() */ public int getFetchSize() throws SQLException { return callableStatement.getFetchSize(); } /** * @return * @throws SQLException * @see java.sql.PreparedStatement#execute() */ public boolean execute() throws SQLException { return callableStatement.execute(); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getArray(int) */ public Array getArray(int parameterIndex) throws SQLException { return callableStatement.getArray(parameterIndex); } /** * @return * @throws SQLException * @see java.sql.Statement#getResultSetConcurrency() */ public int getResultSetConcurrency() throws SQLException { return callableStatement.getResultSetConcurrency(); } /** * @param parameterIndex * @param cal * @return * @throws SQLException * @see java.sql.CallableStatement#getDate(int, java.util.Calendar) */ public Date getDate(int parameterIndex, Calendar cal) throws SQLException { return callableStatement.getDate(parameterIndex, cal); } /** * @return * @throws SQLException * @see java.sql.Statement#getResultSetType() */ public int getResultSetType() throws SQLException { return callableStatement.getResultSetType(); } /** * @param sql * @throws SQLException * @see java.sql.Statement#addBatch(java.lang.String) */ public void addBatch(String sql) throws SQLException { callableStatement.addBatch(sql); } /** * @throws SQLException * @see java.sql.PreparedStatement#addBatch() */ public void addBatch() throws SQLException { callableStatement.addBatch(); } /** * @param parameterIndex * @param reader * @param length * @throws SQLException * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, int) */ public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException { callableStatement.setCharacterStream(parameterIndex, reader, length); } /** * @param parameterIndex * @param cal * @return * @throws SQLException * @see java.sql.CallableStatement#getTime(int, java.util.Calendar) */ public Time getTime(int parameterIndex, Calendar cal) throws SQLException { return callableStatement.getTime(parameterIndex, cal); } /** * @throws SQLException * @see java.sql.Statement#clearBatch() */ public void clearBatch() throws SQLException { callableStatement.clearBatch(); } /** * @return * @throws SQLException * @see java.sql.Statement#executeBatch() */ public int[] executeBatch() throws SQLException { return callableStatement.executeBatch(); } /** * @param parameterIndex * @param cal * @return * @throws SQLException * @see java.sql.CallableStatement#getTimestamp(int, java.util.Calendar) */ public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException { return callableStatement.getTimestamp(parameterIndex, cal); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setRef(int, java.sql.Ref) */ public void setRef(int parameterIndex, Ref x) throws SQLException { callableStatement.setRef(parameterIndex, x); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setBlob(int, java.sql.Blob) */ public void setBlob(int parameterIndex, Blob x) throws SQLException { callableStatement.setBlob(parameterIndex, x); } /** * @param parameterIndex * @param sqlType * @param typeName * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(int, int, java.lang.String) */ public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException { d("registerOutParameter(parameterIndex/sqlType/typeName):" + parameterIndex + ":" + sqlType + ":" + typeName); callableStatement.registerOutParameter(parameterIndex, sqlType, typeName); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setClob(int, java.sql.Clob) */ public void setClob(int parameterIndex, Clob x) throws SQLException { callableStatement.setClob(parameterIndex, x); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setArray(int, java.sql.Array) */ public void setArray(int parameterIndex, Array x) throws SQLException { callableStatement.setArray(parameterIndex, x); } /** * @return * @throws SQLException * @see java.sql.Statement#getConnection() */ public Connection getConnection() throws SQLException { return callableStatement.getConnection(); } /** * @return * @throws SQLException * @see java.sql.PreparedStatement#getMetaData() */ public ResultSetMetaData getMetaData() throws SQLException { return callableStatement.getMetaData(); } /** * @param parameterName * @param sqlType * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, int) */ public void registerOutParameter(String parameterName, int sqlType) throws SQLException { d("registerOutParameter(parameterName/sqlType):" + parameterName + ":" + sqlType); callableStatement.registerOutParameter(parameterName, sqlType); } /** * @param parameterIndex * @param x * @param cal * @throws SQLException * @see java.sql.PreparedStatement#setDate(int, java.sql.Date, java.util.Calendar) */ public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException { callableStatement.setDate(parameterIndex, x, cal); } /** * @param current * @return * @throws SQLException * @see java.sql.Statement#getMoreResults(int) */ public boolean getMoreResults(int current) throws SQLException { return callableStatement.getMoreResults(current); } /** * @param parameterName * @param sqlType * @param scale * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, int, int) */ public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException { d("registerOutParameter(parameterName/sqlType/scale):" + parameterName + ":" + sqlType + ":" + scale); callableStatement.registerOutParameter(parameterName, sqlType, scale); } /** * @param parameterIndex * @param x * @param cal * @throws SQLException * @see java.sql.PreparedStatement#setTime(int, java.sql.Time, java.util.Calendar) */ public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException { callableStatement.setTime(parameterIndex, x, cal); } /** * @return * @throws SQLException * @see java.sql.Statement#getGeneratedKeys() */ public ResultSet getGeneratedKeys() throws SQLException { return callableStatement.getGeneratedKeys(); } /** * @param parameterIndex * @param x * @param cal * @throws SQLException * @see java.sql.PreparedStatement#setTimestamp(int, java.sql.Timestamp, java.util.Calendar) */ public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException { callableStatement.setTimestamp(parameterIndex, x, cal); } /** * @param parameterName * @param sqlType * @param typeName * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, int, java.lang.String) */ public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException { d("registerOutParameter(parameterName/sqlType/typeName):" + parameterName + ":" + sqlType + ":" + typeName); callableStatement .registerOutParameter(parameterName, sqlType, typeName); } /** * @param sql * @param autoGeneratedKeys * @return * @throws SQLException * @see java.sql.Statement#executeUpdate(java.lang.String, int) */ public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { return callableStatement.executeUpdate(sql, autoGeneratedKeys); } /** * @param parameterIndex * @param sqlType * @param typeName * @throws SQLException * @see java.sql.PreparedStatement#setNull(int, int, java.lang.String) */ public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException { d("setNull(parameterIndex/sqlType/typeName):" + parameterIndex + ":" + sqlType + ":" + typeName); callableStatement.setNull(parameterIndex, sqlType, typeName); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getURL(int) */ public URL getURL(int parameterIndex) throws SQLException { return callableStatement.getURL(parameterIndex); } /** * @param sql * @param columnIndexes * @return * @throws SQLException * @see java.sql.Statement#executeUpdate(java.lang.String, int[]) */ public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { return callableStatement.executeUpdate(sql, columnIndexes); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setURL(int, java.net.URL) */ public void setURL(int parameterIndex, URL x) throws SQLException { callableStatement.setURL(parameterIndex, x); } /** * @param parameterName * @param val * @throws SQLException * @see java.sql.CallableStatement#setURL(java.lang.String, java.net.URL) */ public void setURL(String parameterName, URL val) throws SQLException { callableStatement.setURL(parameterName, val); } /** * @return * @throws SQLException * @see java.sql.PreparedStatement#getParameterMetaData() */ public ParameterMetaData getParameterMetaData() throws SQLException { return callableStatement.getParameterMetaData(); } /** * @param parameterName * @param sqlType * @throws SQLException * @see java.sql.CallableStatement#setNull(java.lang.String, int) */ public void setNull(String parameterName, int sqlType) throws SQLException { d("setNull(parameterName/sqlType):" + parameterName + ":" + sqlType); callableStatement.setNull(parameterName, sqlType); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setRowId(int, java.sql.RowId) */ public void setRowId(int parameterIndex, RowId x) throws SQLException { callableStatement.setRowId(parameterIndex, x); } /** * @param sql * @param columnNames * @return * @throws SQLException * @see java.sql.Statement#executeUpdate(java.lang.String, java.lang.String[]) */ public int executeUpdate(String sql, String[] columnNames) throws SQLException { return callableStatement.executeUpdate(sql, columnNames); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setBoolean(java.lang.String, boolean) */ public void setBoolean(String parameterName, boolean x) throws SQLException { callableStatement.setBoolean(parameterName, x); } /** * @param parameterIndex * @param value * @throws SQLException * @see java.sql.PreparedStatement#setNString(int, java.lang.String) */ public void setNString(int parameterIndex, String value) throws SQLException { callableStatement.setNString(parameterIndex, value); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setByte(java.lang.String, byte) */ public void setByte(String parameterName, byte x) throws SQLException { callableStatement.setByte(parameterName, x); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setShort(java.lang.String, short) */ public void setShort(String parameterName, short x) throws SQLException { callableStatement.setShort(parameterName, x); } /** * @param parameterIndex * @param value * @param length * @throws SQLException * @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader, long) */ public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException { callableStatement.setNCharacterStream(parameterIndex, value, length); } /** * @param sql * @param autoGeneratedKeys * @return * @throws SQLException * @see java.sql.Statement#execute(java.lang.String, int) */ public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { return callableStatement.execute(sql, autoGeneratedKeys); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setInt(java.lang.String, int) */ public void setInt(String parameterName, int x) throws SQLException { callableStatement.setInt(parameterName, x); } /** * @param parameterIndex * @param value * @throws SQLException * @see java.sql.PreparedStatement#setNClob(int, java.sql.NClob) */ public void setNClob(int parameterIndex, NClob value) throws SQLException { callableStatement.setNClob(parameterIndex, value); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setLong(java.lang.String, long) */ public void setLong(String parameterName, long x) throws SQLException { callableStatement.setLong(parameterName, x); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setFloat(java.lang.String, float) */ public void setFloat(String parameterName, float x) throws SQLException { callableStatement.setFloat(parameterName, x); } /** * @param parameterIndex * @param reader * @param length * @throws SQLException * @see java.sql.PreparedStatement#setClob(int, java.io.Reader, long) */ public void setClob(int parameterIndex, Reader reader, long length) throws SQLException { callableStatement.setClob(parameterIndex, reader, length); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setDouble(java.lang.String, double) */ public void setDouble(String parameterName, double x) throws SQLException { callableStatement.setDouble(parameterName, x); } /** * @param sql * @param columnIndexes * @return * @throws SQLException * @see java.sql.Statement#execute(java.lang.String, int[]) */ public boolean execute(String sql, int[] columnIndexes) throws SQLException { return callableStatement.execute(sql, columnIndexes); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setBigDecimal(java.lang.String, java.math.BigDecimal) */ public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException { callableStatement.setBigDecimal(parameterName, x); } /** * @param parameterIndex * @param inputStream * @param length * @throws SQLException * @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream, long) */ public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException { callableStatement.setBlob(parameterIndex, inputStream, length); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setString(java.lang.String, java.lang.String) */ public void setString(String parameterName, String x) throws SQLException { d("setString:" + parameterName + ":" + x); callableStatement.setString(parameterName, x); } /** * @param parameterIndex * @param reader * @param length * @throws SQLException * @see java.sql.PreparedStatement#setNClob(int, java.io.Reader, long) */ public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException { callableStatement.setNClob(parameterIndex, reader, length); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setBytes(java.lang.String, byte[]) */ public void setBytes(String parameterName, byte[] x) throws SQLException { callableStatement.setBytes(parameterName, x); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setDate(java.lang.String, java.sql.Date) */ public void setDate(String parameterName, Date x) throws SQLException { callableStatement.setDate(parameterName, x); } /** * @param sql * @param columnNames * @return * @throws SQLException * @see java.sql.Statement#execute(java.lang.String, java.lang.String[]) */ public boolean execute(String sql, String[] columnNames) throws SQLException { return callableStatement.execute(sql, columnNames); } /** * @param parameterIndex * @param xmlObject * @throws SQLException * @see java.sql.PreparedStatement#setSQLXML(int, java.sql.SQLXML) */ public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException { callableStatement.setSQLXML(parameterIndex, xmlObject); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setTime(java.lang.String, java.sql.Time) */ public void setTime(String parameterName, Time x) throws SQLException { callableStatement.setTime(parameterName, x); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setTimestamp(java.lang.String, java.sql.Timestamp) */ public void setTimestamp(String parameterName, Timestamp x) throws SQLException { callableStatement.setTimestamp(parameterName, x); } /** * @param parameterIndex * @param x * @param targetSqlType * @param scaleOrLength * @throws SQLException * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, int, int) */ public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException { callableStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength); } /** * @param parameterName * @param x * @param length * @throws SQLException * @see java.sql.CallableStatement#setAsciiStream(java.lang.String, java.io.InputStream, int) */ public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException { callableStatement.setAsciiStream(parameterName, x, length); } /** * @return * @throws SQLException * @see java.sql.Statement#getResultSetHoldability() */ public int getResultSetHoldability() throws SQLException { return callableStatement.getResultSetHoldability(); } /** * @return * @throws SQLException * @see java.sql.Statement#isClosed() */ public boolean isClosed() throws SQLException { return callableStatement.isClosed(); } /** * @param parameterName * @param x * @param length * @throws SQLException * @see java.sql.CallableStatement#setBinaryStream(java.lang.String, java.io.InputStream, int) */ public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException { callableStatement.setBinaryStream(parameterName, x, length); } /** * @param poolable * @throws SQLException * @see java.sql.Statement#setPoolable(boolean) */ public void setPoolable(boolean poolable) throws SQLException { callableStatement.setPoolable(poolable); } /** * @param parameterIndex * @param x * @param length * @throws SQLException * @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream, long) */ public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException { callableStatement.setAsciiStream(parameterIndex, x, length); } /** * @param parameterName * @param x * @param targetSqlType * @param scale * @throws SQLException * @see java.sql.CallableStatement#setObject(java.lang.String, java.lang.Object, int, int) */ public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException { callableStatement.setObject(parameterName, x, targetSqlType, scale); } /** * @return * @throws SQLException * @see java.sql.Statement#isPoolable() */ public boolean isPoolable() throws SQLException { return callableStatement.isPoolable(); } /** * @throws SQLException * @see java.sql.Statement#closeOnCompletion() */ public void closeOnCompletion() throws SQLException { callableStatement.closeOnCompletion(); } /** * @param parameterIndex * @param x * @param length * @throws SQLException * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, long) */ public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException { callableStatement.setBinaryStream(parameterIndex, x, length); } /** * @return * @throws SQLException * @see java.sql.Statement#isCloseOnCompletion() */ public boolean isCloseOnCompletion() throws SQLException { return callableStatement.isCloseOnCompletion(); } /** * @param parameterName * @param x * @param targetSqlType * @throws SQLException * @see java.sql.CallableStatement#setObject(java.lang.String, java.lang.Object, int) */ public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException { callableStatement.setObject(parameterName, x, targetSqlType); } /** * @param parameterIndex * @param reader * @param length * @throws SQLException * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, long) */ public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException { callableStatement.setCharacterStream(parameterIndex, reader, length); } /** * @return * @throws SQLException * @see java.sql.Statement#getLargeUpdateCount() */ public long getLargeUpdateCount() throws SQLException { return callableStatement.getLargeUpdateCount(); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setObject(java.lang.String, java.lang.Object) */ public void setObject(String parameterName, Object x) throws SQLException { callableStatement.setObject(parameterName, x); } /** * @param max * @throws SQLException * @see java.sql.Statement#setLargeMaxRows(long) */ public void setLargeMaxRows(long max) throws SQLException { callableStatement.setLargeMaxRows(max); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setAsciiStream(int, java.io.InputStream) */ public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException { callableStatement.setAsciiStream(parameterIndex, x); } /** * @return * @throws SQLException * @see java.sql.Statement#getLargeMaxRows() */ public long getLargeMaxRows() throws SQLException { return callableStatement.getLargeMaxRows(); } /** * @param parameterIndex * @param x * @throws SQLException * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream) */ public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException { callableStatement.setBinaryStream(parameterIndex, x); } /** * @return * @throws SQLException * @see java.sql.Statement#executeLargeBatch() */ public long[] executeLargeBatch() throws SQLException { return callableStatement.executeLargeBatch(); } /** * @param parameterName * @param reader * @param length * @throws SQLException * @see java.sql.CallableStatement#setCharacterStream(java.lang.String, java.io.Reader, int) */ public void setCharacterStream(String parameterName, Reader reader, int length) throws SQLException { callableStatement.setCharacterStream(parameterName, reader, length); } /** * @param parameterIndex * @param reader * @throws SQLException * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader) */ public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException { callableStatement.setCharacterStream(parameterIndex, reader); } /** * @param parameterName * @param x * @param cal * @throws SQLException * @see java.sql.CallableStatement#setDate(java.lang.String, java.sql.Date, java.util.Calendar) */ public void setDate(String parameterName, Date x, Calendar cal) throws SQLException { callableStatement.setDate(parameterName, x, cal); } /** * @param parameterIndex * @param value * @throws SQLException * @see java.sql.PreparedStatement#setNCharacterStream(int, java.io.Reader) */ public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException { callableStatement.setNCharacterStream(parameterIndex, value); } /** * @param parameterName * @param x * @param cal * @throws SQLException * @see java.sql.CallableStatement#setTime(java.lang.String, java.sql.Time, java.util.Calendar) */ public void setTime(String parameterName, Time x, Calendar cal) throws SQLException { callableStatement.setTime(parameterName, x, cal); } /** * @param sql * @return * @throws SQLException * @see java.sql.Statement#executeLargeUpdate(java.lang.String) */ public long executeLargeUpdate(String sql) throws SQLException { return callableStatement.executeLargeUpdate(sql); } /** * @param parameterIndex * @param reader * @throws SQLException * @see java.sql.PreparedStatement#setClob(int, java.io.Reader) */ public void setClob(int parameterIndex, Reader reader) throws SQLException { callableStatement.setClob(parameterIndex, reader); } /** * @param parameterName * @param x * @param cal * @throws SQLException * @see java.sql.CallableStatement#setTimestamp(java.lang.String, java.sql.Timestamp, java.util.Calendar) */ public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException { callableStatement.setTimestamp(parameterName, x, cal); } /** * @param sql * @param autoGeneratedKeys * @return * @throws SQLException * @see java.sql.Statement#executeLargeUpdate(java.lang.String, int) */ public long executeLargeUpdate(String sql, int autoGeneratedKeys) throws SQLException { return callableStatement.executeLargeUpdate(sql, autoGeneratedKeys); } /** * @param parameterName * @param sqlType * @param typeName * @throws SQLException * @see java.sql.CallableStatement#setNull(java.lang.String, int, java.lang.String) */ public void setNull(String parameterName, int sqlType, String typeName) throws SQLException { d("setNull(parameterName/sqlType/typeName):" + parameterName + ":" + sqlType + ":" + typeName); callableStatement.setNull(parameterName, sqlType, typeName); } /** * @param parameterIndex * @param inputStream * @throws SQLException * @see java.sql.PreparedStatement#setBlob(int, java.io.InputStream) */ public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException { callableStatement.setBlob(parameterIndex, inputStream); } /** * @param parameterIndex * @param reader * @throws SQLException * @see java.sql.PreparedStatement#setNClob(int, java.io.Reader) */ public void setNClob(int parameterIndex, Reader reader) throws SQLException { callableStatement.setNClob(parameterIndex, reader); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getString(java.lang.String) */ public String getString(String parameterName) throws SQLException { return callableStatement.getString(parameterName); } /** * @param sql * @param columnIndexes * @return * @throws SQLException * @see java.sql.Statement#executeLargeUpdate(java.lang.String, int[]) */ public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException { return callableStatement.executeLargeUpdate(sql, columnIndexes); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getBoolean(java.lang.String) */ public boolean getBoolean(String parameterName) throws SQLException { return callableStatement.getBoolean(parameterName); } /** * @param parameterIndex * @param x * @param targetSqlType * @param scaleOrLength * @throws SQLException * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, java.sql.SQLType, int) */ public void setObject(int parameterIndex, Object x, SQLType targetSqlType, int scaleOrLength) throws SQLException { callableStatement.setObject(parameterIndex, x, targetSqlType, scaleOrLength); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getByte(java.lang.String) */ public byte getByte(String parameterName) throws SQLException { return callableStatement.getByte(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getShort(java.lang.String) */ public short getShort(String parameterName) throws SQLException { return callableStatement.getShort(parameterName); } /** * @param sql * @param columnNames * @return * @throws SQLException * @see java.sql.Statement#executeLargeUpdate(java.lang.String, java.lang.String[]) */ public long executeLargeUpdate(String sql, String[] columnNames) throws SQLException { return callableStatement.executeLargeUpdate(sql, columnNames); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getInt(java.lang.String) */ public int getInt(String parameterName) throws SQLException { return callableStatement.getInt(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getLong(java.lang.String) */ public long getLong(String parameterName) throws SQLException { return callableStatement.getLong(parameterName); } /** * @param parameterIndex * @param x * @param targetSqlType * @throws SQLException * @see java.sql.PreparedStatement#setObject(int, java.lang.Object, java.sql.SQLType) */ public void setObject(int parameterIndex, Object x, SQLType targetSqlType) throws SQLException { callableStatement.setObject(parameterIndex, x, targetSqlType); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getFloat(java.lang.String) */ public float getFloat(String parameterName) throws SQLException { return callableStatement.getFloat(parameterName); } /** * @return * @throws SQLException * @see java.sql.PreparedStatement#executeLargeUpdate() */ public long executeLargeUpdate() throws SQLException { return callableStatement.executeLargeUpdate(); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getDouble(java.lang.String) */ public double getDouble(String parameterName) throws SQLException { return callableStatement.getDouble(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getBytes(java.lang.String) */ public byte[] getBytes(String parameterName) throws SQLException { return callableStatement.getBytes(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getDate(java.lang.String) */ public Date getDate(String parameterName) throws SQLException { return callableStatement.getDate(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getTime(java.lang.String) */ public Time getTime(String parameterName) throws SQLException { return callableStatement.getTime(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getTimestamp(java.lang.String) */ public Timestamp getTimestamp(String parameterName) throws SQLException { return callableStatement.getTimestamp(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getObject(java.lang.String) */ public Object getObject(String parameterName) throws SQLException { return callableStatement.getObject(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getBigDecimal(java.lang.String) */ public BigDecimal getBigDecimal(String parameterName) throws SQLException { return callableStatement.getBigDecimal(parameterName); } /** * @param parameterName * @param map * @return * @throws SQLException * @see java.sql.CallableStatement#getObject(java.lang.String, java.util.Map) */ public Object getObject(String parameterName, Map<String, Class<?>> map) throws SQLException { return callableStatement.getObject(parameterName, map); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getRef(java.lang.String) */ public Ref getRef(String parameterName) throws SQLException { return callableStatement.getRef(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getBlob(java.lang.String) */ public Blob getBlob(String parameterName) throws SQLException { return callableStatement.getBlob(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getClob(java.lang.String) */ public Clob getClob(String parameterName) throws SQLException { return callableStatement.getClob(parameterName); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getArray(java.lang.String) */ public Array getArray(String parameterName) throws SQLException { return callableStatement.getArray(parameterName); } /** * @param parameterName * @param cal * @return * @throws SQLException * @see java.sql.CallableStatement#getDate(java.lang.String, java.util.Calendar) */ public Date getDate(String parameterName, Calendar cal) throws SQLException { return callableStatement.getDate(parameterName, cal); } /** * @param parameterName * @param cal * @return * @throws SQLException * @see java.sql.CallableStatement#getTime(java.lang.String, java.util.Calendar) */ public Time getTime(String parameterName, Calendar cal) throws SQLException { return callableStatement.getTime(parameterName, cal); } /** * @param parameterName * @param cal * @return * @throws SQLException * @see java.sql.CallableStatement#getTimestamp(java.lang.String, java.util.Calendar) */ public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { return callableStatement.getTimestamp(parameterName, cal); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getURL(java.lang.String) */ public URL getURL(String parameterName) throws SQLException { return callableStatement.getURL(parameterName); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getRowId(int) */ public RowId getRowId(int parameterIndex) throws SQLException { return callableStatement.getRowId(parameterIndex); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getRowId(java.lang.String) */ public RowId getRowId(String parameterName) throws SQLException { return callableStatement.getRowId(parameterName); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setRowId(java.lang.String, java.sql.RowId) */ public void setRowId(String parameterName, RowId x) throws SQLException { callableStatement.setRowId(parameterName, x); } /** * @param parameterName * @param value * @throws SQLException * @see java.sql.CallableStatement#setNString(java.lang.String, java.lang.String) */ public void setNString(String parameterName, String value) throws SQLException { callableStatement.setNString(parameterName, value); } /** * @param parameterName * @param value * @param length * @throws SQLException * @see java.sql.CallableStatement#setNCharacterStream(java.lang.String, java.io.Reader, long) */ public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException { callableStatement.setNCharacterStream(parameterName, value, length); } /** * @param parameterName * @param value * @throws SQLException * @see java.sql.CallableStatement#setNClob(java.lang.String, java.sql.NClob) */ public void setNClob(String parameterName, NClob value) throws SQLException { callableStatement.setNClob(parameterName, value); } /** * @param parameterName * @param reader * @param length * @throws SQLException * @see java.sql.CallableStatement#setClob(java.lang.String, java.io.Reader, long) */ public void setClob(String parameterName, Reader reader, long length) throws SQLException { callableStatement.setClob(parameterName, reader, length); } /** * @param parameterName * @param inputStream * @param length * @throws SQLException * @see java.sql.CallableStatement#setBlob(java.lang.String, java.io.InputStream, long) */ public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException { callableStatement.setBlob(parameterName, inputStream, length); } /** * @param parameterName * @param reader * @param length * @throws SQLException * @see java.sql.CallableStatement#setNClob(java.lang.String, java.io.Reader, long) */ public void setNClob(String parameterName, Reader reader, long length) throws SQLException { callableStatement.setNClob(parameterName, reader, length); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getNClob(int) */ public NClob getNClob(int parameterIndex) throws SQLException { return callableStatement.getNClob(parameterIndex); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getNClob(java.lang.String) */ public NClob getNClob(String parameterName) throws SQLException { return callableStatement.getNClob(parameterName); } /** * @param parameterName * @param xmlObject * @throws SQLException * @see java.sql.CallableStatement#setSQLXML(java.lang.String, java.sql.SQLXML) */ public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException { callableStatement.setSQLXML(parameterName, xmlObject); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getSQLXML(int) */ public SQLXML getSQLXML(int parameterIndex) throws SQLException { return callableStatement.getSQLXML(parameterIndex); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getSQLXML(java.lang.String) */ public SQLXML getSQLXML(String parameterName) throws SQLException { return callableStatement.getSQLXML(parameterName); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getNString(int) */ public String getNString(int parameterIndex) throws SQLException { return callableStatement.getNString(parameterIndex); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getNString(java.lang.String) */ public String getNString(String parameterName) throws SQLException { return callableStatement.getNString(parameterName); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getNCharacterStream(int) */ public Reader getNCharacterStream(int parameterIndex) throws SQLException { return callableStatement.getNCharacterStream(parameterIndex); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getNCharacterStream(java.lang.String) */ public Reader getNCharacterStream(String parameterName) throws SQLException { return callableStatement.getNCharacterStream(parameterName); } /** * @param parameterIndex * @return * @throws SQLException * @see java.sql.CallableStatement#getCharacterStream(int) */ public Reader getCharacterStream(int parameterIndex) throws SQLException { return callableStatement.getCharacterStream(parameterIndex); } /** * @param parameterName * @return * @throws SQLException * @see java.sql.CallableStatement#getCharacterStream(java.lang.String) */ public Reader getCharacterStream(String parameterName) throws SQLException { return callableStatement.getCharacterStream(parameterName); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setBlob(java.lang.String, java.sql.Blob) */ public void setBlob(String parameterName, Blob x) throws SQLException { callableStatement.setBlob(parameterName, x); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setClob(java.lang.String, java.sql.Clob) */ public void setClob(String parameterName, Clob x) throws SQLException { callableStatement.setClob(parameterName, x); } /** * @param parameterName * @param x * @param length * @throws SQLException * @see java.sql.CallableStatement#setAsciiStream(java.lang.String, java.io.InputStream, long) */ public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException { callableStatement.setAsciiStream(parameterName, x, length); } /** * @param parameterName * @param x * @param length * @throws SQLException * @see java.sql.CallableStatement#setBinaryStream(java.lang.String, java.io.InputStream, long) */ public void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException { callableStatement.setBinaryStream(parameterName, x, length); } /** * @param parameterName * @param reader * @param length * @throws SQLException * @see java.sql.CallableStatement#setCharacterStream(java.lang.String, java.io.Reader, long) */ public void setCharacterStream(String parameterName, Reader reader, long length) throws SQLException { callableStatement.setCharacterStream(parameterName, reader, length); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setAsciiStream(java.lang.String, java.io.InputStream) */ public void setAsciiStream(String parameterName, InputStream x) throws SQLException { callableStatement.setAsciiStream(parameterName, x); } /** * @param parameterName * @param x * @throws SQLException * @see java.sql.CallableStatement#setBinaryStream(java.lang.String, java.io.InputStream) */ public void setBinaryStream(String parameterName, InputStream x) throws SQLException { callableStatement.setBinaryStream(parameterName, x); } /** * @param parameterName * @param reader * @throws SQLException * @see java.sql.CallableStatement#setCharacterStream(java.lang.String, java.io.Reader) */ public void setCharacterStream(String parameterName, Reader reader) throws SQLException { callableStatement.setCharacterStream(parameterName, reader); } /** * @param parameterName * @param value * @throws SQLException * @see java.sql.CallableStatement#setNCharacterStream(java.lang.String, java.io.Reader) */ public void setNCharacterStream(String parameterName, Reader value) throws SQLException { callableStatement.setNCharacterStream(parameterName, value); } /** * @param parameterName * @param reader * @throws SQLException * @see java.sql.CallableStatement#setClob(java.lang.String, java.io.Reader) */ public void setClob(String parameterName, Reader reader) throws SQLException { callableStatement.setClob(parameterName, reader); } /** * @param parameterName * @param inputStream * @throws SQLException * @see java.sql.CallableStatement#setBlob(java.lang.String, java.io.InputStream) */ public void setBlob(String parameterName, InputStream inputStream) throws SQLException { callableStatement.setBlob(parameterName, inputStream); } /** * @param parameterName * @param reader * @throws SQLException * @see java.sql.CallableStatement#setNClob(java.lang.String, java.io.Reader) */ public void setNClob(String parameterName, Reader reader) throws SQLException { callableStatement.setNClob(parameterName, reader); } /** * @param parameterIndex * @param type * @return * @throws SQLException * @see java.sql.CallableStatement#getObject(int, java.lang.Class) */ public <T> T getObject(int parameterIndex, Class<T> type) throws SQLException { return callableStatement.getObject(parameterIndex, type); } /** * @param parameterName * @param type * @return * @throws SQLException * @see java.sql.CallableStatement#getObject(java.lang.String, java.lang.Class) */ public <T> T getObject(String parameterName, Class<T> type) throws SQLException { return callableStatement.getObject(parameterName, type); } /** * @param parameterName * @param x * @param targetSqlType * @param scaleOrLength * @throws SQLException * @see java.sql.CallableStatement#setObject(java.lang.String, java.lang.Object, java.sql.SQLType, int) */ public void setObject(String parameterName, Object x, SQLType targetSqlType, int scaleOrLength) throws SQLException { callableStatement.setObject(parameterName, x, targetSqlType, scaleOrLength); } /** * @param parameterName * @param x * @param targetSqlType * @throws SQLException * @see java.sql.CallableStatement#setObject(java.lang.String, java.lang.Object, java.sql.SQLType) */ public void setObject(String parameterName, Object x, SQLType targetSqlType) throws SQLException { callableStatement.setObject(parameterName, x, targetSqlType); } /** * @param parameterIndex * @param sqlType * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(int, java.sql.SQLType) */ public void registerOutParameter(int parameterIndex, SQLType sqlType) throws SQLException { d("registerOutParameter(parameterIndex/sqlType):" + parameterIndex + ":" + sqlType + ""); callableStatement.registerOutParameter(parameterIndex, sqlType); } /** * @param parameterIndex * @param sqlType * @param scale * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(int, java.sql.SQLType, int) */ public void registerOutParameter(int parameterIndex, SQLType sqlType, int scale) throws SQLException { d("registerOutParameter(parameterIndex/sqlType/scale):" + parameterIndex + ":" + sqlType + ":" + scale); callableStatement.registerOutParameter(parameterIndex, sqlType, scale); } /** * @param parameterIndex * @param sqlType * @param typeName * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(int, java.sql.SQLType, java.lang.String) */ public void registerOutParameter(int parameterIndex, SQLType sqlType, String typeName) throws SQLException { d("registerOutParameter(parameterIndex/sqlType/typeName):" + parameterIndex + ":" + sqlType + ":" + typeName); callableStatement.registerOutParameter(parameterIndex, sqlType, typeName); } /** * @param parameterName * @param sqlType * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, java.sql.SQLType) */ public void registerOutParameter(String parameterName, SQLType sqlType) throws SQLException { d("registerOutParameter(parameterName/sqlType):" + parameterName + ":" + sqlType); callableStatement.registerOutParameter(parameterName, sqlType); } /** * @param parameterName * @param sqlType * @param scale * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, java.sql.SQLType, int) */ public void registerOutParameter(String parameterName, SQLType sqlType, int scale) throws SQLException { d("registerOutParameter(parameterName/sqlType/scale):" + parameterName + ":" + sqlType + ":" + scale); callableStatement.registerOutParameter(parameterName, sqlType, scale); } /** * @param parameterName * @param sqlType * @param typeName * @throws SQLException * @see java.sql.CallableStatement#registerOutParameter(java.lang.String, java.sql.SQLType, java.lang.String) */ public void registerOutParameter(String parameterName, SQLType sqlType, String typeName) throws SQLException { d("registerOutParameter(parameterName/sqlType/typeName):" + parameterName + ":" + sqlType + ":" + typeName); callableStatement .registerOutParameter(parameterName, sqlType, typeName); } }
31.029779
119
0.632481
31455f99c0169530930f72e69e0c4a441ffb7ec6
3,322
package org.apache.solr.search.xjoin; /* * 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 org.apache.solr.SolrTestCaseJ4; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.core.SolrCore; import org.apache.solr.handler.component.SearchComponent; import org.apache.solr.request.LocalSolrQueryRequest; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.request.SolrRequestHandler; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.search.QParserPlugin; import org.apache.solr.search.xjoin.simple.TestSimple; import org.junit.BeforeClass; import org.junit.Ignore; /** * Test case for XJoin, setting up a core containing test documents. */ @Ignore public abstract class AbstractXJoinTestCase extends SolrTestCaseJ4 { protected static int numberOfDocs = 0; @BeforeClass public static void beforeClass() throws Exception { System.setProperty("simple-test-file", TestSimple.class.getResource("results.json").toString()); initCore("solrconfig.xml", "schema.xml", "xjoin/solr"); numberOfDocs = 0; for (String[] doc : DOCUMENTS) { assertNull(h.validateUpdate(adoc("id", Integer.toString(numberOfDocs), "colour", doc[0], "letter", doc[1], "letter", doc[2]))); numberOfDocs++; } assertNull(h.validateUpdate(commit())); } final static String[][] DOCUMENTS = new String[][] { { "red", "alpha", "beta" }, { "green", "alpha", "gamma" }, { "blue", "delta", "gamma" }, { "pink", "theta", "gamma" }, { "blue", "epsilon", "zeta" } }; @SuppressWarnings("rawtypes") protected NamedList test(ModifiableSolrParams params, String componentName) { SolrCore core = h.getCore(); SearchComponent sc = core.getSearchComponent(componentName); assertTrue("XJoinSearchComponent not found in solrconfig", sc != null); QParserPlugin qp = core.getQueryPlugin("xjoin"); assertTrue("XJoinQParserPlugin not found in solrconfig", qp != null); params.add("q", "*:*"); params.add("fq", "{!xjoin}" + componentName); SolrQueryResponse rsp = new SolrQueryResponse(); rsp.add("responseHeader", new SimpleOrderedMap<>()); SolrQueryRequest req = new LocalSolrQueryRequest(core, params); SolrRequestHandler handler = core.getRequestHandler("standard"); handler.handleRequest(req, rsp); req.close(); assertNull(rsp.getException()); return rsp.getValues(); } }
36.911111
133
0.72065
b2faf9052b66b1cd7f0f896b763ceef8a8a4700a
1,193
package com.ext.nacid.web.taglib.applications.report.internal; import java.io.IOException; import java.util.List; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.SimpleTagSupport; import com.nacid.web.WebKeys; import com.nacid.web.model.applications.report.internal.UniversityExaminationByPlaceInternalForReportWebModel; public class ExpertReportUniversityExaminationByPlaceViewTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { List<UniversityExaminationByPlaceInternalForReportWebModel> universityExaminations = (List<UniversityExaminationByPlaceInternalForReportWebModel>) getJspContext().getAttribute(WebKeys.UNIVERSITY_EXAMINATION_BY_PLACE_WEB_MODEL, PageContext.REQUEST_SCOPE); if (universityExaminations != null) { for (UniversityExaminationByPlaceInternalForReportWebModel universityExamination : universityExaminations) { getJspContext().setAttribute("trainingLocation", universityExamination.getTrainingLocation()); getJspContext().setAttribute("trainingInstitution", universityExamination.getTrainingInstitution()); getJspBody().invoke(null); } } } }
39.766667
256
0.838223
af8900c09922665e42ed0402a96891b51a853dc8
1,126
package net.minecraft.client.model; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import java.util.function.Function; import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.renderer.RenderType; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.entity.Entity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; @OnlyIn(Dist.CLIENT) public abstract class ListModel<E extends Entity> extends EntityModel<E> { public ListModel() { this(RenderType::entityCutoutNoCull); } public ListModel(Function<ResourceLocation, RenderType> p_103011_) { super(p_103011_); } public void renderToBuffer(PoseStack p_103013_, VertexConsumer p_103014_, int p_103015_, int p_103016_, float p_103017_, float p_103018_, float p_103019_, float p_103020_) { this.parts().forEach((p_103030_) -> { p_103030_.render(p_103013_, p_103014_, p_103015_, p_103016_, p_103017_, p_103018_, p_103019_, p_103020_); }); } public abstract Iterable<ModelPart> parts(); }
37.533333
176
0.774423
67167e7c3fde614866dc1d7af28f6b06b69e97cd
2,723
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; import edu.wpi.first.cameraserver.CameraServer; import edu.wpi.first.cscore.UsbCamera; import edu.wpi.first.networktables.NetworkTable; import edu.wpi.first.networktables.NetworkTableInstance; import edu.wpi.first.wpilibj.TimedRobot; import frc.molib.buttons.ButtonManager; import frc.molib.utilities.Console; import frc.robot.period.Autonomous; import frc.robot.period.Disabled; import frc.robot.period.Teleoperated; import frc.robot.period.Test; import frc.robot.subsystem.Drivetrain; import frc.robot.subsystem.Manipulator; public class Robot extends TimedRobot { public static final NetworkTable tblMain = NetworkTableInstance.getDefault().getTable("MO Data"); public static final NetworkTable tblPeriods = tblMain.getSubTable("Control Periods"); public static final NetworkTable tblSubsystems = tblMain.getSubTable("Subsystems"); private static UsbCamera camDrive; @Override public void robotInit() { Console.logMsg("*****Robot Initialization Starting*****"); Console.logMsg("Establishing NetworkTable Connection..."); while(!NetworkTableInstance.getDefault().isConnected()) {} NetworkTableInstance.getDefault().deleteAllEntries(); Console.logMsg("*****Initializing Subsystems***********"); Drivetrain.init(); Manipulator.init(); Console.logMsg("*****Initializing Dashboard************"); Autonomous.initDashboard(); Teleoperated.initDashboard(); Test.initDashboard(); Drivetrain.initDashboard(); Manipulator.initDashboard(); Console.logMsg("*****Initializing Cameras**************"); camDrive = CameraServer.startAutomaticCapture("Camera 1", 0); camDrive.setFPS(10); camDrive.setResolution(160, 100); Console.logMsg("*****Robot Initialization Complete*****"); } @Override public void robotPeriodic() { ButtonManager.updateValues(); Autonomous.updateDashboard(); Teleoperated.updateDashboard(); Test.updateDashboard(); Drivetrain.updateDashboard(); Manipulator.updateDashboard(); } @Override public void disabledInit() { Disabled.init(); } @Override public void disabledPeriodic() { Disabled.periodic(); } @Override public void testInit() { Test.init(); } @Override public void testPeriodic() { Test.periodic(); } @Override public void autonomousInit() { Autonomous.init(); } @Override public void autonomousPeriodic() { Autonomous.periodic(); } @Override public void teleopInit() { Teleoperated.init(); } @Override public void teleopPeriodic() { Teleoperated.periodic(); } }
25.212963
98
0.740727
e4029d632258fb0fe55f3e25a1ecce930f4fa732
2,187
package ides.dsl.parser; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.Interval; import org.antlr.v4.runtime.tree.ParseTreeWalker; /** * Created by songgr on 2020/10/23. */ public class ListenerTest { public static void main(String[] args) { String expr = "load hive.`a.bc` as table1;\n" + "\n----注释" + "\n" + "\n/*------*/" + "\n" + "\n" + "\n" + "load jsonStr.`abc` as table1;\n" + "load hive.`a.abc` as table1;\n" + "!hdfs -cp /tmp/abc.txt /tmp/dd;"; CodePointCharStream cpcs = CharStreams.fromString(expr); IdesLexer idesDslLexer = new IdesLexer(cpcs); CommonTokenStream tokenStream = new CommonTokenStream(idesDslLexer); IdesParser parser = new IdesParser(tokenStream); MyListener listener = new MyListener(); IdesParser.StatementContext statement = parser.statement(); ParseTreeWalker.DEFAULT.walk(listener, statement); } } class MyListener extends IdesParserBaseListener { @Override public void exitSql(IdesParser.SqlContext ctx) { System.out.println(ctx.getText()); } @Override public void exitLoad(IdesParser.LoadContext ctx) { String text = ctx.format().getText(); System.out.println("load -----> " + text); } @Override public void exitCommand(IdesParser.CommandContext ctx) { String text = ctx.commandParam().getText(); System.out.println("exec=======>" + text); String commandParam = currentText(ctx.commandParam()); System.out.println(commandParam); System.out.println(commandParam.split(" ")); super.exitCommand(ctx); } public String currentText(ParserRuleContext ctx) { if ( ctx == null ) return null; IdesLexer lexer = (IdesLexer)ctx.start.getTokenSource(); CharStream input = lexer._input; int start = ctx.start.getStartIndex(); int stop = ctx.stop.getStopIndex(); Interval interval = new Interval(start, stop); return input.getText(interval); } }
30.375
76
0.600366
8594db731e514348a6041f0acfaf4bca8a705d06
3,462
package fatcat.ai; import fatcat.EntityFatCat; import fatcat.EntityFatCat.StatusChangeReason; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; /* 恋愛度が高ければ子供を作る */ public class EntityAIFatCatMate extends EntityAIBase { private EntityFatCat cat; private EntityFatCat mate; private World worldObj; private int matingTimeout; private int tick; private static final int CAT_MIN_WEIGHT = 4000; public EntityAIFatCatMate(EntityFatCat cat) { this.cat = cat; this.worldObj = cat.worldObj; this.setMutexBits(15); } @Override public boolean shouldExecute() { // System.out.println("EntityAIFatCatMate(shouldExecute): cs="+checkSufficientMating(cat)); boolean exec = true; if (cat.getRNG().nextInt(500) != 0) { exec = false; } else if (cat.isMating) { exec = false; } else if (!checkSufficientMating(cat)) { exec = false; } if (exec || cat.tryMating) { EntityFatCat entity = (EntityFatCat) this.worldObj.findNearestEntityWithinAABB(EntityFatCat.class, cat.getEntityBoundingBox().expand(8.0D, 3.0D, 8.0D), this.cat); exec = checkSufficientMating(mate); this.mate = entity; // System.out.println("EntityAIFatCatMate(shouldExecute): exec="+exec+","); } return exec; } @Override public void startExecuting() { this.matingTimeout = 300; this.tick = 0; this.cat.isMating = true; this.cat.setAISit(false); if (!this.mate.isMating) { this.mate.tryMating = true; } } @Override public void resetTask() { this.cat.isMating = false; this.mate.isMating = false; this.cat.tryMating = false; this.cat.setAISit(true); this.mate = null; } @Override public boolean continueExecuting() { return this.matingTimeout >= 0 && cat.isMating && checkSufficientMating(cat) && checkSufficientMating(mate); } @Override public void updateTask() { --this.matingTimeout; this.cat.getLookHelper().setLookPositionWithEntity(this.mate, 10.0F, 30.0F); if (tick % 50 == 0) { cat.generateRandomParticles(EnumParticleTypes.HEART); } // System.out.println("EntityAIFatCatMate(updateTask): tick="+tick); if (this.cat.getDistanceSqToEntity(this.mate) > 2.25D) { this.cat.getNavigator().tryMoveToEntityLiving(this.mate, 0.25D); } else if (this.matingTimeout == 0 && this.mate.isMating) { this.giveBirth(); } this.tick++; } private boolean checkSufficientMating(EntityFatCat cat) { // System.out.println("EntityAIFatCatMate(checkSufficientMating): weight="+cat.getWeight()+",loveness="+cat.getLoveness()); return (cat != null) && (!cat.isChild()) && (cat.getLoveness() >= EntityFatCat.LOVENESS_MAX); } private void giveBirth() { // System.out.println("EntityAIFatCatMate(shouldExecute): getBirth"); EntityFatCat child = this.cat.createChild(this.mate); child.setLocationAndAngles(this.cat.posX, this.cat.posY, this.cat.posZ, 0.0F, 0.0F); worldObj.spawnEntityInWorld(child); cat.setLoveness(0, StatusChangeReason.Spawn); mate.setLoveness(0, StatusChangeReason.Spawn); } }
29.589744
171
0.635471
b792093e1d7010f06bd150f41c9f7057f880da72
2,149
package ltd.chuchen; import ltd.chuchen.mapper.UserMapper; import ltd.chuchen.service.UserService; import ltd.chuchen.service.impl.DashboardServiceImpl; import ltd.chuchen.service.impl.RecordServiceImpl; import ltd.chuchen.utils.EmailUtil; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.util.List; import java.util.Map; @SpringBootTest class BlogApiApplicationTests { @Autowired private UserMapper userMapper; @Autowired private UserService userService; @Autowired private JavaMailSenderImpl mailSender; @Autowired private DashboardServiceImpl dashboardService; @Test void contextLoads() { int i = userMapper.deleteById(1504321767206895617L); } @Test public void testSelect(){ BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); System.out.println(passwordEncoder.encode("Kfb200004195013")); } @Test void contextLoads2() throws MessagingException { //一个复杂的邮件 MimeMessage mimeMessage = mailSender.createMimeMessage(); //组装 MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true); helper.setSubject("小初晨"); helper.setText("<p style='color: red'>谢谢你</p>",true); //附件 // helper.addAttachment("1.png",new File("F:\\Users\\Administrator\\Desktop\\1.png")); // helper.addAttachment("2.pjg",new File("F:\\Users\\Administrator\\Desktop\\1.png")); helper.setTo("2665300871@qq.com"); helper.setFrom("2665300871@qq.com"); mailSender.send(mimeMessage); } @Test void contextLoads3() { Map<String, List> categoryBlogCountMap = dashboardService.getCategoryBlogCountMap(); System.out.println(categoryBlogCountMap); } }
32.560606
93
0.731038
3ae5d212246b5650456381176966ae1c0351abd1
2,927
package frc.robot.lib; import static frc.robot.lib.PoseHelper.*; import static org.junit.jupiter.api.Assertions.assertEquals; import edu.wpi.first.math.geometry.Pose2d; import org.junit.jupiter.api.Test; /** * Test the PoseHelper class. * * To run just this test, use: * ./gradlew test --tests "frc.robot.lib.TestPoseHelper" */ public class TestPoseHelper { Pose2d zero = createPose2d(0, 0, 0); Pose2d pose = createPose2d(-10, 10, 150); @Test public void testZero() { assertEquals(approachPose(zero, 0, 0), createPose2d(0, 0, 0)); } @Test public void testPositiveDistances() { assertEquals(approachPose(zero, 2, 0), createPose2d(2, 0, 0)); assertEquals(approachPose(pose, 19.5, 0), createPose2d(9.5, 10, 0)); } @Test public void testNegativeDistances() { assertEquals(approachPose(zero, -2, 0), createPose2d(-2, 0, 0)); assertEquals(approachPose(pose, -19.5, 0), createPose2d(-29.5, 10, 0)); } @Test public void testAngles() { double dist = 5.0; // Testing 0, 90, 180, 270, 360 assertEquals(approachPose(pose, dist, 0), createPose2d(-10 + dist, 10, 0)); assertEquals(approachPose(pose, dist, 90), createPose2d(-10, 10 + dist, 90)); assertEquals(approachPose(pose, dist, 180), createPose2d(-10 - dist, 10, 180)); assertEquals(approachPose(pose, dist, 270), createPose2d(-10, 10 - dist, 270)); assertEquals(approachPose(pose, dist, 360), createPose2d(-10 + dist, 10, 360)); } @Test public void testWeirderAngles() { double dist = 5.0; assertEquals(approachPose(zero, dist, -90), createPose2d(0, -dist, -90)); assertEquals(approachPose(zero, dist, 450), createPose2d(0, dist, 450)); assertEquals(approachPose(zero, dist, 30), createPose2d(dist * Math.sqrt(3) / 2, dist / 2, 30)); assertEquals(approachPose(pose, 0, 275), createPose2d(-10, 10, 275)); assertEquals(approachPose(pose, -41.5, 300), createPose2d(-10 + -41.5 / 2, 10 - -41.5 * Math.sqrt(3) / 2, 300)); } @Test public void testPoses() { Pose2d firstQuadrant = createPose2d(7, 13, 125); assertEquals(approachPose(firstQuadrant, -3, 45), createPose2d(7 - 3.0 / Math.sqrt(2), 13 - 3.0 / Math.sqrt(2), 45)); Pose2d secondQuadrant = createPose2d(-11, 8, 339); assertEquals(approachPose(secondQuadrant, -3, 0), createPose2d(-11 - 3, 8, 0)); Pose2d thirdQuadrant = createPose2d(-13, -198.4, 0); assertEquals(approachPose(thirdQuadrant, -3, 30), createPose2d(-13 - 3.0 * Math.sqrt(3) / 2, -198.4 - 3.0 / 2, 30)); Pose2d fourthQuadrant = createPose2d(17, -2, 150); assertEquals(approachPose(fourthQuadrant, -3, -30), createPose2d(17 - 3.0 * Math.sqrt(3) / 2, -2 + 3.0 / 2, -30)); } }
34.034884
87
0.611548
729d89bcbe65401edcf2b7cda2a292f687f23e2b
3,331
package jetbrains.mps.ide.make.actions; /*Generated by MPS */ import jetbrains.mps.workbench.action.BaseAction; import javax.swing.Icon; import jetbrains.mps.smodel.language.LanguageAspectDescriptor; import org.jetbrains.annotations.NotNull; import com.intellij.openapi.actionSystem.AnActionEvent; import java.util.Map; import jetbrains.mps.util.NameUtil; import jetbrains.mps.project.MPSProject; import jetbrains.mps.ide.actions.MPSCommonDataKeys; import jetbrains.mps.baseLanguage.closures.runtime.Wrappers; import java.util.List; import org.jetbrains.mps.openapi.model.SModel; import jetbrains.mps.smodel.Language; import jetbrains.mps.internal.collections.runtime.ListSequence; import org.jetbrains.mps.openapi.module.SModule; import jetbrains.mps.internal.collections.runtime.ITranslator2; import jetbrains.mps.internal.collections.runtime.IWhereFilter; import jetbrains.mps.generator.GenerationFacade; public class BuildAspect_Action extends BaseAction { private static final Icon ICON = null; private LanguageAspectDescriptor aspect; public BuildAspect_Action(LanguageAspectDescriptor aspect_par) { super("Rebuild All Aspect", "", ICON); this.aspect = aspect_par; this.setIsAlwaysVisible(false); this.setExecuteOutsideCommand(true); } @Override public boolean isDumbAware() { return true; } @Override public void doUpdate(@NotNull AnActionEvent event, final Map<String, Object> _params) { event.getPresentation().setText(NameUtil.capitalize(BuildAspect_Action.this.aspect.getPresentableAspectName())); } @Override protected boolean collectActionData(AnActionEvent event, final Map<String, Object> _params) { if (!(super.collectActionData(event, _params))) { return false; } { MPSProject p = event.getData(MPSCommonDataKeys.MPS_PROJECT); if (p == null) { return false; } } return true; } @Override public void doExecute(@NotNull final AnActionEvent event, final Map<String, Object> _params) { final Wrappers._T<List<SModel>> models = new Wrappers._T<List<SModel>>(); event.getData(MPSCommonDataKeys.MPS_PROJECT).getModelAccess().runReadAction(() -> { List<Language> projectModules = ListSequence.fromList(((List<SModule>) event.getData(MPSCommonDataKeys.MPS_PROJECT).getProjectModules())).ofType(Language.class).toListSequence(); models.value = ListSequence.fromList(projectModules).translate(new ITranslator2<Language, SModel>() { public Iterable<SModel> translate(Language it) { return BuildAspect_Action.this.aspect.getAspectModels(it); } }).where(new IWhereFilter<SModel>() { public boolean accept(SModel it) { return GenerationFacade.canGenerate(it); } }).toListSequence(); }); new MakeActionImpl(new MakeActionParameters(event.getData(MPSCommonDataKeys.MPS_PROJECT)).models(models.value).cleanMake(true)).executeAction(); } @NotNull public String getActionId() { StringBuilder res = new StringBuilder(); res.append(super.getActionId()); res.append("#"); res.append(aspect_State((LanguageAspectDescriptor) this.aspect)); res.append("!"); return res.toString(); } public static String aspect_State(LanguageAspectDescriptor object) { return object.getPresentableAspectName(); } }
39.188235
184
0.750225
43315d7fbdba36c53134adf52b9502a43bbbe626
945
package com.medallia.references.speechapi.publish; import org.apache.commons.lang3.StringUtils; import com.medallia.references.speechapi.publish.SpeechRecordMetadata.BooleanString; import com.opencsv.bean.AbstractBeanField; import com.opencsv.exceptions.CsvConstraintViolationException; import com.opencsv.exceptions.CsvDataTypeMismatchException; public class StringToBooleanConverter extends AbstractBeanField<String, BooleanString> { @Override protected Object convert( final String s ) throws CsvDataTypeMismatchException, CsvConstraintViolationException { if (StringUtils.isBlank(s)) { return null; } for (BooleanString b : BooleanString.values()) { if (b.getDisplayName().equalsIgnoreCase(s)) { return b; } } throw new CsvDataTypeMismatchException(s, BooleanString.class, "Value did not match expectations"); } }
31.5
107
0.721693
5429a0f5b64a852a92f14f5d946fd1e3da55b1af
14,676
package ui; import com.hp.hpl.jena.rdf.model.Model; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ButtonGroup; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import org.apache.jena.riot.RDFDataMgr; import org.apache.jena.riot.RiotException; import src.Utilities; public class JDialogCodificacion extends javax.swing.JDialog { File file; public JDialogCodificacion(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); buttonGroup2 = new javax.swing.ButtonGroup(); jPanel2 = new javax.swing.JPanel(); jRadioButton4 = new javax.swing.JRadioButton(); jRadioButton5 = new javax.swing.JRadioButton(); jRadioButton6 = new javax.swing.JRadioButton(); jRadioButton8 = new javax.swing.JRadioButton(); jRadioButton10 = new javax.swing.JRadioButton(); jTextFieldOutputName = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jButtonChooseFile = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jButtonConvert = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Output sintax")); buttonGroup2.add(jRadioButton4); jRadioButton4.setText("Turtle"); buttonGroup2.add(jRadioButton5); jRadioButton5.setText("N3"); buttonGroup2.add(jRadioButton6); jRadioButton6.setText("RDF/XML"); buttonGroup2.add(jRadioButton8); jRadioButton8.setText("RDF/JSON"); buttonGroup2.add(jRadioButton10); jRadioButton10.setText("N-Triples"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton4) .addComponent(jRadioButton5) .addComponent(jRadioButton6) .addComponent(jRadioButton8) .addComponent(jRadioButton10)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jRadioButton4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButton5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButton6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButton8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButton10) .addContainerGap(52, Short.MAX_VALUE)) ); jTextFieldOutputName.setText("nuevo"); jTextFieldOutputName.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextFieldOutputNameActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jLabel1.setText("File"); jButtonChooseFile.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jButtonChooseFile.setText("Browse..."); jButtonChooseFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonChooseFileActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Dialog", 0, 12)); // NOI18N jLabel2.setText("Output name"); jButtonConvert.setText("Convert"); jButtonConvert.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonConvertActionPerformed(evt); } }); jTextField1.setEditable(false); jTextField1.setBackground(new java.awt.Color(255, 255, 255)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldOutputName, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(328, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(94, 94, 94) .addComponent(jTextField1) .addGap(18, 18, 18) .addComponent(jButtonChooseFile) .addContainerGap()))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonConvert) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jButtonChooseFile) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextFieldOutputName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(13, 13, 13) .addComponent(jButtonConvert) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextFieldOutputNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldOutputNameActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextFieldOutputNameActionPerformed private void jButtonChooseFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonChooseFileActionPerformed JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { this.file = fc.getSelectedFile(); //new File(filename); this.jTextField1.setText(file.getAbsolutePath()); } }//GEN-LAST:event_jButtonChooseFileActionPerformed private void jButtonConvertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConvertActionPerformed JRadioButton finalSintax = getSelection(this.buttonGroup2); String path = file.getParent(); String outputFilePath = path + "/" + this.jTextFieldOutputName.getText() + getExtension(finalSintax.getText()); System.out.println("input: " + this.file.getAbsolutePath()); System.out.println("output: " + outputFilePath); System.out.println("syntax: " + finalSintax.getText()); Model model = null; try { model = RDFDataMgr.loadModel(this.file.getAbsolutePath()); } catch (RiotException ex){ JOptionPane.showMessageDialog(this, "Content and extension are not compatible", "Invalid file", JOptionPane.ERROR_MESSAGE); } if (model != null) { try { FileWriter out = new FileWriter(outputFilePath); model.write(out, finalSintax.getText()); JOptionPane.showMessageDialog(this, "File saved in "+outputFilePath, "", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { Logger.getLogger(JDialogCodificacion.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jButtonConvertActionPerformed // Return the selected button in a buttongroup public JRadioButton getSelection(ButtonGroup group) { for (Enumeration e=group.getElements(); e.hasMoreElements(); ) { JRadioButton b = (JRadioButton)e.nextElement(); if (b.getModel() == group.getSelection()) { return b; } } return null; } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(JDialogCodificacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JDialogCodificacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JDialogCodificacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JDialogCodificacion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JDialogCodificacion dialog = new JDialogCodificacion(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.ButtonGroup buttonGroup2; private javax.swing.JButton jButtonChooseFile; private javax.swing.JButton jButtonConvert; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel2; private javax.swing.JRadioButton jRadioButton10; private javax.swing.JRadioButton jRadioButton4; private javax.swing.JRadioButton jRadioButton5; private javax.swing.JRadioButton jRadioButton6; private javax.swing.JRadioButton jRadioButton8; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextFieldOutputName; // End of variables declaration//GEN-END:variables private String getExtension(String text) { switch (text){ case "Turtle": return Utilities.TURTLE_EXTENSION; case "N-Triples": return Utilities.NTRIPLES_EXTENSION; case "RDF/XML": return Utilities.RDF_XML_EXTENSION; case "RDF/JSON": return Utilities.RDF_JSON_EXTENSION; default: return ""; } } }
46.00627
174
0.641047
55232d5ea6a00cbbe816754e4d941c8975891a6d
3,522
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.analyticsadmin.v1alpha.model; /** * Data specific to Android app streams. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Google Analytics Admin API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleAnalyticsAdminV1alphaDataStreamAndroidAppStreamData extends com.google.api.client.json.GenericJson { /** * Output only. ID of the corresponding Android app in Firebase, if any. This ID can change if the * Android app is deleted and recreated. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String firebaseAppId; /** * Immutable. The package name for the app being measured. Example: "com.example.myandroidapp" * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String packageName; /** * Output only. ID of the corresponding Android app in Firebase, if any. This ID can change if the * Android app is deleted and recreated. * @return value or {@code null} for none */ public java.lang.String getFirebaseAppId() { return firebaseAppId; } /** * Output only. ID of the corresponding Android app in Firebase, if any. This ID can change if the * Android app is deleted and recreated. * @param firebaseAppId firebaseAppId or {@code null} for none */ public GoogleAnalyticsAdminV1alphaDataStreamAndroidAppStreamData setFirebaseAppId(java.lang.String firebaseAppId) { this.firebaseAppId = firebaseAppId; return this; } /** * Immutable. The package name for the app being measured. Example: "com.example.myandroidapp" * @return value or {@code null} for none */ public java.lang.String getPackageName() { return packageName; } /** * Immutable. The package name for the app being measured. Example: "com.example.myandroidapp" * @param packageName packageName or {@code null} for none */ public GoogleAnalyticsAdminV1alphaDataStreamAndroidAppStreamData setPackageName(java.lang.String packageName) { this.packageName = packageName; return this; } @Override public GoogleAnalyticsAdminV1alphaDataStreamAndroidAppStreamData set(String fieldName, Object value) { return (GoogleAnalyticsAdminV1alphaDataStreamAndroidAppStreamData) super.set(fieldName, value); } @Override public GoogleAnalyticsAdminV1alphaDataStreamAndroidAppStreamData clone() { return (GoogleAnalyticsAdminV1alphaDataStreamAndroidAppStreamData) super.clone(); } }
37.073684
182
0.743612
eb89efdfdaa5a073a2db93c33fd3b7d122641d37
11,813
package com.github.giulioscattolin.rinex; import java.util.function.Function; import java.util.function.Supplier; import static java.lang.Double.isNaN; @Deprecated public class RinexFileParser { private final RinexFileCollector itsFileCollector; RinexNavigationDataBuilder itsNavigationMessageBuilder; private LineReader itsLineReader = new VersionType(); private Supplier<LineReader> itsLineReaderSupplier; private MutableRinexFile itsMutableRinexFile = new MutableRinexFile(); public RinexFileParser(RinexFileCollector fileCollector) { itsFileCollector = fileCollector; } public void readLine(String line) { itsLineReader.readLine(line); } public void flush() { itsFileCollector.collect(itsMutableRinexFile); } class VersionType extends LineReader { protected void execute() { if (isHeader("RINEX VERSION / TYPE")) parseLine(); } private void parseLine() { String version = itsLine.substring(0, 9).trim(); char fileType = itsLine.charAt(20); char satelliteSystem = itsLine.charAt(40); switch (version) { case "2": addVersionTypeHeader(version, fileType); switch (fileType) { case 'N': itsLineReader = new NavigationHeader(); itsLineReaderSupplier = () -> new SvEpochSvClk( new SvEpochSvClkReaderV2('G'), (ignored) -> new RinexGpsNavigationDataBuilderV2(), () -> new BroadcastOrbit(new BroadcastOrbitParameterReaderV2())); return; } case "2.10": switch (fileType) { case 'N': addVersionTypeHeader(version, fileType); itsLineReader = new NavigationHeader(); itsLineReaderSupplier = () -> new SvEpochSvClk( new SvEpochSvClkReaderV2('G'), (ignored) -> new RinexGpsNavigationDataBuilderV210(), () -> new BroadcastOrbit(new BroadcastOrbitParameterReaderV2())); return; case 'O': addVersionTypeHeader(version, fileType, satelliteSystem); itsLineReader = new ObservationDataFileHeader(); itsLineReaderSupplier = () -> new VersionType(); return; } case "3.02": case "3.03": case "3.04": addVersionTypeHeader(version, fileType, satelliteSystem); switch (fileType) { case 'N': switch (satelliteSystem) { case 'G': itsLineReader = new NavigationHeader(); itsLineReaderSupplier = () -> new SvEpochSvClk( new SvEpochSvClkReaderV3(), (ignored) -> new RinexGpsNavigationDataBuilderV302(), () -> new BroadcastOrbit(new BroadcastOrbitParameterReaderV3())); return; case 'M': itsLineReader = new NavigationHeader(); itsLineReaderSupplier = () -> new SvEpochSvClk( new SvEpochSvClkReaderV3(), this::selectEpochReaderV3, () -> new BroadcastOrbit(new BroadcastOrbitParameterReaderV3())); return; } } } } private RinexNavigationDataBuilder selectEpochReaderV3(char satelliteSystem) { switch (satelliteSystem) { case 'G': return new RinexGpsNavigationDataBuilderV302(); default: return null; } } private void addVersionTypeHeader(String version, char fileType) { itsMutableRinexFile.addHeader(new RinexVersionTypeHeader(version, fileType)); } private void addVersionTypeHeader(String version, char fileType, char satelliteSystem) { itsMutableRinexFile.addHeader(new RinexVersionTypeHeader(version, fileType, satelliteSystem)); } } class NavigationHeader extends LineReader { protected void execute() { switch (getHeaderLabel()) { case "PGM / RUN BY / DATE": parsePgmRunByDateHeader(); return; case "END OF HEADER": itsLineReader = itsLineReaderSupplier.get(); return; } } private void parsePgmRunByDateHeader() { String program = itsLine.substring(0, 20).trim(); String agency = itsLine.substring(20, 40).trim(); String timestamp = itsLine.substring(40, 60).trim(); itsMutableRinexFile.addHeader(new RinexPgmRunByDateHeader(program, agency, timestamp)); } } class ObservationDataFileHeader extends LineReader { protected void execute() { switch (getHeaderLabel()) { case "PGM / RUN BY / DATE": parsePgmRunByDateHeader(); return; case "MARKER NAME": parseMarkerNameHeader(); return; case "OBSERVER / AGENCY": parseObserverAgencyHeader(); return; case "END OF HEADER": itsLineReader = itsLineReaderSupplier.get(); return; } } private void parsePgmRunByDateHeader() { String program = itsLine.substring(0, 20).trim(); String agency = itsLine.substring(20, 40).trim(); String timestamp = itsLine.substring(40, 60).trim(); itsMutableRinexFile.addHeader(new RinexPgmRunByDateHeader(program, agency, timestamp)); } private void parseMarkerNameHeader() { String name = itsLine.substring(0, 60).trim(); itsMutableRinexFile.addHeader(new RinexMarkerNameHeader(name)); } private void parseObserverAgencyHeader() { String observer = itsLine.substring(0, 20).trim(); String agency = itsLine.substring(20, 60).trim(); itsMutableRinexFile.addHeader(new RinexObserverAgencyHeader(observer, agency)); } } class SvEpochSvClk extends LineReader { private final SvEpochSvClkReader itsSvEpochSvClkReader; private final Function<Character, RinexNavigationDataBuilder> itsNavigationMessageBuilderSupplier; private final Supplier<LineReader> itsBroadcastOrbitReaderSupplier; SvEpochSvClk(SvEpochSvClkReader svEpochSvClkReader, Function<Character, RinexNavigationDataBuilder> navigationMessageBuilderSupplier, Supplier<LineReader> broadcastOrbitCompilerSupplier) { itsSvEpochSvClkReader = svEpochSvClkReader; itsNavigationMessageBuilderSupplier = navigationMessageBuilderSupplier; itsBroadcastOrbitReaderSupplier = broadcastOrbitCompilerSupplier; } protected void execute() { if (isHeader("RINEX VERSION / TYPE")) { new VersionType().readLine(itsLine); return; } whichSatelliteSystem(); } private void whichSatelliteSystem() { char satelliteSystem = itsSvEpochSvClkReader.getSatelliteSystem(itsLine); itsNavigationMessageBuilder = itsNavigationMessageBuilderSupplier.apply(satelliteSystem); if (itsNavigationMessageBuilder == null) return; itsLineReader = itsBroadcastOrbitReaderSupplier.get(); findPrn(); } private void findPrn() { int prn = itsSvEpochSvClkReader.getSatelliteNumberOrNegative(itsLine); if (prn < 1) return; itsNavigationMessageBuilder.setParameter(0, prn); findToc(); } private void findToc() { int year = itsSvEpochSvClkReader.getTocYearOrNegative(itsLine); int month = itsSvEpochSvClkReader.getTocMonthOrNegative(itsLine); int day = itsSvEpochSvClkReader.getTocDayOrNegative(itsLine); int hour = itsSvEpochSvClkReader.getTocHourOrNegative(itsLine); int minute = itsSvEpochSvClkReader.getTocMinuteOrNegative(itsLine); int second = itsSvEpochSvClkReader.getTocSecondOrNegative(itsLine); if (year < 0 || month < 1 || day < 1 || hour < 0 || minute < 0 || second < 0) return; itsNavigationMessageBuilder.setParameter(1, year); itsNavigationMessageBuilder.setParameter(2, month); itsNavigationMessageBuilder.setParameter(3, day); itsNavigationMessageBuilder.setParameter(4, hour); itsNavigationMessageBuilder.setParameter(5, minute); itsNavigationMessageBuilder.setParameter(6, second); findSvClock(); } private void findSvClock() { double first = itsSvEpochSvClkReader.getFirstTimeParameterOrNaN(itsLine); double second = itsSvEpochSvClkReader.getSecondTimeParameterOrNaN(itsLine); double third = itsSvEpochSvClkReader.getThirdTimeParameterOrNaN(itsLine); if (isNaN(first) || isNaN(second) || isNaN(third)) return; itsNavigationMessageBuilder.setParameter(7, first); itsNavigationMessageBuilder.setParameter(8, second); itsNavigationMessageBuilder.setParameter(9, third); } } private class BroadcastOrbit extends LineReader { private final BroadcastOrbitParameterReader itsParameterReader; private int itsIndex = 10; private boolean shouldContinue = true; private BroadcastOrbit(BroadcastOrbitParameterReader parameterReader) { itsParameterReader = parameterReader; } protected void execute() { for (int i = 0; i < 4 && shouldContinue; i++) readParameter(i); } private void readParameter(int i) { double value = itsParameterReader.getParameterOrNaN(itsLine, i); tellIfShouldContinue(value); if (shouldContinue) { itsNavigationMessageBuilder.setParameter(itsIndex++, value); collectIfBuilderIsReady(); } } private void collectIfBuilderIsReady() { if (itsNavigationMessageBuilder.isReady()) { itsMutableRinexFile.addRecord(itsNavigationMessageBuilder.build()); itsLineReader = itsLineReaderSupplier.get(); shouldContinue = false; } } private void tellIfShouldContinue(double value) { if (isNaN(value)) { itsLineReader = itsLineReaderSupplier.get(); shouldContinue = false; } } } }
42.800725
196
0.554305
bf4f5d56a92e9d1faa6b12fffafb6d43da9473d3
3,069
/* * Copyright 2017 Jett Marks * * 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. * * Created by jett on 8/13/17. */ package com.clueride.domain.account.member; import java.io.IOException; import java.util.List; import javax.annotation.Nonnull; import javax.inject.Inject; import javax.mail.internet.InternetAddress; import javax.persistence.EntityManager; import com.clueride.infrastructure.db.ClueRide; import static java.util.Objects.requireNonNull; /** * JPA Implementation of the MemberStore (DAO) interface. */ public class MemberStoreJpa implements MemberStore { private final EntityManager entityManager; @Inject public MemberStoreJpa( @Nonnull @ClueRide EntityManager entityManager ) { this.entityManager = requireNonNull(entityManager); } @Override public Integer addNew(Member member) throws IOException { entityManager.getTransaction().begin(); entityManager.persist(Member.Builder.from(member)); entityManager.getTransaction().commit(); return member.getId(); } @Override public Member getMemberById(Integer id) { entityManager.getTransaction().begin(); Member.Builder memberBuilder = entityManager.find(Member.Builder.class, id); entityManager.getTransaction().commit(); return memberBuilder.build(); } @Override public List<Member> getMemberByName(String name) { return null; } @Override public Member getMemberByEmail(InternetAddress emailAddress) { Member.Builder memberBuilder; try { entityManager.getTransaction().begin(); memberBuilder = entityManager .createQuery( "from member m where m.emailAddress = :emailAddress", Member.Builder.class ) .setParameter("emailAddress", emailAddress.toString()) .getSingleResult(); entityManager.getTransaction().commit(); } catch (Exception e) { entityManager.getTransaction().rollback(); throw e; } return memberBuilder.build(); } @Override public void update(Member member) { } @Override public List<Member.Builder> getAllMembers() { entityManager.getTransaction().begin(); List<Member.Builder> builders = entityManager.createQuery("SELECT m FROM member m").getResultList(); entityManager.getTransaction().commit(); return builders; } }
31.316327
108
0.666993
2543737233591315e8a528892569b334dddb0d76
1,898
/* * Copyright 2015-2017 GenerallyCloud.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.generallycloud.baseio.codec.protobase; import java.io.IOException; import com.generallycloud.baseio.buffer.ByteBuf; import com.generallycloud.baseio.buffer.ByteBufAllocator; import com.generallycloud.baseio.codec.protobase.future.ParamedProtobaseFutureImpl; import com.generallycloud.baseio.component.SocketChannel; import com.generallycloud.baseio.protocol.ChannelFuture; import com.generallycloud.baseio.protocol.ProtocolDecoder; /** * <pre> * * B0 :0-1 : 报文类型 0=UNKONW 1=NORMAL 2=PING 3=PONG * B0 :2 : 推送类型 0=PUSH 1=BRODCAST * B0 :3 : 是否包含FutureId 4 byte * B0 :4 : 是否包含SessionId 4 byte * B0 :5 : 是否包含HashId 4 byte * B0 :6 : 是否包含Binary 4 byte * B0 :7 : 预留 * B1 : 预留 * B2-B3 : future name * B4-B7 :text length * * </pre> */ public class ParamedProtobaseProtocolDecoder implements ProtocolDecoder { protected int limit; public ParamedProtobaseProtocolDecoder(int limit) { this.limit = limit; } @Override public ChannelFuture decode(SocketChannel channel, ByteBuf buffer) throws IOException { ByteBufAllocator allocator = channel.getByteBufAllocator(); ByteBuf buf = allocator.allocate(2); return new ParamedProtobaseFutureImpl(channel, buf); } }
32.169492
91
0.717071
492b38476f950b9051479c30b6418fa59f4b4fc2
6,312
package tkohdk.lib.calcstr.tokenizer; import tkohdk.lib.calcstr.checker.BigDecimalNumericChecker; import tkohdk.lib.calcstr.checker.FunctionChecker; import tkohdk.lib.calcstr.checker.OperatorChecker; import tkohdk.lib.calcstr.splitter.StringSplitter; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.assertEquals; /** * Created by takeoh on 2017/11/15. */ public class StringListTokenizerTest { /** * * @param temp * @return */ ArrayList<String> getStrList(ArrayList<TokenElement> temp) { ArrayList<String> strList = new ArrayList<>(); for(int i = 0; i < temp.size(); i++){ strList.add(temp.get(i).getRawStr()); } return strList; } @Test public void getProblemStrObjListFromStr() throws Exception { StringListTokenizer tokenizer = new StringListTokenizer( new StringTokenizer(new StringSplitter()), new TokenValueChecker(new BigDecimalNumericChecker(), new FunctionChecker(), new OperatorChecker()) ); ArrayList<TokenElement> temp = tokenizer.getList("1 * (2 + 3) "); ArrayList<String> l1 = new ArrayList<>(); for(int i = 0; i < temp.size(); i++){ l1.add(temp.get(i).getRawStr()); } ArrayList<String> e1 = new ArrayList<>(); e1.add("1"); e1.add("*"); e1.add("("); e1.add("2"); e1.add("+"); e1.add("3"); e1.add(")"); assertEquals(e1, l1); temp = tokenizer.getList("(1 + 2) * (2 + 3) "); l1 = this.getStrList(temp); ArrayList<String> e2 = new ArrayList<>(); e2.add("("); e2.add("1"); e2.add("+"); e2.add("2"); e2.add(")"); e2.add("*"); e2.add("("); e2.add("2"); e2.add("+"); e2.add("3"); e2.add(")"); assertEquals(e2, l1); temp = tokenizer.getList("(1 + 2) * (2 + 3) + 0.789"); l1 = this.getStrList(temp); ArrayList<String> e3 = new ArrayList<>(); e3.add("("); e3.add("1"); e3.add("+"); e3.add("2"); e3.add(")"); e3.add("*"); e3.add("("); e3.add("2"); e3.add("+"); e3.add("3"); e3.add(")"); e3.add("+"); e3.add("0.789"); assertEquals(e3, l1); temp = tokenizer.getList("-2(-2 - 1)-1-(-2)"); l1 = this.getStrList(temp); ArrayList<String> e4 = new ArrayList<>(); e4.add("-2"); e4.add("*"); e4.add("("); e4.add("-2"); e4.add("-"); e4.add("1"); e4.add(")"); e4.add("-"); e4.add("1"); e4.add("-"); e4.add("("); e4.add("-2"); e4.add(")"); assertEquals(e4, l1); /* N! の表記も対応してみたいので分割できるようにしておく */ temp = tokenizer.getList("3! + 4!"); l1 = this.getStrList(temp); ArrayList<String> e5 = new ArrayList<>(); e5.add("3"); e5.add("!"); e5.add("+"); e5.add("4"); e5.add("!"); assertEquals(e5, l1); temp = tokenizer.getList("1 - - 1"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("1"); e5.add("-"); e5.add("-1"); assertEquals(e5, l1); temp = tokenizer.getList("-3"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("-3"); assertEquals(e5, l1); // 2 * -2 temp = tokenizer.getList("2*-2"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("2"); e5.add("*"); e5.add("-2"); assertEquals(e5, l1); // 2 / -2 temp = tokenizer.getList("2/-2"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("2"); e5.add("/"); e5.add("-2"); assertEquals(e5, l1); // 1.23.4 temp = tokenizer.getList("1.23.4"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("1.23"); e5.add("*"); e5.add(".4"); assertEquals(e5, l1); // 1.23.4 temp = tokenizer.getList(".123"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add(".123"); assertEquals(e5, l1); // 1.23.4 temp = tokenizer.getList(".1.23.4"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add(".1"); e5.add("*"); e5.add(".23"); e5.add("*"); e5.add(".4"); assertEquals(e5, l1); /* +3は、正規表現で-3と同じように+3として取り出すこともできるが 最終的には"+"を取り除くことを考えると別々の要素とした方がよいと判断した。 */ temp = tokenizer.getList("+3"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("+"); e5.add("3"); assertEquals(e5, l1); temp = tokenizer.getList("tan(3)"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("tan"); e5.add("("); e5.add("3"); e5.add(")"); assertEquals(e5, l1); temp = tokenizer.getList("1 + tan(3)"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("1"); e5.add("+"); e5.add("tan"); e5.add("("); e5.add("3"); e5.add(")"); assertEquals(e5, l1); temp = tokenizer.getList("1 - tan(3)"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("1"); e5.add("-"); e5.add("tan"); e5.add("("); e5.add("3"); e5.add(")"); assertEquals(e5, l1); temp = tokenizer.getList("1 * tan(3)"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("1"); e5.add("*"); e5.add("tan"); e5.add("("); e5.add("3"); e5.add(")"); assertEquals(e5, l1); temp = tokenizer.getList("3 / tan(3)"); l1 = this.getStrList(temp); e5 = new ArrayList<>(); e5.add("3"); e5.add("/"); e5.add("tan"); e5.add("("); e5.add("3"); e5.add(")"); assertEquals(e5, l1); } }
24
115
0.454056
e604c63ad6d4db580f7ca13046ce73526953b221
4,807
/* * Copyright 2018 YitanTribal & Beelzebu * * 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 cl.mastercode.DamageIndicator.util; import cl.mastercode.DamageIndicator.DIMain; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.attribute.Attribute; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; /** * Class to manage compatibility with older minecraft versions. * * @author Beelzebu */ public final class CompatUtil { public static ItemStack RED_INK = null; public static int MINOR_VERSION = 8; public static void onEnable() { MINOR_VERSION = _getMinorVersion(); if (MINOR_VERSION >= 13) { if (MINOR_VERSION == 13) { RED_INK = new ItemStack(Material.valueOf("ROSE_RED")); } else { RED_INK = new ItemStack(Material.RED_DYE); } } else { RED_INK = new ItemStack(Material.valueOf("INK_SACK"), 1, (short) 1); } } public static boolean isCanSetCollidable() { return MINOR_VERSION > 8; } public static boolean is113orHigher() { return _getMinorVersion() > 13; } public static double getMaxHealth(LivingEntity livingEntity) { if (MINOR_VERSION > 8) { return livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue(); } return livingEntity.getMaxHealth(); } private static int _getMinorVersion() { String ver = Bukkit.getServer().getClass().getPackage().getName().substring(Bukkit.getServer().getClass().getPackage().getName().lastIndexOf(".") + 1); int verInt = -1; try { verInt = Integer.parseInt(ver.split("_")[1]); } catch (IllegalArgumentException e) { Bukkit.getScheduler().runTask(DIMain.getPlugin(DIMain.class), () -> { DIMain.getPlugin(DIMain.class).getLogger().warning("An error occurred getting server version, please contact developer."); DIMain.getPlugin(DIMain.class).getLogger().warning("Detected version " + ver); Bukkit.getPluginManager().disablePlugin(DIMain.getPlugin(DIMain.class)); }); } return verInt; } public static ArmorStand buildArmorStand(Location location, double distance, FixedMetadataValue fixedMetadataValue, String name) { ArmorStand armorStand; if (MINOR_VERSION >= 11) { armorStand = modernEntitySpawn(location, distance, fixedMetadataValue); } else { armorStand = legacyEntitySpawn(location, distance, fixedMetadataValue); } armorStand.setCustomName(name); armorStand.setCustomNameVisible(true); return armorStand; } private static ArmorStand modernEntitySpawn(Location location, double distance, FixedMetadataValue fixedMetadataValue) { return location.getWorld().spawn(location.clone().add(0, location.getWorld().getMaxHeight() - location.getY(), 0), ArmorStand.class, stand -> setStandProperties(stand, location, distance, fixedMetadataValue)); } private static ArmorStand legacyEntitySpawn(Location location, double distance, FixedMetadataValue fixedMetadataValue) { ArmorStand armorStand = (ArmorStand) location.getWorld().spawnEntity(location, EntityType.ARMOR_STAND); setStandProperties(armorStand, location, distance, fixedMetadataValue); return armorStand; } private static void setStandProperties(ArmorStand armorStand, Location location, double distance, FixedMetadataValue fixedMetadataValue) { armorStand.setVisible(false); armorStand.setGravity(false); armorStand.setMarker(true); armorStand.setSmall(true); armorStand.setCustomNameVisible(false); armorStand.setMetadata("Mastercode-DamageIndicator", fixedMetadataValue); if (CompatUtil.isCanSetCollidable()) { armorStand.setCollidable(false); armorStand.setInvulnerable(true); } armorStand.teleport(location.clone().add(0, distance, 0)); armorStand.setRemoveWhenFarAway(true); } }
40.394958
217
0.689619
ec0b0900d1d00703d7e9e4fc048f970013fc767e
111
package com.zuehlke.carrera.javapilot.akka.actors; public interface LazyCreator<T> { public T create(); }
18.5
50
0.747748
bae4bd71771fc07010a6f9de28c6ea4bb5d90688
4,074
package Pistas; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import Usuarios.DAOUsuarios; import Usuarios.DAOUsuariosImp; import transfer.TipoOrdenacion; import transfer.TransferPista; import transfer.TransferUsuario; public class SAPistasImp implements SAPistas{ private DAOPistas daoPistas; /** * @Descripcion Constructor de la clase, asigna el DAOPistas; */ public SAPistasImp() { this.daoPistas = new DAOPistasImp(); } /** * @param filtro: contiene el filtro de busqueda (en el inicio es TipoOrdenacion.NINGUNO) * @param busqueda: contiene el texto a buscar (en el inicio es vacio "") * @return Devuelve la lista obtenida segun el filtro y busqueda recibidos. * @Descripcion Transforma en string el filtro recibido, llama al dao para obtener la lista de pistas, la ordena por deporte, * por último devuelve la lista. */ public List<TransferPista> consultarListaPistas(TipoOrdenacion filtro, String busqueda) { //Declaracion. List<TransferPista> lista; String filBusqueda; //Inicializacion lista= new ArrayList <TransferPista>(); filBusqueda = filtrarLista(filtro); try { lista = this.daoPistas.getListaPistas(filBusqueda, busqueda); lista = this.ordenarListaPistas(TipoOrdenacion.DEPORTE, lista); } catch (ClassNotFoundException e) {} catch (SQLException e){} return lista; } private String filtrarLista(TipoOrdenacion filtro) { String busqueda; switch (filtro) { case PISTA: busqueda = "Numero_pista"; break; case DEPORTE: busqueda = "Tipo"; break; case ID: busqueda = "ID"; break; default: busqueda = "*"; break; } return busqueda; } /** * @param pista: contiene la pista a eliminar. * @Descripcion Llama al dao para que elimine de la BBDD la pista recibida. */ public void eliminarPista(TransferPista pista) { try { this.daoPistas.deletePista(pista); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } /** * @param pista: contiene la pista que se quiere agregar. * @Descripcion Llama al dao para que agregue la pista recibida. */ public void agregarPista(TransferPista pista) { try { this.daoPistas.setPista(pista); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } /** * @param filtro: contiene el tipo de ordenacion seleccionado * @param lista: contiene la lista a ordenar. * @return Devuelve la lista ordenada segun el filtro recibido. * @Descripcion elige según el filtro recibido a cual de las funciones de ordenación privadas llama; finalmente devuelve * la lista ordenada. */ public List<TransferPista> ordenarListaPistas(TipoOrdenacion filtro, List<TransferPista> lista) { switch (filtro) { case PISTA: lista = ordenarPorPista(lista); break; case DEPORTE: lista = ordenarPorDeporte(lista); break; } return lista; } private List<TransferPista> ordenarPorDeporte(List<TransferPista> lista) { //Declaracion. boolean inter; int i; //Inicializacion. inter = true; i = 0; while ((i < lista.size()-1) && inter) { inter = false; for (int j = lista.size() - 1; j > i; j--) { if (lista.get(j).getTipo().toString().compareTo(lista.get(j-1).getTipo().toString()) < 0) { TransferPista tmp; tmp = lista.get(j); lista.set(j, lista.get(j-1)); lista.set(j-1, tmp); inter = true; } } if (inter) { i++; } } return lista; } private List<TransferPista> ordenarPorPista(List<TransferPista> lista) { //Declaracion. boolean inter; int i; //Inicializacion. inter = true; i = 0; while ((i < lista.size() - 1) && inter) { inter = false; for (int j = lista.size() - 1; j > i; j--) { if (lista.get(j).getNumPista() < lista.get(j-1).getNumPista()) { TransferPista tmp; tmp = lista.get(j); lista.set(j, lista.get(j-1)); lista.set(j-1, tmp); inter = true; } } if (inter) { i++; } } return lista; } }
22.88764
126
0.666176
3871c66fb903ff09c40112070f8abeb2f5aa9a42
1,089
package com.runtimeverification.rvmonitor.java.rvj.output.codedom; import com.runtimeverification.rvmonitor.java.rvj.output.codedom.analysis.ICodeVisitor; import com.runtimeverification.rvmonitor.java.rvj.output.codedom.helper.ICodeFormatter; /** * This class represents a 'return' statement; e.g., <code> * return 1; * </code> The returned value can be nothing because a void method does not have * any return value. * * @author Choonghwan Lee <clee83@illinois.edu> */ public class CodeReturnStmt extends CodeStmt { private final CodeExpr retval; public CodeReturnStmt() { this(null); } public CodeReturnStmt(CodeExpr retval) { this.retval = retval; } @Override public void getCode(ICodeFormatter fmt) { fmt.keyword("return"); if (this.retval != null) this.retval.getCode(fmt); } @Override public void accept(ICodeVisitor visitor) { if (this.retval != null) this.retval.accept(visitor); } @Override public boolean isBlock() { return false; } }
25.325581
87
0.67034
a64287c7de15624f98ac9746e214cfab0878bc63
3,559
package com.autoreason.setfileconverter; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; import java.util.Hashtable; import java.util.Set; /** * Store a {@link Set} of arbitrary elements as a line in a text file by * assigning an unique {@link int} ID to each set element, such that the set can * be represented by a {@link String} that contains these IDs separated by space * */ public class SetFileConverter { // current number that can be used as unique ID for an object static int currentNr = 0; // hash table to store IDs for objects static Hashtable<Object, Integer> hashtable = new Hashtable<Object, Integer>(); /** * Write a {@link Collection} to a given file by representing its contained * {@link Set} elements as {@link String} objects * @param <C> * * @param col A {@link Collection} of {@link Set} objects * @param file A {@link String} that defines the path to the file where the * transformed collection is stored */ public static <C> void writeCollectionToFile(Collection<Set<C>> col, String file) { try { // create writer FileWriter writer = new FileWriter(file, true); BufferedWriter buffWriter = new BufferedWriter(writer); // write each set to collection for (Set<C> set : col) { // convert set to string containing its elements' IDs String setIDs = setToString(set); // write string to file buffWriter.write(setIDs); buffWriter.newLine(); } buffWriter.newLine(); buffWriter.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Represent a {@link Set} by a {@link String} that contains a unique ID of each * set element, separated by space, and write this string as new line to a named * file * * @param set A {@link Set} * @param file A {@link String} that defines the path to the file where the * created set-string is stored */ public static void writeSetToFile(Set<?> set, String file) { try { // create writer FileWriter writer = new FileWriter(file, true); BufferedWriter buffWriter = new BufferedWriter(writer); // convert set to string containing its elements' IDs String setIDs = setToString(set); // write string to file buffWriter.write(setIDs); buffWriter.newLine(); buffWriter.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Create a {@link String} that contains the IDs of each element, separated by * space, from the given {@link Set} * * @param set A {@link Set} * @return A {@link String} of {@link int} values separated by space */ static String setToString(Set<?> set) { StringBuilder str = new StringBuilder(); // go through elements of set for (Object o : set) { // add ID of element to string str.append(getID(o) + " "); } return str.toString(); } /** * Get the ID of an object * * @param o An object * @return An {@code int} value that serves as unique identifier for the object * {@code o} */ static int getID(Object o) { // look for ID number in hash table Integer id = hashtable.get(o); if (id == null) { // use current number as ID for object id = currentNr; // store ID in hash table hashtable.put(o, id); // update current number currentNr++; } return id; } /** * Reset the hash table. Can be used to process a new collection of sets. */ public static void reset() { SetFileConverter.hashtable.clear(); SetFileConverter.currentNr = 0; } }
27.589147
84
0.66957
9b460b324416d005a90b805ebce25e3956bc59d4
4,744
package edu.isi.bmkeg.sciDT.bin; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; /** * This script runs the sciDP neural net classifier on a set of files * (we will need to set up the input and output of the data for this): * * Supposed to run this with Anaconda to include all the correct paths and data points. * * python /usr1/shared/projects/bigmech/tools/sciDP/nn_passage_tagger.py * /usr1/shared/projects/bigmech/data/embeddings/pyysalo_et_al/wikipedia-pubmed-and-PMC-w2v.txt.gz * --use_attention * --test_files 15550174_scidp.txt 20179705_scidp.txt 20333297_scidp.txt * 23392125_scidp.txt 23706742_scidp.txt 24467442_scidp.txt * 24602610_scidp.txt 25449683_scidp.txt 26816343_scidp.txt * * @author Gully * */ public class SciDT_05_runSciDT { public static class Options { @Option(name = "-inDir", usage = "Input Directory", required = true, metaVar = "INPUT") public File inDir; @Option(name = "-trainPath", usage = "Path to the training files", required = true, metaVar = "TRAIN") public File trainPath; @Option(name = "-nnTaggerPath", usage = "Path to the nn_passage_tagger script", required = true, metaVar = "PATH") public File taggerPath; @Option(name = "-modelPath", usage = "Path to the word2vec embeddings", required = true, metaVar = "PATH") public File modelPath; @Option(name = "-suffix", usage = "Altered suffix of *.nxml files", required = false, metaVar = "SCIDP SUFFIX") public String suffix = "_scidp.txt"; @Option(name = "-pythonPath", usage = "Path to the python executable", required = true, metaVar = "TRAIN") public File pythonPath; } private static Logger logger = Logger .getLogger(SciDT_05_runSciDT.class); /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Options options = new Options(); CmdLineParser parser = new CmdLineParser(options); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.print("Arguments: "); parser.printSingleLineUsage(System.err); System.err.println("\n\n Options: \n"); parser.printUsage(System.err); System.exit(-1); } Pattern pattern = Pattern.compile("\\.(.*)$"); Matcher matcher = pattern.matcher(options.suffix); String fileEx = options.suffix; if( matcher.find() ) fileEx = matcher.group(1); String[] fileTypes = {fileEx}; @SuppressWarnings("unchecked") Iterator<File> it = FileUtils.iterateFiles(options.inDir, fileTypes, true); int counter = 0; String filesToRun = ""; while( it.hasNext() ) { File f = it.next(); if( !f.getName().endsWith(options.suffix) ) continue; if( counter == 10 || !it.hasNext() ) { String command = options.taggerPath.getPath() + " " + options.modelPath + " --use_attention --test_files " + filesToRun; runPythonCommand(command, options.pythonPath, options.trainPath.getParentFile()); counter = 0; filesToRun = ""; } else { filesToRun += " " + f.getPath(); counter++; } } } private static void runPythonCommand(String command, File pythonPath, File trainDir) throws Exception { command = pythonPath.getPath() + "/bin/python " + command; ProcessBuilder pb = new ProcessBuilder(command.split(" ")); Map<String,String> env = pb.environment(); env.put("PYTHONPATH", pythonPath.getPath() + "/lib/python2.7/site-packages"); pb.directory(trainDir); Process p = pb.start(); if (p == null) { throw new Exception("Can't execute " + command); } InputStream in = p.getErrorStream(); BufferedInputStream buf = new BufferedInputStream(in); InputStreamReader inread = new InputStreamReader(buf); BufferedReader bufferedreader = new BufferedReader(inread); String line, out = ""; while ((line = bufferedreader.readLine()) != null) { out += line; } try { if (p.waitFor() != 0) { System.err.println("CMD: " + command); System.err.println("RETURNED ERROR: " + out); } } catch (Exception e) { System.err.println(out); } finally { // Close the InputStream bufferedreader.close(); inread.close(); buf.close(); in.close(); } } }
27.264368
116
0.679806
2d552dd09ee2d247a9ef6d1d283df7628f6fc494
1,367
package models.financeiro; import javax.persistence.*; import java.math.BigDecimal; import java.util.Calendar; @Entity @Table(name = "solicitacao_financeira") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public abstract class SolicitacaoFinanceira { @Id @SequenceGenerator(name="solicitacao_financeira_id_seq", sequenceName = "solicitacao_financeira_id_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "solicitacao_financeira_id_seq") @Column(name = "solicitacao_financeira_id",updatable = false) private Long id; @Column(name = "usuario_id") private Long solicitante; private BigDecimal valor; @Column(name = "criado_em") private Calendar criadoEm = Calendar.getInstance(); @OneToOne @JoinColumn(name = "conta_id") private Conta conta; public SolicitacaoFinanceira() { } public SolicitacaoFinanceira(Long solicitante, BigDecimal valor) { this.solicitante = solicitante; this.valor = valor; } public Long getId() { return id; } public Long getSolicitante() { return solicitante; } public BigDecimal getValor() { return valor; } public Calendar getCriadoEm() { return criadoEm; } public void setConta(Conta conta) { this.conta = conta; } }
23.568966
128
0.6891
e043c6dc43739951aead193578987dbde8b3fbdc
15,282
package com.instructure.canvasapi.utilities; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import com.instructure.canvasapi.api.BuildInterfaceAPI; import com.instructure.canvasapi.model.CanvasError; import java.io.Serializable; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * CanvasCallback is a parameterized class that handles pagination and caching automatically. * Created by Joshua Dutton on 8/9/13. * * Copyright (c) 2014 Instructure. All rights reserved. */ public abstract class CanvasCallback<T> implements Callback<T> { protected APIStatusDelegate statusDelegate; // Controls whether of not the cache callbacks are called. Useful for pull-to-refresh, where the cache results should be ignored protected APICacheStatusDelegate cacheStatusDelegate; private String cacheFileName; private boolean isNextPage = false; private boolean isCancelled = false; private boolean isFinished = true; private boolean hasReadFromCache = false; public static ErrorDelegate defaultErrorDelegate; private ErrorDelegate errorDelegate; /////////////////////////////////////////////////////////////////////////// // Getters and Setters /////////////////////////////////////////////////////////////////////////// public boolean isFinished() { return isFinished; } public boolean isCancelled() { return isCancelled; } public void setFinished(boolean isFinished) { this.isFinished = isFinished; } public boolean hasReadFromCache(){ return hasReadFromCache; } public void setHasReadFromCache(boolean hasReadFromCache){ this.hasReadFromCache = hasReadFromCache; } public APIStatusDelegate getStatusDelegate() { return statusDelegate; } public APICacheStatusDelegate getCacheStatusDelegate() { return cacheStatusDelegate; } /** * setIsNextPage sets whether you're on the NextPages (2 or more) of pagination. * @param nextPage */ public void setIsNextPage(boolean nextPage){ isNextPage = nextPage; } /////////////////////////////////////////////////////////////////////////// // Constructors /////////////////////////////////////////////////////////////////////////// /** * @param statusDelegate Delegate to get the context */ public CanvasCallback(APIStatusDelegate statusDelegate) { setupDelegates(statusDelegate, null); } /** * Overload constructor to override default error delegate. */ public CanvasCallback(APIStatusDelegate statusDelegate, ErrorDelegate errorDelegate){ setupDelegates(statusDelegate, errorDelegate); } private void setupDelegates(APIStatusDelegate statusDelegate, ErrorDelegate errorDelegate) { this.statusDelegate = statusDelegate; if (statusDelegate instanceof APICacheStatusDelegate) { this.cacheStatusDelegate = (APICacheStatusDelegate) statusDelegate; } if (errorDelegate == null) { this.errorDelegate = getDefaultErrorDelegate(statusDelegate.getContext()); } else { this.errorDelegate = errorDelegate; } if(this.errorDelegate == null){ Log.e(APIHelpers.LOG_TAG, "WARNING: No ErrorDelegate Set."); } } /////////////////////////////////////////////////////////////////////////// // Helpers /////////////////////////////////////////////////////////////////////////// /** * Returns the default Error Delegate * @param context * @return */ public static ErrorDelegate getDefaultErrorDelegate(Context context){ if(defaultErrorDelegate == null ){ String defaultErrorDelegateClass = APIHelpers.getDefaultErrorDelegateClass(context); if(defaultErrorDelegateClass != null){ try { Class<?> errorDelegateClass = (Class.forName(defaultErrorDelegateClass)); defaultErrorDelegate = (ErrorDelegate) errorDelegateClass.newInstance(); } catch (Exception E) { Log.e(APIHelpers.LOG_TAG,"WARNING: Invalid defaultErrorDelegateClass Set: "+defaultErrorDelegateClass); } } } return defaultErrorDelegate; } private void finishLoading() { isFinished = true; statusDelegate.onCallbackFinished(SOURCE.API); } /** * @return Current context, can be null */ public Context getContext(){ return statusDelegate.getContext(); } /** * setShouldCache sets whether or not a call should be cached and the filename where it'll be cached to. * Should only be called by the API */ @Deprecated public void setShouldCache(String fileName) { cacheFileName = fileName; } /** * shouldCache is a helper for whether or not a cacheFileName has been set. * @return */ @Deprecated public boolean shouldCache() { return cacheFileName != null; } /** * Intended to work as AsyncTask.cancel() does. * The network call is still made, but no response is made. * * Gotchas: * Cache is still called. * The callback has to be reinitialized as you can't 'uncancel' */ public void cancel(){ isCancelled = true; } /** * readFromCache reads from the cache filename and simultaneously sets the cache filename * Use {@link BuildInterfaceAPI#buildCacheInterface} instead * @param path */ @Deprecated public void readFromCache(String path) { new ReadCacheData().execute(path); } @Deprecated public boolean deleteCache(){ return FileUtilities.DeleteFile(getContext(), cacheFileName); } /////////////////////////////////////////////////////////////////////////// // Interface /////////////////////////////////////////////////////////////////////////// /** * cache is a function you can override to get the cached values. * @param t */ @Deprecated public void cache(T t) { } public void cache(T t, LinkHeaders linkHeaders, Response response) { firstPage(t, linkHeaders, response); } /** * firstPage is the first (or only in some cases) of the API response. * @param t * @param linkHeaders * @param response */ public abstract void firstPage(T t, LinkHeaders linkHeaders, Response response); /** * * nextPage is the second (or more) page of the API response. * Defaults to calling firstPage * Override if you want to change this functionality * @param t * @param linkHeaders * @param response */ public void nextPage(T t, LinkHeaders linkHeaders, Response response){ firstPage(t, linkHeaders, response); } /** * onFailure is a way to handle a failure instead using the * default error handling * @param retrofitError * @return true if the failure was handled, false otherwise */ public boolean onFailure(RetrofitError retrofitError) { return false; } /////////////////////////////////////////////////////////////////////////// // Retrofit callback methods /////////////////////////////////////////////////////////////////////////// /** * If you want caching and pagination, you must call this function using super or leave it alone.. * @param t * @param response */ @Override public void success(T t, Response response) { // check if it's been cancelled or detached Log.d("URL_STATUS", APIHelpers.isCachedResponse(response) ? "From cache " + response.getUrl() : "From API " + response.getUrl()); if(isCancelled || t == null || getContext() == null) { return; } new CacheData(t, response).execute(t); } /** * failure calls the correct method on the ErrorDelegate that's been set. * @param retrofitError */ @Override public void failure(RetrofitError retrofitError) { // check if it's cancelled or detached if (isCancelled || getContext() == null) { return; } finishLoading(); Log.e(APIHelpers.LOG_TAG, "ERROR: " + retrofitError.getUrl()); Log.e(APIHelpers.LOG_TAG, "ERROR: " + retrofitError.getMessage()); // Return if the failure was already handled if (onFailure(retrofitError)) { return; } if (errorDelegate == null) { Log.d(APIHelpers.LOG_TAG, "WARNING: No ErrorDelegate Provided "); return; } CanvasError canvasError; switch (retrofitError.getKind()) { case CONVERSION: canvasError = CanvasError.createError("Conversion Error", "An exception was thrown while (de)serializing a body"); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; case HTTP: // A non-200 HTTP status code was received from the server. handleHTTPError(retrofitError); break; case NETWORK: // An IOException occurred while communicating to the server. statusDelegate.onNoNetwork(); errorDelegate.noNetworkError(retrofitError, getContext()); break; case UNEXPECTED: canvasError = CanvasError.createError("Unexpected Error", "An internal error occurred while attempting to execute a request."); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; default: canvasError = CanvasError.createError("Unexpected Error", "An unexpected error occurred."); errorDelegate.generalError(retrofitError, canvasError, getContext()); break; } } private void handleHTTPError(RetrofitError retrofitError) { Response response = retrofitError.getResponse(); if (response == null) { return; } Log.e(APIHelpers.LOG_TAG, "Response code: " + response.getStatus()); Log.e(APIHelpers.LOG_TAG, "Response body: " + response.getBody()); CanvasError canvasError = null; try { canvasError = (CanvasError) retrofitError.getBodyAs(CanvasError.class); } catch (Exception exception) { } if (response.getStatus() == 200) { errorDelegate.generalError(retrofitError, canvasError, getContext()); } else if (response.getStatus() == 401) { errorDelegate.notAuthorizedError(retrofitError, canvasError, getContext()); } else if (response.getStatus() >= 400 && response.getStatus() < 500) { errorDelegate.invalidUrlError(retrofitError, getContext()); } else if (response.getStatus() >= 500 && response.getStatus() < 600) { //don't do anything for a 504 (Unsatisfiable Request (only-if-cached)). //It will happen when we try to read from the http cache and there isn't //anything there if (response.getStatus() == 504 && APIHelpers.isCachedResponse(response)) { if (!CanvasRestAdapter.isNetworkAvaliable(getContext())) { // Purposely not part of the above if statement. First if statement is prevent the error delegate from a 504 cache response statusDelegate.onNoNetwork(); // Only call when no items were cached and there isn't a network } // do nothing } else { errorDelegate.serverError(retrofitError, getContext()); } } } public static enum SOURCE{ API, CACHE; public boolean isAPI(){ return this == API; } public boolean isCache(){ return this == CACHE; } } private class CacheData extends AsyncTask<T, Void, LinkHeaders> { private T t; private Response response; public CacheData(T t, Response response) { this.t = t; this.response = response; } @Override protected LinkHeaders doInBackground(T... params) { LinkHeaders linkHeaders = APIHelpers.parseLinkHeaderResponse(getContext(), response.getHeaders()); if (shouldCache() && !isNextPage && getContext() != null) { if(t instanceof Serializable) { try { FileUtilities.SerializableToFile(getContext(), cacheFileName, (Serializable)params[0]); } catch (Exception E) { Log.e(APIHelpers.LOG_TAG, "Could not cache serializable: " + E); } } } return linkHeaders; } @Override protected void onPostExecute(LinkHeaders linkHeaders) { super.onPostExecute(linkHeaders); if (isCancelled) { return; } boolean isCache = APIHelpers.isCachedResponse(response); boolean isIgnoreCache = false; if (cacheStatusDelegate != null) { isIgnoreCache = cacheStatusDelegate.shouldIgnoreCache(); } if (isCache && !isIgnoreCache) { Log.v(APIHelpers.LOG_TAG, "Cache"); cache(t); cache(t, linkHeaders, response); statusDelegate.onCallbackFinished(SOURCE.CACHE); } else if (isNextPage) { nextPage(t, linkHeaders, response); statusDelegate.onCallbackFinished(SOURCE.API); } else if (!isCache) { firstPage(t, linkHeaders, response); statusDelegate.onCallbackFinished(SOURCE.API); // since we have had a successful network call, reset the variable that tracks whether the user has seen the // no network error if (getContext() != null) { APIHelpers.setHasSeenNetworkErrorMessage(getContext(), false); } } isFinished = true; } } private class ReadCacheData extends AsyncTask<String, Void, Serializable> { private String path = null; @Override protected Serializable doInBackground(String... params) { path = params[0]; try { return FileUtilities.FileToSerializable(getContext(), path); } catch (Exception E) { Log.e(APIHelpers.LOG_TAG, "NO CACHE: " + path); } return null; } @Override protected void onPostExecute(Serializable serializable) { super.onPostExecute(serializable); if (serializable != null && getContext() != null) { cache((T) serializable); } setHasReadFromCache(true); setShouldCache(path); statusDelegate.onCallbackFinished(SOURCE.CACHE); } } }
33.366812
198
0.578524
654da5c4fc77923098c0bf014fbc5094b957eed0
1,643
package com.xmall.xmall.service.Impl; import com.xmall.xmall.dao.entity.FreightEntity; import com.xmall.xmall.dao.mapper.FreightMapper; import com.xmall.xmall.dao.mapper.ProductMapper; import com.xmall.xmall.service.FreightService; import com.xmall.xmall.utils.Constants; import com.xmall.xmall.utils.RedisUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * @ClassName: * @Description: TODO * @Author:Dazz1e * @Date:2021/12/14 下午 2:39 * Version V1.0 */ @Service @Slf4j public class FreightServiceImpl implements FreightService { @Resource private FreightMapper freightMapper; @Autowired private RedisUtil redisUtil; @Override @Cacheable(cacheNames = Constants.THIRTY_MINUTES, key ="'FREIGHT_'", unless = "#result == null") public List<FreightEntity> getAll() throws Exception { return freightMapper.findAll(); } @Override public int saveFreight(FreightEntity freightEntity) throws Exception { redisUtil.remove("THIRTY_MINUTES::FREIGHT_"); return freightMapper.saveFreight(freightEntity); } @Override public int deleteById(long id) throws Exception { redisUtil.remove("THIRTY_MINUTES::FREIGHT_"); return freightMapper.deleteById(id); } @Override public FreightEntity getById(long id) throws Exception { return freightMapper.findById(id) .orElseThrow(() -> new Exception("找不到")); } }
29.339286
100
0.732806
6b7b8f6dffe5daebe18dcc6f9e912f9195927e52
3,584
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.client.result; /** * @author Sean Owen */ public final class GeoParsedResult extends ParsedResult { private final double latitude; private final double longitude; private final double altitude; private final String query; GeoParsedResult(double latitude, double longitude, double altitude, String query) { super(ParsedResultType.GEO); this.latitude = latitude; this.longitude = longitude; this.altitude = altitude; this.query = query; } public String getGeoURI() { StringBuffer result = new StringBuffer(); result.append("geo:"); result.append(latitude); result.append(','); result.append(longitude); if (altitude > 0) { result.append(','); result.append(altitude); } if (query != null) { result.append('?'); result.append(query); } return result.toString(); } /** * @return latitude in degrees */ public double getLatitude() { return latitude; } /** * @return longitude in degrees */ public double getLongitude() { return longitude; } /** * @return altitude in meters. If not specified, in the geo URI, returns 0.0 */ public double getAltitude() { return altitude; } /** * @return query string associated with geo URI or null if none exists */ public String getQuery() { return query; } @Override public String getDisplayResult() { StringBuffer result = new StringBuffer(20); result.append(latitude); result.append(", "); result.append(longitude); if (altitude > 0.0) { result.append(", "); result.append(altitude); result.append('m'); } if (query != null) { result.append(" ("); result.append(query); result.append(')'); } return result.toString(); } /** * @return a URI link to Google Maps which display the point on the Earth described * by this instance, and sets the zoom level in a way that roughly reflects the * altitude, if specified */ /* public String getGoogleMapsURI() { StringBuffer result = new StringBuffer(50); result.append("http://maps.google.com/?ll="); result.append(latitude); result.append(','); result.append(longitude); if (altitude > 0.0f) { // Map altitude to zoom level, cleverly. Roughly, zoom level 19 is like a // view from 1000ft, 18 is like 2000ft, 17 like 4000ft, and so on. double altitudeInFeet = altitude * 3.28; int altitudeInKFeet = (int) (altitudeInFeet / 1000.0); // No Math.log() available here, so compute log base 2 the old fashioned way // Here logBaseTwo will take on a value between 0 and 18 actually int logBaseTwo = 0; while (altitudeInKFeet > 1 && logBaseTwo < 18) { altitudeInKFeet >>= 1; logBaseTwo++; } int zoom = 19 - logBaseTwo; result.append("&z="); result.append(zoom); } return result.toString(); } */ }
26.947368
85
0.646205
ad7863a8d3ce7744994228c42d05f6864378fa74
899
package com.xiaoyi.ssm.service; import java.util.List; import com.xiaoyi.ssm.model.VenueLog; /** * @Description: 场馆日志业务逻辑层 * @author 宋高俊 * @date 2018年8月16日 下午5:59:40 */ public interface VenueLogService extends BaseService<VenueLog, String> { /** * @Description: 根据场馆ID查询 * @author 宋高俊 * @date 2018年8月18日 下午2:03:12 */ Integer countByVenue(String id); /** * @Description: 根据场馆ID获取日志数据 * @author 宋高俊 * @date 2018年8月20日 下午3:03:51 */ List<VenueLog> selectByVenue(String venueid); /** * @Description: 条件查询场馆日志数据 * @author 宋高俊 * @param selectType * @param keyword * @return * @date 2018年10月15日 下午3:12:12 */ List<VenueLog> selectBySearch(Integer selectType, String keyword); /** * @Description: 保存日志数据 * @author 宋高俊 * @return * @date 2018年12月6日下午2:33:45 */ int saveLog(String venueid, String managerid, String content); }
19.543478
72
0.666296
57e266c1a92de99106e5858bcd9544007ed57d6d
2,857
package Chapter5.src.ChapterThree; import Chapter5.src.ChapterThree.EmployeeTdd.EmployeeTwo; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class EmployeeTwoTest { EmployeeTwo employee1 = new EmployeeTwo("toye", "Daramola", 20000); EmployeeTwo employee2 = new EmployeeTwo("toye", "Daramola", 20000); @BeforeEach void displayBeforeEach() { EmployeeTwo employee = new EmployeeTwo("toye", "Daramola", 20000); } @Test void testThatEmployeesFirstName(){ //HasFirstName employee1.setFirstName("Toye"); assertEquals("Toye", employee1.getFirstName()); } @Test void testThatEmployeesLastName(){ //HasSecondName employee1.setLastName("Daramola"); assertEquals("Daramola", employee1.getLastName()); } // @Test // void testThatEmployeesReceivesMonthlySalary() { // employee1.setMonthlySalary(20000); // assertEquals(20000, employee1.getMonthlySalary()); // } // @Test // void testThatEmployeesSalaryMustNotBeBelowZero() { //CannotBeBelowZero // employee2.setMonthlySalary(20000); // assertEquals(20000, employee2.getMonthlySalary()); // employee2.setMonthlySalary(-20000); // assertEquals(20000, employee2.getMonthlySalary()); // } // // @Test // void testThatEmployeesYearlySalariesCanBeCalculated() { //Calculated by/from what? // employee2.setMonthlySalary(20000.0); // assertEquals(240000,employee2.calculateYearlySalary()); // } // // @Test // void testThatEmployeesYearlySalariesCanBeIncreasedByTenPercentage() { //At what month/year // employee1.setMonthlySalary(20000); // assertEquals(22000, employee1.calculateNewSalary(10)); // } // // @Test // void testThatEmployeesYearlySalariesCanBeIncreasedByTenPercentageInAYear() { // employee1.setMonthlySalary(20000); // assertEquals(264000, employee1.calculateNewSalaryInMoreThanOneMonth(10, 12)); // } // // @Test // void testThatEmployeeHasEmployeeOne(){ //Instantiate object of class instead // employee2.setFirstName("Eric"); // assertEquals("Eric", employee2.getFirstName()); // employee2.setLastName("Chineye"); // assertEquals("Chineye", employee2.getLastName()); // employee2.setEmployees(1); // assertEquals(1, employee2.getEmployees()); // } // // @Test // void testThatEmployeeHasEmployeeTwo(){ //Instantiate object of class instead // employee2.setFirstName("Eric"); // assertEquals("Eric", employee2.getFirstName()); // employee2.setLastName("Chineye"); // assertEquals("Chineye", employee2.getLastName()); // employee2.setEmployees(2); // assertEquals(2, employee2.getEmployees()); // } }
34.841463
98
0.674134
0f2d94e8b563b41464223b392872814a5ddb27ba
443
package com.appspot.dmutti.calculator.support; import javax.persistence.*; public class EMF { private EntityManagerFactory entityManagerFactory; public EntityManager entityManager() { return entityManagerFactory.createEntityManager(); } public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } }
27.6875
85
0.715576
3238e665bf30f38f0dec63a83d56d0235b0296fe
1,683
package com.zhangxin.study.utils; import android.content.Context; import android.os.Looper; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.text.TextUtils; import android.widget.Toast; import com.zhangxin.study.MyApplication; /** * @Author zhangxin * @date 2017/7/3 15:33 * @description 自定义toast **/ public class ToastUtil { private static Toast mToast = null; /** * 非延时toast * * @param * @param msg */ public static void showTextToast(@NonNull String msg) { try { if (!TextUtils.isEmpty(msg) && !msg.equals("null")) { if (mToast != null) { mToast.cancel(); } mToast = Toast.makeText(MyApplication.getInstance(), msg + "", Toast.LENGTH_LONG); mToast.show(); } } catch (Exception e) { e.printStackTrace(); } } public static void showTextToast(@StringRes int stringId) { try { if (mToast != null) { mToast.cancel(); } mToast = Toast.makeText(MyApplication.getInstance(), stringId + "", Toast.LENGTH_LONG); mToast.show(); } catch (Exception e) { e.printStackTrace(); } } public static void showToast(final String toast, final Context context) { new Thread(new Runnable() { @Override public void run() { Looper.prepare(); Toast.makeText(context, toast, Toast.LENGTH_SHORT).show(); Looper.loop(); } }).start(); } }
25.119403
99
0.547237
21623b8af1ebf186db46f481fb9eb8dd1105f90e
2,799
/* * Copyright (C) 2011 LINUXTEK, Inc. All Rights Reserved. */ package com.linuxtek.kona.app.social.entity; import java.util.Date; public class KBaseFriendshipEvent implements KFriendshipEvent { private Long id; private Long typeId; private Long friendshipId; private Long userId; private Long friendId; private String event; private Date eventDate; private Date createdDate; private Date updatedDate; private static final long serialVersionUID = 1L; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } @Override public Long getTypeId() { return typeId; } @Override public void setTypeId(Long typeId) { this.typeId = typeId; } @Override public Long getFriendshipId() { return friendshipId; } @Override public void setFriendshipId(Long friendshipId) { this.friendshipId = friendshipId; } @Override public Long getUserId() { return userId; } @Override public void setUserId(Long userId) { this.userId = userId; } @Override public Long getFriendId() { return friendId; } @Override public void setFriendId(Long friendId) { this.friendId = friendId; } @Override public String getEvent() { return event; } @Override public void setEvent(String event) { this.event = event == null ? null : event.trim(); } @Override public Date getEventDate() { return eventDate; } @Override public void setEventDate(Date eventDate) { this.eventDate = eventDate; } @Override public Date getCreatedDate() { return createdDate; } @Override public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } @Override public Date getUpdatedDate() { return updatedDate; } @Override public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", typeId=").append(typeId); sb.append(", friendshipId=").append(friendshipId); sb.append(", userId=").append(userId); sb.append(", friendId=").append(friendId); sb.append(", event=").append(event); sb.append(", eventDate=").append(eventDate); sb.append(", createdDate=").append(createdDate); sb.append(", updatedDate=").append(updatedDate); sb.append("]"); return sb.toString(); } }
21.530769
63
0.61522
6f7b2dba5cdaf9c931841b92e68df8806681c5cc
658
package com.jt.manage.service; import java.util.List; import com.jt.common.vo.EasyUIResult; import com.jt.manage.pojo.Item; import com.jt.manage.pojo.ItemDesc; public interface ItemService { //查询全部商品信息 List<Item> findAll(); EasyUIResult findItemByPage(int page, int rows); String findItemNameById(Long itemId); //新增商品信息 void saveItem(Item item,String desc); //修改商品信息 void updateItem(Item item, String desc); //删除商品信息 void deleteItems(Long[] ids); //修改状态信息,上下架 void updateStatus(Long[] ids, int status); //查询商品描述信息 ItemDesc findItemDesc(Long itemId); //根据商品id进行查询 Item findItemById(Long itemId); }
18.8
50
0.708207
469e35174fc20cd69ee639bb02970f1c82281eee
1,709
/* * 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.cuba.core.model.beanvalidation; import io.jmix.data.entity.StandardEntity; import org.hibernate.validator.constraints.Length; import javax.persistence.*; import javax.validation.Valid; import javax.validation.constraints.NotNull; @Entity(name = "test$ValidatedEntity") @Table(name = "TEST_VALIDATED_ENTITY") public class ValidatedEntity extends StandardEntity { @Length(min = 5, max = 2147483647) @NotNull @Column(name = "NAME") protected String name; @Embedded @Valid @AttributeOverrides({ @AttributeOverride(name = "name", column = @Column(name = "EE_NAME")) }) protected EmbeddedValidatedEntity embeddedValidatedEntity; public String getName() { return name; } public void setName(String name) { this.name = name; } public EmbeddedValidatedEntity getEmbeddedValidatedEntity() { return embeddedValidatedEntity; } public void setEmbeddedValidatedEntity(EmbeddedValidatedEntity embeddedValidatedEntity) { this.embeddedValidatedEntity = embeddedValidatedEntity; } }
29.982456
93
0.726156
c14536428e0a8bce0278f411f25b7b8a3f7cb5e4
614
package net.binzume.android.nicovideo; import java.util.List; public class MyList { public final int id; public int userId; public String name; public String description; public int createDate; public int updateDate; public int isPublic; public List<MyListEntry> items; public MyList(int id) { this.id = id; } public static class MyListEntry extends VideoInfo { public MyListEntry(String videoId, String title) { super(videoId, title); } public int threadId; public int type; public int deleted; public String lastResBody; public long createDate; public long updateDate; } }
18.606061
52
0.741042
3067c0987b582d9876e3ad8510d549843637b68d
2,477
package org.jessenpan.leetcode.dsu; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author jessenpan * tag:dsu */ public class S839SimilarStringGroups { //TODO public int numSimilarGroups(String[] A) { int N = A.length; int W = A[0].length(); DSU dsu = new DSU(N); if (N < W * W) { // If few words, then check for pairwise similarity: O(N^2 W) for (int i = 0; i < N; ++i) for (int j = i + 1; j < N; ++j) if (similar(A[i], A[j])) dsu.union(i, j); } else { // If short words, check all neighbors: O(N W^3) Map<String, List<Integer>> buckets = new HashMap(); for (int i = 0; i < N; ++i) { char[] L = A[i].toCharArray(); for (int j0 = 0; j0 < L.length; ++j0) for (int j1 = j0 + 1; j1 < L.length; ++j1) { swap(L, j0, j1); StringBuilder sb = new StringBuilder(); for (char c : L) sb.append(c); buckets.computeIfAbsent(sb.toString(), x -> new ArrayList<Integer>()).add(i); swap(L, j0, j1); } } for (int i1 = 0; i1 < A.length; ++i1) if (buckets.containsKey(A[i1])) for (int i2 : buckets.get(A[i1])) dsu.union(i1, i2); } int ans = 0; for (int i = 0; i < N; ++i) if (dsu.parent[i] == i) ans++; return ans; } public boolean similar(String word1, String word2) { int diff = 0; for (int i = 0; i < word1.length(); ++i) if (word1.charAt(i) != word2.charAt(i)) diff++; return diff <= 2; } public void swap(char[] A, int i, int j) { char tmp = A[i]; A[i] = A[j]; A[j] = tmp; } static class DSU { int[] parent; public DSU(int N) { parent = new int[N]; for (int i = 0; i < N; ++i) parent[i] = i; } public int find(int x) { if (parent[x] != x) parent[x] = find(parent[x]); return parent[x]; } public void union(int x, int y) { parent[find(x)] = find(y); } } }
27.522222
101
0.419863
cd105c2d07ee67b58d952f047c1d49b8e965a2b9
23,511
package com.unionpay.sdk; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.ServiceInfo; import android.content.res.Resources; import android.nfc.NfcAdapter; import android.nfc.NfcManager; import android.nfc.cardemulation.CardEmulation; import android.os.Build; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Environment; import android.os.StatFs; import android.text.TextUtils; import android.util.DisplayMetrics; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.TimeZone; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import org.json.JSONObject; public class h { private static int a(String paramString) { String str = ""; try { Matcher localMatcher = Pattern.compile("([0-9]+)").matcher(paramString); paramString = str; if (localMatcher.find()) { paramString = localMatcher.toMatchResult().group(0); } int i = Integer.valueOf(paramString).intValue(); return i; } catch (Exception paramString) {} return 0; } public static String a() { return "Android+" + Build.VERSION.RELEASE; } private static String a(String paramString1, String paramString2) { try { String str = paramString1.toLowerCase(); if ((!str.startsWith("unknown")) && (!str.startsWith("alps")) && (!str.startsWith("android")) && (!str.startsWith("sprd")) && (!str.startsWith("spreadtrum")) && (!str.startsWith("rockchip")) && (!str.startsWith("wondermedia")) && (!str.startsWith("mtk")) && (!str.startsWith("mt65")) && (!str.startsWith("nvidia")) && (!str.startsWith("brcm")) && (!str.startsWith("marvell"))) { boolean bool = paramString2.toLowerCase().contains(str); if (!bool) {} } else { paramString1 = null; } return paramString1; } catch (Throwable paramString1) {} return null; } public static JSONObject a(Context paramContext) { try { JSONObject localJSONObject = new JSONObject(); localJSONObject.put("nfc-status", b(paramContext)); localJSONObject.put("appsRegistedHCE", d(paramContext)); localJSONObject.put("ssMode", f(paramContext)); return localJSONObject; } catch (Throwable paramContext) {} return null; } public static int b(Context paramContext) { if (paramContext == null) { return 0; } NfcAdapter localNfcAdapter = ((NfcManager)paramContext.getSystemService("nfc")).getDefaultAdapter(); int i; if (localNfcAdapter != null) { if (!localNfcAdapter.isEnabled()) { i = 1; } } for (;;) { return i; if ((r.a(19)) && (paramContext.getPackageManager().hasSystemFeature("android.hardware.nfc.hce"))) { i = 3; } else { i = 2; continue; i = 0; } } } public static String b() { return Build.MANUFACTURER.trim(); } private static String b(String paramString) { BufferedReader localBufferedReader = null; Object localObject4 = null; Object localObject3 = null; Object localObject1 = localBufferedReader; try { FileReader localFileReader = new FileReader(paramString); localObject1 = localBufferedReader; Object localObject2 = localObject4; char[] arrayOfChar; int i; return (String)localObject2; } catch (Throwable paramString) { try { arrayOfChar = new char['Ѐ']; localObject1 = localBufferedReader; localObject2 = localObject4; localBufferedReader = new BufferedReader(localFileReader, 1024); for (paramString = (String)localObject3;; paramString = paramString + new String(arrayOfChar, 0, i)) { localObject1 = paramString; localObject2 = paramString; i = localBufferedReader.read(arrayOfChar, 0, 1024); if (-1 == i) { break; } localObject1 = paramString; localObject2 = paramString; } localObject1 = paramString; localObject2 = paramString; localBufferedReader.close(); localObject1 = paramString; localObject2 = paramString; localFileReader.close(); return paramString; } catch (IOException paramString) {} paramString = paramString; return (String)localObject1; } } public static String c() { return Build.BRAND.trim(); } public static String c(Context paramContext) { try { paramContext = paramContext.getResources().getDisplayMetrics(); if (paramContext != null) { int i = paramContext.widthPixels; int j = paramContext.heightPixels; paramContext = Math.min(i, j) + "*" + Math.max(i, j) + "*" + paramContext.densityDpi; return paramContext; } } catch (Throwable paramContext) {} return ""; } public static String d() { return Build.MODEL.trim(); } private static JSONArray d(Context paramContext) { if (!r.a(19)) { return null; } try { JSONArray localJSONArray = new JSONArray(); paramContext = e(paramContext).iterator(); while (paramContext.hasNext()) { PackageInfo localPackageInfo = (PackageInfo)paramContext.next(); ServiceInfo[] arrayOfServiceInfo = localPackageInfo.services; if (arrayOfServiceInfo != null) { int j = arrayOfServiceInfo.length; int i = 0; while (i < j) { Bundle localBundle = arrayOfServiceInfo[i].metaData; if ((localBundle != null) && (localBundle.containsKey("android.nfc.cardemulation.host_apdu_service"))) { localJSONArray.put(localPackageInfo.packageName); } i += 1; } } } return localJSONArray; } catch (Throwable paramContext) {} return null; } public static int e() { return TimeZone.getDefault().getRawOffset() / 3600000; } /* Error */ private static List e(Context paramContext) { // Byte code: // 0: aload_0 // 1: invokevirtual 172 android/content/Context:getPackageManager ()Landroid/content/pm/PackageManager; // 4: astore_2 // 5: aload_2 // 6: iconst_4 // 7: invokevirtual 315 android/content/pm/PackageManager:getInstalledPackages (I)Ljava/util/List; // 10: astore_0 // 11: aload_0 // 12: areturn // 13: astore_0 // 14: new 317 java/util/ArrayList // 17: dup // 18: invokespecial 318 java/util/ArrayList:<init> ()V // 21: astore_3 // 22: aconst_null // 23: astore_0 // 24: invokestatic 324 java/lang/Runtime:getRuntime ()Ljava/lang/Runtime; // 27: ldc_w 326 // 30: invokevirtual 330 java/lang/Runtime:exec (Ljava/lang/String;)Ljava/lang/Process; // 33: astore 4 // 35: new 195 java/io/BufferedReader // 38: dup // 39: new 332 java/io/InputStreamReader // 42: dup // 43: aload 4 // 45: invokevirtual 338 java/lang/Process:getInputStream ()Ljava/io/InputStream; // 48: invokespecial 341 java/io/InputStreamReader:<init> (Ljava/io/InputStream;)V // 51: invokespecial 344 java/io/BufferedReader:<init> (Ljava/io/Reader;)V // 54: astore_1 // 55: aload_1 // 56: astore_0 // 57: aload_1 // 58: invokevirtual 347 java/io/BufferedReader:readLine ()Ljava/lang/String; // 61: astore 5 // 63: aload 5 // 65: ifnull +60 -> 125 // 68: aload_1 // 69: astore_0 // 70: aload_3 // 71: aload_2 // 72: aload 5 // 74: aload 5 // 76: bipush 58 // 78: invokevirtual 351 java/lang/String:indexOf (I)I // 81: iconst_1 // 82: iadd // 83: invokevirtual 354 java/lang/String:substring (I)Ljava/lang/String; // 86: iconst_4 // 87: invokevirtual 358 android/content/pm/PackageManager:getPackageInfo (Ljava/lang/String;I)Landroid/content/pm/PackageInfo; // 90: invokeinterface 362 2 0 // 95: pop // 96: goto -41 -> 55 // 99: astore_2 // 100: aload_1 // 101: astore_0 // 102: aload_2 // 103: invokevirtual 365 java/lang/Throwable:printStackTrace ()V // 106: aload_3 // 107: astore_0 // 108: aload_1 // 109: ifnull -98 -> 11 // 112: aload_1 // 113: invokevirtual 209 java/io/BufferedReader:close ()V // 116: aload_3 // 117: areturn // 118: astore_0 // 119: aload_0 // 120: invokevirtual 365 java/lang/Throwable:printStackTrace ()V // 123: aload_3 // 124: areturn // 125: aload_1 // 126: astore_0 // 127: aload 4 // 129: invokevirtual 368 java/lang/Process:waitFor ()I // 132: pop // 133: aload_1 // 134: invokevirtual 209 java/io/BufferedReader:close ()V // 137: aload_3 // 138: areturn // 139: astore_0 // 140: aload_0 // 141: invokevirtual 365 java/lang/Throwable:printStackTrace ()V // 144: aload_3 // 145: areturn // 146: astore_2 // 147: aload_0 // 148: astore_1 // 149: aload_2 // 150: astore_0 // 151: aload_1 // 152: ifnull +7 -> 159 // 155: aload_1 // 156: invokevirtual 209 java/io/BufferedReader:close ()V // 159: aload_0 // 160: athrow // 161: astore_1 // 162: aload_1 // 163: invokevirtual 365 java/lang/Throwable:printStackTrace ()V // 166: goto -7 -> 159 // 169: astore_2 // 170: aload_0 // 171: astore_1 // 172: aload_2 // 173: astore_0 // 174: goto -23 -> 151 // 177: astore_2 // 178: aconst_null // 179: astore_1 // 180: goto -80 -> 100 // Local variable table: // start length slot name signature // 0 183 0 paramContext Context // 54 102 1 localObject1 Object // 161 2 1 localThrowable1 Throwable // 171 9 1 localContext Context // 4 68 2 localPackageManager PackageManager // 99 4 2 localThrowable2 Throwable // 146 4 2 localObject2 Object // 169 4 2 localObject3 Object // 177 1 2 localThrowable3 Throwable // 21 124 3 localArrayList java.util.ArrayList // 33 95 4 localProcess Process // 61 14 5 str String // Exception table: // from to target type // 5 11 13 java/lang/Throwable // 57 63 99 java/lang/Throwable // 70 96 99 java/lang/Throwable // 127 133 99 java/lang/Throwable // 112 116 118 java/lang/Throwable // 133 137 139 java/lang/Throwable // 24 55 146 finally // 155 159 161 java/lang/Throwable // 57 63 169 finally // 70 96 169 finally // 102 106 169 finally // 127 133 169 finally // 24 55 177 java/lang/Throwable } private static int f(Context paramContext) { try { if (r.a(19)) { int i = CardEmulation.getInstance(((NfcManager)paramContext.getSystemService("nfc")).getDefaultAdapter()).getSelectionModeForCategory("payment"); return i; } } catch (Throwable paramContext) {} return -1; } public static String f() { try { String str = Build.MODEL.trim(); Object localObject2 = a(Build.MANUFACTURER.trim(), str); Object localObject1 = localObject2; if (TextUtils.isEmpty((CharSequence)localObject2)) { localObject1 = a(Build.BRAND.trim(), str); } localObject2 = localObject1; if (localObject1 == null) { localObject2 = ""; } localObject1 = (String)localObject2 + ":" + str; return (String)localObject1; } catch (Throwable localThrowable) {} return ""; } public static int g() { return Build.VERSION.SDK_INT; } public static String h() { return Build.VERSION.RELEASE; } public static String i() { return Locale.getDefault().getLanguage(); } public static String j() { return Locale.getDefault().getCountry(); } /* Error */ public static String[] k() { // Byte code: // 0: iconst_4 // 1: anewarray 81 java/lang/String // 4: astore_3 // 5: iconst_0 // 6: istore_0 // 7: iload_0 // 8: iconst_4 // 9: if_icmpge +15 -> 24 // 12: aload_3 // 13: iload_0 // 14: ldc 17 // 16: aastore // 17: iload_0 // 18: iconst_1 // 19: iadd // 20: istore_0 // 21: goto -14 -> 7 // 24: new 317 java/util/ArrayList // 27: dup // 28: invokespecial 318 java/util/ArrayList:<init> ()V // 31: astore 4 // 33: new 192 java/io/FileReader // 36: dup // 37: ldc_w 410 // 40: invokespecial 193 java/io/FileReader:<init> (Ljava/lang/String;)V // 43: astore 5 // 45: new 195 java/io/BufferedReader // 48: dup // 49: aload 5 // 51: sipush 1024 // 54: invokespecial 198 java/io/BufferedReader:<init> (Ljava/io/Reader;I)V // 57: astore 6 // 59: aload 6 // 61: invokevirtual 347 java/io/BufferedReader:readLine ()Ljava/lang/String; // 64: astore 7 // 66: aload 7 // 68: ifnull +132 -> 200 // 71: aload 4 // 73: aload 7 // 75: invokeinterface 362 2 0 // 80: pop // 81: goto -22 -> 59 // 84: astore 7 // 86: aload 6 // 88: invokevirtual 209 java/io/BufferedReader:close ()V // 91: aload 5 // 93: invokevirtual 210 java/io/FileReader:close ()V // 96: iconst_0 // 97: istore_0 // 98: iload_0 // 99: ifeq +159 -> 258 // 102: aload 4 // 104: invokeinterface 413 1 0 // 109: istore_2 // 110: iconst_0 // 111: istore_0 // 112: iload_0 // 113: iconst_3 // 114: if_icmpge +144 -> 258 // 117: iconst_3 // 118: anewarray 81 java/lang/String // 121: dup // 122: iconst_0 // 123: ldc_w 415 // 126: aastore // 127: dup // 128: iconst_1 // 129: ldc_w 417 // 132: aastore // 133: dup // 134: iconst_2 // 135: ldc_w 419 // 138: aastore // 139: iload_0 // 140: aaload // 141: invokestatic 25 java/util/regex/Pattern:compile (Ljava/lang/String;)Ljava/util/regex/Pattern; // 144: astore 5 // 146: iconst_0 // 147: istore_1 // 148: iload_1 // 149: iload_2 // 150: if_icmpge +101 -> 251 // 153: aload 5 // 155: aload 4 // 157: iload_1 // 158: invokeinterface 423 2 0 // 163: checkcast 81 java/lang/String // 166: invokevirtual 29 java/util/regex/Pattern:matcher (Ljava/lang/CharSequence;)Ljava/util/regex/Matcher; // 169: astore 6 // 171: aload 6 // 173: invokevirtual 35 java/util/regex/Matcher:find ()Z // 176: ifeq +17 -> 193 // 179: aload_3 // 180: iload_0 // 181: aload 6 // 183: invokevirtual 39 java/util/regex/Matcher:toMatchResult ()Ljava/util/regex/MatchResult; // 186: iconst_1 // 187: invokeinterface 45 2 0 // 192: aastore // 193: iload_1 // 194: iconst_1 // 195: iadd // 196: istore_1 // 197: goto -49 -> 148 // 200: aload 6 // 202: invokevirtual 209 java/io/BufferedReader:close ()V // 205: aload 5 // 207: invokevirtual 210 java/io/FileReader:close ()V // 210: iconst_1 // 211: istore_0 // 212: goto -114 -> 98 // 215: astore 5 // 217: iconst_1 // 218: istore_0 // 219: goto -121 -> 98 // 222: astore 5 // 224: iconst_0 // 225: istore_0 // 226: goto -128 -> 98 // 229: astore 7 // 231: aload 6 // 233: invokevirtual 209 java/io/BufferedReader:close ()V // 236: aload 5 // 238: invokevirtual 210 java/io/FileReader:close ()V // 241: aload 7 // 243: athrow // 244: astore 5 // 246: iconst_0 // 247: istore_0 // 248: goto -150 -> 98 // 251: iload_0 // 252: iconst_1 // 253: iadd // 254: istore_0 // 255: goto -143 -> 112 // 258: aload_3 // 259: iconst_3 // 260: ldc_w 425 // 263: invokestatic 427 com/unionpay/sdk/h:b (Ljava/lang/String;)Ljava/lang/String; // 266: aastore // 267: aload_3 // 268: areturn // 269: astore 5 // 271: iconst_1 // 272: istore_0 // 273: goto -175 -> 98 // 276: astore 5 // 278: goto -37 -> 241 // Local variable table: // start length slot name signature // 6 267 0 i int // 147 50 1 j int // 109 42 2 k int // 4 264 3 arrayOfString String[] // 31 125 4 localArrayList java.util.ArrayList // 43 163 5 localObject1 Object // 215 1 5 localIOException1 IOException // 222 15 5 localIOException2 IOException // 244 1 5 localThrowable1 Throwable // 269 1 5 localThrowable2 Throwable // 276 1 5 localIOException3 IOException // 57 175 6 localObject2 Object // 64 10 7 str String // 84 1 7 localThrowable3 Throwable // 229 13 7 localObject3 Object // Exception table: // from to target type // 59 66 84 java/lang/Throwable // 71 81 84 java/lang/Throwable // 200 210 215 java/io/IOException // 86 96 222 java/io/IOException // 59 66 229 finally // 71 81 229 finally // 33 59 244 java/lang/Throwable // 86 96 244 java/lang/Throwable // 231 241 244 java/lang/Throwable // 241 244 244 java/lang/Throwable // 200 210 269 java/lang/Throwable // 231 241 276 java/io/IOException } public static String[] l() { return null; } /* Error */ public static int[] m() { // Byte code: // 0: iconst_0 // 1: istore_1 // 2: iconst_2 // 3: newarray <illegal type> // 5: astore_2 // 6: aload_2 // 7: iconst_0 // 8: iconst_0 // 9: iastore // 10: aload_2 // 11: iconst_1 // 12: iconst_0 // 13: iastore // 14: iconst_4 // 15: newarray <illegal type> // 17: astore 5 // 19: iconst_0 // 20: istore_0 // 21: iload_0 // 22: iconst_4 // 23: if_icmpge +15 -> 38 // 26: aload 5 // 28: iload_0 // 29: iconst_0 // 30: iastore // 31: iload_0 // 32: iconst_1 // 33: iadd // 34: istore_0 // 35: goto -14 -> 21 // 38: new 192 java/io/FileReader // 41: dup // 42: ldc_w 432 // 45: invokespecial 193 java/io/FileReader:<init> (Ljava/lang/String;)V // 48: astore_3 // 49: new 195 java/io/BufferedReader // 52: dup // 53: aload_3 // 54: sipush 1024 // 57: invokespecial 198 java/io/BufferedReader:<init> (Ljava/io/Reader;I)V // 60: astore 4 // 62: iload_1 // 63: istore_0 // 64: iload_0 // 65: iconst_4 // 66: if_icmpge +22 -> 88 // 69: aload 5 // 71: iload_0 // 72: aload 4 // 74: invokevirtual 347 java/io/BufferedReader:readLine ()Ljava/lang/String; // 77: invokestatic 434 com/unionpay/sdk/h:a (Ljava/lang/String;)I // 80: iastore // 81: iload_0 // 82: iconst_1 // 83: iadd // 84: istore_0 // 85: goto -21 -> 64 // 88: aload_2 // 89: iconst_0 // 90: aload 5 // 92: iconst_0 // 93: iaload // 94: iastore // 95: aload 5 // 97: iconst_1 // 98: iaload // 99: istore_0 // 100: aload 5 // 102: iconst_2 // 103: iaload // 104: istore_1 // 105: aload_2 // 106: iconst_1 // 107: aload 5 // 109: iconst_3 // 110: iaload // 111: iload_0 // 112: iload_1 // 113: iadd // 114: iadd // 115: iastore // 116: aload 4 // 118: invokevirtual 209 java/io/BufferedReader:close ()V // 121: aload_3 // 122: invokevirtual 210 java/io/FileReader:close ()V // 125: aload_2 // 126: areturn // 127: astore 5 // 129: aload 4 // 131: invokevirtual 209 java/io/BufferedReader:close ()V // 134: aload_3 // 135: invokevirtual 210 java/io/FileReader:close ()V // 138: aload_2 // 139: areturn // 140: astore_3 // 141: aload_2 // 142: areturn // 143: astore 5 // 145: aload 4 // 147: invokevirtual 209 java/io/BufferedReader:close ()V // 150: aload_3 // 151: invokevirtual 210 java/io/FileReader:close ()V // 154: aload 5 // 156: athrow // 157: astore_3 // 158: aload_2 // 159: areturn // 160: astore_3 // 161: goto -7 -> 154 // 164: astore_3 // 165: aload_2 // 166: areturn // Local variable table: // start length slot name signature // 20 94 0 i int // 1 113 1 j int // 5 161 2 arrayOfInt1 int[] // 48 87 3 localFileReader FileReader // 140 11 3 localIOException1 IOException // 157 1 3 localThrowable Throwable // 160 1 3 localIOException2 IOException // 164 1 3 localIOException3 IOException // 60 86 4 localBufferedReader BufferedReader // 17 91 5 arrayOfInt2 int[] // 127 1 5 localIOException4 IOException // 143 12 5 localObject Object // Exception table: // from to target type // 69 81 127 java/io/IOException // 129 138 140 java/io/IOException // 69 81 143 finally // 38 62 157 java/lang/Throwable // 116 125 157 java/lang/Throwable // 129 138 157 java/lang/Throwable // 145 154 157 java/lang/Throwable // 154 157 157 java/lang/Throwable // 145 154 160 java/io/IOException // 116 125 164 java/io/IOException } public static int[] n() { try { StatFs localStatFs = new StatFs(Environment.getDataDirectory().getAbsolutePath()); int i = localStatFs.getBlockCount() * (localStatFs.getBlockSize() / 512) / 2; int j = localStatFs.getAvailableBlocks(); j = localStatFs.getBlockSize() / 512 * j / 2; localStatFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath()); int k = localStatFs.getBlockCount() * (localStatFs.getBlockSize() / 512) / 2; int m = localStatFs.getAvailableBlocks(); m = localStatFs.getBlockSize() / 512 * m / 2; return new int[] { i, j, k, m }; } catch (Throwable localThrowable) {} return null; } public static int o() { int i = 0; try { Object localObject = b("/sys/class/power_supply/battery/full_bat"); localObject = Pattern.compile("\\s*([0-9]+)").matcher((CharSequence)localObject); if (((Matcher)localObject).find()) { i = Integer.valueOf(((Matcher)localObject).toMatchResult().group(0)).intValue(); } return i; } catch (Exception localException) {} return 0; } public static class a {} } /* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/unionpay/sdk/h.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
29.025926
382
0.577347
d3294d0b2a75d7507f7e099fa00ae999fefa8f98
10,199
class wk5DW7EzNdPk { public boolean OK5rhwyRvtZ () { boolean B; return; while ( !false[ !new int[ new Rc7f2q()[ JA2VKj[ new D[ -new void[ -( this.u2YsFbnLHi())[ new dsB3kibYK()[ new vGFeA1SviU3a().x]]].pGm889jG7].wBgb()]]].nauLFSCj()]) AapH3().UjhkcVJqYu9mf; ; if ( !-( 3[ false.QoMFYKp])[ new TBT().Uot04rAH0ws8Wu()]) { CelE9Z KI1ZcA; } int JuI3ay2by = --true.q7uMGg5uyoS4u() = null.bfkVb(); return !!new P4m().ZB; boolean[] yE; void[][][] kAvHcdwvuV; while ( !this._Q) return; int mudWO3xuvQ; ; null.rZH(); { boolean[][][][][][] qm; } } public boolean[][][][] dd9ya3JNKIeC; public boolean[] em (FvLflyhzX7 q7C, int _1i0Wbeww8, int[][] xRKlj8bjgMdEm, int[][][] hj, boolean Jsdl, boolean FMNNHnd0lLdD, boolean[] qthaSkiEIUDAk1) throws O3Sav { while ( ( ( ( new void[ new Lly5SNr7yUkLj[ j8WFD1DG6.He].uXQWY5M7()].YZ_2jDn()).ADOElka8)[ !-XsFuN8fPBMJkL().PREjb4MSZ]).E()) { ; } int UbQe9Iz2V8SgHh = -this.X851FHP112JeC() = new void[ -!!!!-new void[ false.I7KCQBhpaIJ].j()].CIb61MJb32f; XkigfbvgNaODL[] SOsPapIcZqW = -ffVy1YZCa8QJ().JXk75Hf29tMQ = new TpXPUwYuPwq1RP()[ !false[ -Ow3dJ3Hn().FiRZINLzhjKdIx]]; while ( tvAzODIRT.y9K()) return; boolean QV_rrmfaG; boolean jT50pyraag5XrL = -true[ -64.L15GW89DBh5qw]; void vcpY1joGS542; while ( false.x()) return; } public static void Uq6PdS (String[] VGJJY) throws zy18r0Zt1SRY { false[ ---!-waJQFObGzJ2a.LgNdBUbufw]; } public static void s (String[] Lsq5dO7Tne4Q3) { int[] Zj1; ; { { void CREr9DI02GDFl; } int I_w6u; IlFKvcJTGHHwW[][][] ygtRIEPcL3; ; while ( -!( !true[ false._96hg()]).ZUM8) while ( -null.UkTGje()) ; while ( !!new boolean[ !jQ7xlUdSb().Ep4][ ZbRprCL1s()[ false.hnLxZN()]]) return; ; int[] clSzMTiihsK2; boolean ZhYy_R5_kQz; if ( this.C) return; { if ( -new qL01BY()[ --!new nfu_PPA4x4[ -true.xlOV7][ !new boolean[ true[ -null.mEC_RBpNN7AC0j()]].uiwwYyH3KHnWOj]]) -!!null.wR2Iun7(); } while ( -null[ 152978.KWpHCCu]) { ; } while ( null.sXaQEqQ_wDi()) ---!C96c6uoAMB().wgm1JlMw4eSwVo(); while ( new int[ -null.PNTMAccEd][ ( new void[ -!new void[ -new w[ !-!!( -new boolean[ new rsKwL9AgcPsC()[ x4[ -null[ !rheEvpGBB8Zq9.mp]]]].gV).nDFbR()][ null[ -!true[ new p().ZX]]]].X4TV0f_xjT8][ !!--!!!66.uLZL()])[ ( -0.H7ZLfSLb())[ !-!-19.uB61e]]]) ; ; int diqGZksmbxFrWw; boolean ZrSEq_vOMdvr; if ( !new void[ !!null.jC0Ri5L()][ new LoYz4().ArZ65LsPkl]) if ( null.QaU()) if ( !!-null.Du7l) if ( this.PE) ; } { int CInxJIjxWOtb0; } return !-!!ioFI()[ ( false[ -!!!new boolean[ !-this.LATeidDFiPlw][ false[ Rzumcxa().rLncdiYhUGYP()]]]).hfHB1dq]; while ( this.Vs3IGb11Ld) if ( !-null[ j8y3pg().xd()]) ; if ( new Zcmt().WW2VZsaKDhgy()) while ( 0050855.Pg5ktFG()) return; void[] E4M7uo6r = JRJ6.CuYb; boolean[][][][] em_E8otB5_H; while ( -747392088.V4IjOL) while ( moFzSRaadTv().Jsil) -new X6wum[ -true.vPwxRpLkG][ OjgWn_.Ugy()]; { void[][] V12Si; boolean K9R2ji; while ( !new kr32ralycl1_tX[ true.b()].vFC()) !7408892.fN6FsudRKzMO; !!null[ -99258201[ -!false.eTu3HER9]]; } int ZxNgC0q; } public boolean[][] kwlCPDGAHZ4l (boolean u5tQR6ezhC, boolean[] YT11JpMnFgeQFM, boolean jrubi0x2zfN, int[] BML5) throws obovTI7gb1xY { { ; if ( 496[ ( false.NAPmLgb_w).H6CL_kzP]) !-0410603[ new X1L().pbraAn]; } if ( J_XuX[ -!new Lmo[ !60309[ this[ false.Xu07Ex5R0()]]].bCQ2DaBPTSAil]) { ; } } public p5ZC6iA1 AWbvIjsu () throws tqGDYkR2TCX2N { return true.jfYaD(); !!!737358.xNWNVde4B_; int HCyg3ehXbIe2m = -dZxpDDUMTWa3()[ !!-false.VlhnY1us]; while ( !!M9pdvfVBsgO.PI6mFLnBfY()) while ( !-new Adb()[ -!-!false.Qxb93YEgRrY3()]) while ( true.x0ugKFWFJfhiX) ; boolean iPXlUO5Lx7 = !-!( !!-!!-new wdSdP7E().ilQlhbPGQH()).R_(); void paZsX = !-( !( qcM().C4OTtx0G66b)[ new int[ -!!-this.IxV0USWDOyLuV].a])[ new wWau5qc[ !new FKTyXoX().cc].TrRVOZ4E] = this.w2A6ZlQAasr(); int dEIUrMoRB4Ps = -new boolean[ !-new mZJHNVq().rYKffYA].V8RfZaOhJg28() = -null.mSqM5JVnD(); boolean rPMPr; { DfmF[] mHl4VNaEx2; while ( !!VIUJmZH.cBmAzgQ) false[ !!-!!new gOduXHl[ new l4[ kAGJimd6hOZy[ null[ false[ false.GOR1ru()]]]].hZ5zNt8UsbP][ !new yQ().RXEJP6ZX_]]; { boolean[] EJUqYhKPXBf; } boolean[][] X; void[] e6wctHZyQx_; ; while ( ( !!-!!false[ !new TCvqTPo9().gvfg5()])[ -!!t9mW5A67h0Rb[ new int[ !---( -new void[ --!-true.dWMHV].NelCn()).LdE11S4oBNsy5o()][ new void[ -this.hECk].gNBeT_XpYtzNV]]]) !--!this.cnC_JTSN7BoI(); S[] QukOw9; int ins8s; int _; kmW p3Pt; } jsxytRZ[ !K5ctlR6[ !true[ new dTx6_r8CQbfFY().hjE]]]; int[] i = !new PcZy2sDqHD6NHA[ -!null[ !( -new int[ !this.WoIdlRR_K0()].GVyuZG1cz).kA]][ false[ 290596.JOAnC]]; int[] h4gPApy; !FqB8AnniO[ false[ !new gKBqU().St2OAfu9]]; boolean lmycOVx = !null[ gvXH6bDu().fU7IthvGQ9AJr()]; new void[ -7.nvUXPNigswO].tqR2(); boolean M6qd7B; while ( ( !!!( new ysxVo()[ new Q19qV4ar0cUu[ -null.Z][ null.lyH5CCEqP()]])[ !-!true.h()])[ 351[ new ojRoUYU().zaALBW]]) return; if ( --!!!!false.oiZiyIgxGAbbHG) 4419[ !!!false.GpDvfJ8nYsc()]; ; return; } public static void w (String[] ScepAWdw9uQ) throws ki4PNh87H { return ( my6()[ 883.yeVwxPwmn4])[ -!-true[ new a()[ -true.e84Mggcg6EU9]]]; } public int kpHkpidSvT () throws j { boolean[] fWA0nJhId1 = -!!-( false[ ( null.W()).cDEJQ68Wozogp1]).wGy = new fC()[ !!-!null.IfBeo()]; { while ( FTEBDKe.dJfc) return; ; int XMBEtS; { boolean[] G_V3; } void u; return; if ( null.UcR_FFUl) ; ; return; MhM[] mZ; this[ ( !!new izjDK2d7oNx5y()[ new boolean[ true.T][ -2.mc]]).ptibVz6El4GYjN]; boolean bCc; { void vaKv; } { return; } } int[][][][][] E = !!!--!null.Tb8Sou4zjs() = !this.M(); void Ul09v; ASVCqp[][][] cmdWPXseX = --!!40454512[ xLwLUbDV036().wqFe()] = r()[ !!!new int[ false[ !!new boolean[ !!77[ null.FENVJzZfIbWLCJ]][ -( false.sd0gDqXc3K).G()]]][ _j.jv1JAuoGXw()]]; int[] Lu = -false.CsQlpX4PW() = false.qM_vgYr(); return; { while ( new LUp().Quc2L()) ; { { void[] LryPp05o2l; } } bD3GyxzJ EkKSWLk1xuil; ; { while ( _WatUct.GKp_xlTWNwBdM5) return; } js HWYzgzztk5Rk; int gAWK6I_4P; boolean[] nF1YVwePCo; { { { { ; } } } } void[][] OSr5L; ; { null[ -!!-( null[ false.sPFGGLBQ])[ h[ ( --new boolean[ ilBs4ePvW3Q2_u().xGcvQf()].cGiQbPsgxwRKvb()).AlgZSG()]]]; } k1Rom4Yv1xr[][] Qp6GFVo2; return; void[][] KwQ7rIEaakkoMi; ; ( !false.jU6GOk())[ 213.zsXl1y0()]; } U[] NpSX5Q2d11PyMe = -DVCiw25Ux.Ig1V19KDX() = !ow3g8JMvRR27tw[ new oXZVp_Q().s_AENQsg1RFyYd()]; boolean B; boolean zefwmXfalq4o; ; { void Li5sR7XnIRz; while ( !!null.J35Qs6KB()) { while ( Sk()[ ( true.H).vd9vDz0yXWRy()]) while ( new V7KYqLecCyePCN().Mew9p5nhxya()) while ( new Ye().tSpst) return; } } KYg[] qkmsoSYk; int[] aYPAsaJwLq; void to = new XGwxKzQRV6q().dX_nfp12jySPfB(); ; int[][] jbJteNIKCisw; } public int bGmgjq2Y () throws LAANzwuf { ; if ( ( P5Vhs2rW().tS8Hh)[ !null.xG_N4bsQMd()]) while ( !----null.imz) ; void[][][][] LT764Rz; } public int xkd (boolean nG3, void wyoIESMmv3yC4, boolean[][] eUj, XIuNQW5fD[] E3UFBswRKDzU, P7UPARHM6B7 tH3daljpo) { void I2_ufL7mmivgf0 = this.Z = true[ -new int[ d4lwkzhlLuQf().lt8hHCIG48Z][ !!-HEMfjjhIdx.CqDw3ofhN]]; boolean[] WnG9; if ( new boolean[ null[ ak()[ false[ !!new J3gUplJ5CiOgoi().zaS5JTRQp()]]]][ -false.FRXiu_l()]) if ( -!-new boolean[ new y().LP5US3pr2()].LGIjMvHF1) -!-DFSrEQGkqi8().V; void O3B9; return --zgaUnRdoJT().PFRs; return; mBsQ863ksQ[] u = new wBi0DMTUuIS().suD9XjodSl() = -43.wBFCimO; ; cXnMikr Y_j0ZFFM = -99[ !!null.jFZeQLue] = -!!969094371[ new XhR2fNCtO9[ true.v4wQlkE8gQ()][ null.ZVHxPzJ1KHUGS()]]; boolean[][] tnfnpUvUl; int[] Z; void z = --new fvP8[ !new K8A47n1n6AR9H().hId8nwQz()].d2F8_zB2WhAlq(); boolean[] VuzB0o1V = ( !true.dfU_I8m).XLBpl() = !false.J; -epkj0e()[ this[ -!( new DfI92dIXK().LsicS()).WLdvC5eR0kjb()]]; boolean[] sbM1; int hEJ = !new int[ null.R0SmBIa()].D5RE(); void[] f; int[] _7jDy8D = ( -new Bfn3buu().L1L3v3uJjEU())[ !false.P2QNnX8dE]; if ( true[ -( --null[ this.R()]).k_5]) { int[][] wqVkUbvzOe; }else ; } public boolean KLS04iH2USgmx; } class W { }
41.45935
265
0.49799
5234e5d7842fac7b2f29143a5f81f2749c65e454
2,098
package com.udacity.superduperdrive.controller; import com.udacity.superduperdrive.model.User; import com.udacity.superduperdrive.model.form.CredentialForm; import com.udacity.superduperdrive.service.CredentialService; import com.udacity.superduperdrive.service.UserService; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping("/credential") public class CredentialController { private final UserService userService; private final CredentialService credentialService; public CredentialController(UserService userService, CredentialService credentialService) { this.userService = userService; this.credentialService = credentialService; } @PostMapping public String post(Authentication authentication, @ModelAttribute("credentialForm") CredentialForm credentialForm, Model model) { User currentUser = userService.getUser(authentication.getName()); Integer rowsAffected; if (credentialForm.getCredentialId() == null) { rowsAffected = credentialService.insertCredential(credentialForm, currentUser.getUserId()); } else { rowsAffected = credentialService.updateCredential(credentialForm, currentUser.getUserId()); } boolean isSuccess = rowsAffected > 0; if (isSuccess) { credentialForm.setUrl(""); credentialForm.setUsername(""); credentialForm.setPassword(""); } model.addAttribute("isSuccess", isSuccess); return "result"; } @RequestMapping(value = "/delete/{credentialId}", method = RequestMethod.GET) public String delete(@PathVariable Integer credentialId, Model model) { Integer rowsAffected = credentialService.deleteCredential(credentialId); boolean isSuccess = rowsAffected > 0; model.addAttribute("isSuccess", isSuccess); return "result"; } }
40.346154
103
0.716397
cc4621d3cd3e82169c77947f09911ac5ae8a8312
378
package aQute.lib.mavenpasswordobfuscator; import junit.framework.TestCase; public class MavenPasswordObfuscatorTest extends TestCase { public void testAgainstMavenEncryptedPassword() throws Exception { String decrypt64 = MavenPasswordObfuscator.decrypt("{YJSiC4rcl1cH2hcwL20EL8wlQwkB2zGvdIGq8x8pX7k=}", "settings.security"); assertEquals("foobar", decrypt64); } }
27
102
0.814815
ce87bfeefc767bf0c5cf1d75544cf18c168a8f11
923
/** * Copyright(c) 2018 * Ulord core developers */ package one.ulord.upaas.uauth.server.contentauth.services; import one.ulord.upaas.common.api.PagingResult; import one.ulord.upaas.uauth.server.contentauth.vo.SensitiveWordItem; import java.util.List; import java.util.Map; /** * @author haibo * @since 5/26/18 */ public interface SensitiveWordService { int createItem(SensitiveWordItem value); int updateItem(SensitiveWordItem value); SensitiveWordItem retrieveItem(long uid); int deleteItem(long uid); List<SensitiveWordItem> loadActive(); PagingResult retrieve(int pageIdx, int pageSize, Map<String, List<String>> criteria); int disableItem(long uid); int enableItem(long uid); SensitiveWordItem select(String keyword); PagingResult selectByItem(int pageIdx, int pageSize, Map<String, List<String>> criteria, String keyword, int level, int disabled, String scene); }
27.147059
148
0.748646
f18c6abad88b85ad1d1661747f4703c522dc6313
3,871
package com.dl7.tag.drawable; import android.animation.ValueAnimator; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.view.animation.AccelerateDecelerateInterpolator; import com.dl7.tag.utils.BitmapUtils; /** * Created by Rukey7 on 2016/12/5. * 旋转动画 Drawable */ public class RotateDrawable extends Drawable implements Animatable { private Paint mPaint; // 绘制的矩形框 private RectF mRect = new RectF(); // 动画控制 private ValueAnimator mValueAnimator; // 旋转角度 private float mRotate; // icon private Bitmap mBitmap; // 偏移 private int mTranslationX; private int mTranslationY; public RotateDrawable(Bitmap bitmap) { mBitmap = bitmap; mPaint = new Paint(); mPaint.setAntiAlias(true); } @Override public void draw(Canvas canvas) { canvas.translate(mTranslationX, mTranslationY); canvas.rotate(mRotate, mRect.width() / 2, mRect.height() / 2); canvas.drawPaint(mPaint); } @Override public void setAlpha(int alpha) { mPaint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter colorFilter) { mPaint.setColorFilter(colorFilter); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } @Override protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); mRect.set(_clipSquare(bounds)); mTranslationX = (int) mRect.left; mTranslationY = (int) mRect.top; // 缩放 Bitmap Bitmap zoom = BitmapUtils.zoom(mBitmap, bounds.width(), bounds.height()); BitmapShader bitmapShader = new BitmapShader(zoom, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); mPaint.setShader(bitmapShader); if (isRunning()) { stop(); } // 设置动画 mValueAnimator = ValueAnimator.ofFloat(0, 2880).setDuration(2000); mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { boolean isOver = false; @Override public void onAnimationUpdate(ValueAnimator animation) { mRotate = (float) animation.getAnimatedValue(); if (mRotate <= 2160) { isOver = false; } else if (!isOver) { isOver = true; mRotate = 2160; } invalidateSelf(); } }); // 设置动画无限循环 mValueAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); mValueAnimator.setRepeatMode(ValueAnimator.RESTART); mValueAnimator.setRepeatCount(ValueAnimator.INFINITE); start(); } /** * 裁剪Rect为正方形 * @param rect * @return */ private Rect _clipSquare(Rect rect) { int w = rect.width(); int h = rect.height(); int min = Math.min(w, h); int cx = rect.centerX(); int cy = rect.centerY(); int r = min / 2; return new Rect( cx - r, cy - r, cx + r, cy + r ); } /** * ==================================== 显示模式 ==================================== */ @Override public void start() { mValueAnimator.start(); } @Override public void stop() { mValueAnimator.end(); } @Override public boolean isRunning() { return mValueAnimator != null && mValueAnimator.isRunning(); } }
26.881944
105
0.595712
3a496846538d3bdf6466555df94be1b8fdcd5497
2,532
package com.suda.jzapp.ui.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.suda.jzapp.R; import com.suda.jzapp.manager.RecordManager; import com.suda.jzapp.manager.domain.RecordDetailDO; import com.suda.jzapp.misc.IntentConstant; import com.suda.jzapp.ui.adapter.NewRecordDetailAdapter; import java.util.List; /** * Created by suda on 2016/8/4. */ public class RecordDetailFrg extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); recordManager = new RecordManager(getActivity()); if (getArguments() != null) { recordTypeId = getArguments().getLong(IntentConstant.RECORD_TYPE_ID); year = getArguments().getInt(IntentConstant.RECORD_YEAR); month = getArguments().getInt(IntentConstant.RECORD_MONTH); } } @Override public void onResume() { super.onResume(); recordDetails = recordManager.getRecordsByRecordTypeIDAndMonth(recordTypeId, year, month); mAccountRecordAdapter = new NewRecordDetailAdapter(getActivity(), recordDetails); mRecordLv.setLayoutManager(new LinearLayoutManager(getActivity())); mRecordLv.setAdapter(mAccountRecordAdapter); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.frg_record_detail, container, false); mRecordLv = (RecyclerView) view.findViewById(R.id.records); return view; } public static RecordDetailFrg newInstance(int year, int month, long recordTypeId) { RecordDetailFrg tabFragment = new RecordDetailFrg(); Bundle bundle = new Bundle(); bundle.putInt(IntentConstant.RECORD_YEAR, year); bundle.putInt(IntentConstant.RECORD_MONTH, month); bundle.putLong(IntentConstant.RECORD_TYPE_ID, recordTypeId); tabFragment.setArguments(bundle); return tabFragment; } private int year = 2016; private int month = 1; private long recordTypeId = 0; private RecyclerView mRecordLv; private NewRecordDetailAdapter mAccountRecordAdapter; private List<RecordDetailDO> recordDetails; private RecordManager recordManager; }
35.166667
98
0.723144
381d8f6f3025284597f6ba64be3e8d9067efe67d
2,918
/* Copyright 2021 aholinch 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 odutils.util; import java.io.File; import java.util.logging.Logger; public class ODConfig { private static final Logger logger = Logger.getLogger(ODConfig.class.getName()); private static ODConfig instance = null; private static final String sync = "mutex"; protected String orekitDataDir = null; private ODConfig() { // load from properties } public static ODConfig getInstance() { if(instance == null) { synchronized(sync) { // yes check again if(instance == null) { instance = new ODConfig(); } } } return instance; } public String getOrekitDataDir() { if(orekitDataDir == null) { File f = searchExistingDir("orekit-data","orekit-data-master","orekit_data","orekit.data"); if(f != null) { orekitDataDir = f.getAbsolutePath(); } } return orekitDataDir; } /** * Looks in env param, java define param, running dir, and then home for directory. * * @param dirEnd * @param env * @param param * @return */ protected File searchExistingDir(String name1, String name2, String env, String param) { File f = null; String path = null; // check env first if(env != null) { path = System.getenv(env); if(path != null) { f = new File(path); } } if(f==null || !f.exists()) { // check define param if(param != null) { path = System.getProperty(param); if(path != null) { f = new File(path); } } } if(f == null || !f.exists()) { // check home directory final File home = new File(System.getProperty("user.home")); f = new File(home,name1); if(!f.exists() && name2 != null) { f = new File(home,name2); } } if(f == null || !f.exists()) { // check current directory f = new File(name1); if(!f.exists() && name2 != null) { f = new File(name2); } } if(f == null || !f.exists()) { logger.warning("Unable to find dir for " + String.valueOf(name1) + " after checking multiple places"); } return f; } }
22.274809
108
0.567169
5b08ce12e1a9393dd2a23d68564affa05e8f2221
3,093
/* * Copyright 2014-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package griffon.plugins.domain.orm; import javax.annotation.Nonnull; import javax.annotation.concurrent.ThreadSafe; import static griffon.util.GriffonNameUtils.requireNonBlank; import static java.util.Objects.requireNonNull; /** * @author Andres Almiray */ @ThreadSafe public final class PropertyExpression implements Criterion { private final String propertyName; private final Operator operator; private final String otherPropertyName; public PropertyExpression(@Nonnull String propertyName, @Nonnull Operator operator, @Nonnull String otherPropertyName) { this.propertyName = requireNonBlank(propertyName, "Argument 'propertyName' cannot be blank"); this.operator = requireNonNull(operator, "Argument 'operator' must not be null"); this.otherPropertyName = requireNonBlank(otherPropertyName, "Argument 'otherPropertyName' cannot be blank"); } @Nonnull public String getPropertyName() { return propertyName; } @Nonnull public String getOtherPropertyName() { return otherPropertyName; } @Nonnull public Operator getOperator() { return operator; } public String toString() { return propertyName + " " + operator + " " + otherPropertyName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PropertyExpression that = (PropertyExpression) o; boolean straight = otherPropertyName.equals(that.otherPropertyName) && propertyName.equals(that.propertyName); boolean mixed = otherPropertyName.equals(that.propertyName) && propertyName.equals(that.otherPropertyName); boolean props = straight; switch (operator) { case EQUAL: case NOT_EQUAL: props = straight || mixed; break; } return operator == that.operator && props; } @Override public int hashCode() { int result = operator.hashCode(); switch (operator) { case EQUAL: case NOT_EQUAL: result = 31 * result + propertyName.hashCode() + otherPropertyName.hashCode(); break; default: result = 31 * result + propertyName.hashCode(); result = 31 * result + otherPropertyName.hashCode(); } return result; } }
32.21875
124
0.66117
53b94deec827a2d3025a78ee8289533992da512a
165
package com.beetle.im; /** * Created by houxh on 14-7-23. */ public interface IMServiceObserver { public void onConnectState(IMService.ConnectState state); }
18.333333
61
0.733333
ff05d1a5881ed24a7942e968370f15a463c23123
1,297
package ezain.poc.oauth2.config; import com.google.common.collect.Maps; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import com.google.inject.servlet.ServletModule; import com.googlecode.objectify.ObjectifyFilter; import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; import java.util.Map; import static org.glassfish.jersey.servlet.ServletProperties.JAXRS_APPLICATION_CLASS; /** * Application listener. <p/> * Intercept /api requests and sends them to ItellicolocApp. <p/> * Use GuiceModule for dependency injection. <p/> */ public class MyGuiceServletContextListener extends GuiceServletContextListener { protected Injector getInjector() { final Map<String, String> params = Maps.newHashMap(); params.put(JAXRS_APPLICATION_CLASS, Oauth2App.class.getCanonicalName()); return Guice.createInjector( new GuiceModule(), new ServletModule() { @Override protected void configureServlets() { filter("/auth/*").through(ObjectifyFilter.class); serve("/auth/*").with(GuiceContainer.class, params); } }); } }
31.634146
85
0.67926
a34a6fe31876fdb93f6513ce6b603f364c6161af
5,732
/* * 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.component.cxf.jaxrs; import java.lang.reflect.Method; import java.util.Map; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MultivaluedMap; import org.apache.camel.BindToRegistry; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.cxf.CXFTestSupport; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; /** * Tests different binding configuration options of the CXFRS consumer. */ public class CxfRsBindingConfigurationSelectionTest extends CamelTestSupport { private static final String RESOURCE_CLASS = "resourceClasses=org.apache.camel.component.cxf.jaxrs.simplebinding.testbean.CustomerServiceResource"; private static final String CXF_RS_ENDPOINT_URI_CUSTOM = String.format("cxfrs://http://localhost:%s/CxfRsConsumerTest/rest?bindingStyle=Custom&", CXFTestSupport.getPort2()) + RESOURCE_CLASS + "&binding=#binding"; private static final String CXF_RS_ENDPOINT_URI_SIMPLE = String.format("cxfrs://http://localhost:%s/CxfRsConsumerTest/rest?bindingStyle=SimpleConsumer&", CXFTestSupport.getPort1()) + RESOURCE_CLASS; private static final String CXF_RS_ENDPOINT_URI_DEFAULT = String.format("cxfrs://http://localhost:%s/CxfRsConsumerTest/rest?bindingStyle=Default&", CXFTestSupport.getPort3()) + RESOURCE_CLASS; private static final String CXF_RS_ENDPOINT_URI_NONE = String.format("cxfrs://http://localhost:%s/CxfRsConsumerTest/rest?", CXFTestSupport.getPort4()) + RESOURCE_CLASS; @BindToRegistry("binding") private DummyCxfRsBindingImplementation dummyCxfRsBindingImplementation = new DummyCxfRsBindingImplementation(); @Test public void testCxfRsBindingConfiguration() { // check binding styles assertEquals(BindingStyle.Custom, endpointForRouteId("custom").getBindingStyle()); assertEquals(BindingStyle.SimpleConsumer, endpointForRouteId("simple").getBindingStyle()); assertEquals(BindingStyle.Default, endpointForRouteId("default").getBindingStyle()); assertEquals(BindingStyle.Default, endpointForRouteId("none").getBindingStyle()); // check binding implementations assertEquals(DummyCxfRsBindingImplementation.class, endpointForRouteId("custom").getBinding().getClass()); assertEquals(SimpleCxfRsBinding.class, endpointForRouteId("simple").getBinding().getClass()); assertEquals(DefaultCxfRsBinding.class, endpointForRouteId("default").getBinding().getClass()); assertEquals(DefaultCxfRsBinding.class, endpointForRouteId("default").getBinding().getClass()); } private CxfRsEndpoint endpointForRouteId(String routeId) { return (CxfRsEndpoint) context.getRoute(routeId).getConsumer().getEndpoint(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { from(CXF_RS_ENDPOINT_URI_CUSTOM).routeId("custom") .to("log:foo"); from(CXF_RS_ENDPOINT_URI_SIMPLE).routeId("simple") .to("log:foo"); from(CXF_RS_ENDPOINT_URI_DEFAULT).routeId("default") .to("log:foo"); from(CXF_RS_ENDPOINT_URI_NONE).routeId("none") .to("log:foo"); } }; } private final class DummyCxfRsBindingImplementation implements CxfRsBinding { @Override public void populateExchangeFromCxfRsRequest(org.apache.cxf.message.Exchange cxfExchange, Exchange camelExchange, Method method, Object[] paramArray) { } @Override public Object populateCxfRsResponseFromExchange(Exchange camelExchange, org.apache.cxf.message.Exchange cxfExchange) throws Exception { return null; } @Override public Object bindResponseToCamelBody(Object response, Exchange camelExchange) throws Exception { return null; } @Override public Map<String, Object> bindResponseHeadersToCamelHeaders(Object response, Exchange camelExchange) throws Exception { return null; } @Override public Entity<Object> bindCamelMessageToRequestEntity(Object body, Message camelMessage, Exchange camelExchange) { return null; } @Override public Object bindCamelMessageBodyToRequestBody(Message camelMessage, Exchange camelExchange) throws Exception { return null; } @Override public MultivaluedMap<String, String> bindCamelHeadersToRequestHeaders(Map<String, Object> camelHeaders, Exchange camelExchange) throws Exception { return null; } } }
45.492063
196
0.708828
7b52e41354e6cb55b1486bed5909a089e0493e4f
1,557
package com.cjy.flb.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.cjy.flb.R; import java.util.ArrayList; /** * Created by Administrator on 2016/1/4 0004. */ public class MProblemAdapter extends BaseAdapter { private LayoutInflater inflater; private ArrayList<String> list; public MProblemAdapter(Context context, ArrayList<String> medicList) { this.list = medicList; inflater = LayoutInflater.from(context); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = inflater.inflate(R.layout.item_mproblem_adapter, null); holder.mTextName = (TextView) convertView.findViewById(R.id.textView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } String str = list.get(position).split("/")[0]; holder.mTextName.setText(str); return convertView; } class ViewHolder { TextView mTextName; } }
23.953846
82
0.653179
77e984b50e97fc78c587eab515407e038792a94d
7,637
package com.alphasta.commons.utils; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * excel工具 * * @author LiYunhao * */ public class ExcelUtils { /** * 读取excel * * @param is * 输入流 * @param fileName * 文件名称(包含后缀名) * @return * @throws Exception */ public static ExcelInfo readExcel(InputStream is, String fileName) throws Exception { ExcelInfo excelInfo = new ExcelInfo(); //获取文件名 String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); //xls格式 if ("xls".equals(suffix)) { excelInfo = readXls(is); //xlsx格式 } else if ("xlsx".equals(suffix)) { excelInfo = readXlsx(is); } else { throw new Exception("未知文件类型"); } return excelInfo; } /** * 读取xls信息 * * @param is * @return * @throws IOException */ //HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xls private static ExcelInfo readXls(InputStream is) throws IOException { int null_num=0; ExcelInfo excelInfo = new ExcelInfo(); // 通过poi读取流 HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is); //sheets Map<String, List<Map<Integer, String>>> sheets = new HashMap<String, List<Map<Integer, String>>>(); // 获取excel中的sheet数量 int numberOfSheets = hssfWorkbook.getNumberOfSheets(); //遍历sheet for (int i = 0; i < numberOfSheets; i++) { //获取sheet类 HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(i); if (hssfSheet == null) { continue; } //创建行 List<Map<Integer, String>> rows = new ArrayList<Map<Integer, String>>(); //最后一行行标 int lastRowNum = hssfSheet.getLastRowNum(); //遍历所有行 for (int j = 0; j <= lastRowNum; j++) { //或取行 HSSFRow hssfRow = hssfSheet.getRow(j); if (hssfRow != null) { if(hssfRow.getCell(0)==null) { null_num+=1; continue; } Map<Integer, String> row = new HashMap<Integer, String>(); // 获取列数 short lastCellNum = hssfRow.getLastCellNum(); for (int k = 0; k < lastCellNum; k++) { if(hssfRow.getCell(k)==null) continue; hssfRow.getCell(k).setCellType(CellType.STRING); row.put(k, hssfRow.getCell(k).getStringCellValue()); } rows.add(row); } } sheets.put(hssfSheet.getSheetName(), rows); } //存储值 类型Map<String, List<Map<Integer, String>>> excelInfo.setSheets(sheets); if(null_num!=0){ excelInfo.setMsg("没有填序号的案件"+null_num+"条"); } return excelInfo; } /** * 读取xlsx信息 * * @param is * @return * @throws IOException */ private static ExcelInfo readXlsx(InputStream is) throws IOException { ExcelInfo excelInfo = new ExcelInfo(); // 通过poi读取流 XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is); //读取sheet标签 Map<String, List<Map<Integer, String>>> sheets = new HashMap<String, List<Map<Integer, String>>>(); // 获取excel中的sheet int numberOfSheets = xssfWorkbook.getNumberOfSheets(); for (int i = 0; i < numberOfSheets; i++) { XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(i); if (xssfSheet == null) { continue; } List<Map<Integer, String>> rows = new ArrayList<Map<Integer, String>>(); // 获取sheet中的行 int lastRowNum = xssfSheet.getLastRowNum(); System.out.println(lastRowNum); for (int j = 0; j <= lastRowNum; j++) { //获取行数据 XSSFRow xssfRow = xssfSheet.getRow(j); if(xssfRow != null){ Map<Integer, String> row = new HashMap<Integer, String>(); // 获取行中的单元格 short lastCellNum = xssfRow.getLastCellNum(); for (int k = 0; k < lastCellNum; k++) { //如果没有序号则不加载本行 // 把单元格类型转成string类型 xssfRow.getCell(k).setCellType(CellType.STRING); row.put(k, xssfRow.getCell(k).getStringCellValue()); } //处理表格空字符串 boolean value = false; for (Integer in : row.keySet()) { String str = row.get(in); if(!str.equals("")){ value=true; } } if(value){ rows.add(row); value = false; } if(rows.size()==3){ rows.get(1).put(14, rows.get(2).get(14)); rows.get(1).put(15, rows.get(2).get(15)); rows.get(1).put(16, rows.get(2).get(16)); rows.get(1).put(17, rows.get(2).get(17)); rows.get(1).put(18, rows.get(2).get(18)); } }else{ continue; } } sheets.put(xssfSheet.getSheetName(), rows); System.out.println("rsjL:"+rows); } excelInfo.setSheets(sheets); return excelInfo; } /** * 专家信息读取xls信息 * * @param is * @return * @throws IOException */ private static ExcelInfo readZjks(InputStream is) throws IOException { ExcelInfo excelInfo = new ExcelInfo(); // 通过poi读取流 HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is); Map<String, List<Map<Integer, String>>> sheets = new HashMap<String, List<Map<Integer, String>>>(); System.out.println("LLLLLLLLLLLLLLLLLLLLLLLLLL=sheets=LL:"+sheets); // 获取excel中的sheet int numberOfSheets = hssfWorkbook.getNumberOfSheets(); for (int i = 0; i < numberOfSheets; i++) { HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(i); if (hssfSheet == null) { continue; } List<Map<Integer, String>> rows = new ArrayList<Map<Integer, String>>(); // 获取sheet中的行 int lastRowNum = hssfSheet.getLastRowNum(); for (int j = 0; j <= lastRowNum; j++) { HSSFRow hssfRow = hssfSheet.getRow(j); if (hssfRow != null) { Map<Integer, String> row = new HashMap<Integer, String>(); // 获取行中的单元格 short lastCellNum = hssfRow.getLastCellNum(); for (int k = 1; k < lastCellNum; k++) { // 把单元格类型转成string类型 hssfRow.getCell(k).setCellType(CellType.STRING); row.put(k, hssfRow.getCell(k).getStringCellValue()); } rows.add(row); } } sheets.put(hssfSheet.getSheetName(), rows); } excelInfo.setSheets(sheets); return excelInfo; } public static void main(String[] args) { Map<String,String>map = new HashMap<String, String>(); map.put("1", "任胜杰1"); map.put("1", "任红雨"); System.out.println(map.get("1")); } /** * 读取xlsx信息 * * @param is * @return * @throws IOException */ private static ExcelInfo readZjkx(InputStream is) throws IOException { ExcelInfo excelInfo = new ExcelInfo(); // 通过poi读取流 XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is); Map<String, List<Map<Integer, String>>> sheets = new HashMap<String, List<Map<Integer, String>>>(); // 获取excel中的sheet int numberOfSheets = xssfWorkbook.getNumberOfSheets(); for (int i = 0; i < numberOfSheets; i++) { XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(i); if (xssfSheet == null) { continue; } List<Map<Integer, String>> rows = new ArrayList<Map<Integer, String>>(); // 获取sheet中的行 int lastRowNum = xssfSheet.getLastRowNum(); for (int j = 0; j <= lastRowNum; j++) { XSSFRow xssfRow = xssfSheet.getRow(j); if (xssfRow != null) { Map<Integer, String> row = new HashMap<Integer, String>(); // 获取行中的单元格 short lastCellNum = xssfRow.getLastCellNum(); for (int k = 1; k < lastCellNum; k++) { // 把单元格类型转成string类型 xssfRow.getCell(k).setCellType(CellType.STRING); row.put(k, xssfRow.getCell(k).getStringCellValue()); } rows.add(row); } } sheets.put(xssfSheet.getSheetName(), rows); } excelInfo.setSheets(sheets); return excelInfo; } }
26.609756
101
0.646196
16a5b7aae58188ef0696b2d45870921634111380
2,482
/* * Copyright 2021 LinkedIn Corp. * Licensed under the BSD 2-Clause License (the "License"). * See License in the project root for license information. */ package com.linkedin.avroutil1.spotbugs; import com.linkedin.avroutil1.testcommon.TestUtil; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.test.SpotBugsRule; import edu.umd.cs.findbugs.test.matcher.BugInstanceMatcher; import edu.umd.cs.findbugs.test.matcher.BugInstanceMatcherBuilder; import org.hamcrest.MatcherAssert; import org.junit.Rule; import org.junit.Test; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import static edu.umd.cs.findbugs.test.CountMatcher.containsExactly; public class OldSchemaConstructableUsageDetectorTest { @Rule public SpotBugsRule spotbugs = new SpotBugsRule(); //only compiles under avro < 1.6 @Test public void testBadCase() throws Exception { List<Path> classFiles = TestUtil.findClassFiles("build/classes/java/test", BadClass.class); BugCollection bugCollection = spotbugs.performAnalysis(classFiles.toArray(new Path[0])); BugInstanceMatcher bugTypeMatcher = new BugInstanceMatcherBuilder() .bugType("OLD_SCHEMACONSTRUCTABLE_USAGE") .inMethod("useOldSchemaConstructable").build(); //some of our bugs get deduped MatcherAssert.assertThat(bugCollection, containsExactly(2, bugTypeMatcher)); bugTypeMatcher = new BugInstanceMatcherBuilder() .bugType("OLD_SCHEMACONSTRUCTABLE_USAGE") .inClass(BadClass.OldSchemaConstructable.class.getName()).build(); MatcherAssert.assertThat(bugCollection, containsExactly(1, bugTypeMatcher)); bugTypeMatcher = new BugInstanceMatcherBuilder() .bugType("OLD_SCHEMACONSTRUCTABLE_USAGE") .inMethod("useOldSchemaConstructableSomeMore").build(); MatcherAssert.assertThat(bugCollection, containsExactly(1, bugTypeMatcher)); } @Test public void testGoodCase() { Path path = Paths.get("build/classes/java/test", GoodClass.class.getName().replace('.', '/') + ".class"); BugCollection bugCollection = spotbugs.performAnalysis(path); BugInstanceMatcher bugTypeMatcher = new BugInstanceMatcherBuilder() .bugType("OLD_SCHEMACONSTRUCTABLE_USAGE") .build(); MatcherAssert.assertThat(bugCollection, containsExactly(0, bugTypeMatcher)); } }
40.032258
113
0.722401
380f73f672c6c2f26a98db977ad79d0aa6784ac2
4,680
package com.inepex.example.ContactManager.entity.kvo; import com.google.inject.Inject; import com.inepex.ineom.shared.AssistedObjectHandler; import com.inepex.ineom.shared.IneList; import com.inepex.ineom.shared.Relation; import com.inepex.ineom.shared.assistedobject.AssistedObject; import com.inepex.ineom.shared.assistedobject.KeyValueObject; import com.inepex.ineom.shared.descriptorstore.DescriptorStore; public class CompanyHandlerFactory { private final DescriptorStore descriptorStore; /** * can be injected or created with 'new CompanyHandlerFactory(decStore)' */ @Inject public CompanyHandlerFactory(DescriptorStore descriptorStore) { this.descriptorStore = descriptorStore; } public CompanyHandler createHandler() { AssistedObject assistedObject = new KeyValueObject(CompanyConsts.descriptorName); return new CompanyHandler(assistedObject, descriptorStore); } public CompanyHandler createHandler(AssistedObject assistedObject) { if (!CompanyConsts.descriptorName.equals(assistedObject.getDescriptorName())) throw new IllegalArgumentException( "Type incompatibility: handler: '" + CompanyConsts.descriptorName + "' assistedObject: '" + assistedObject.getDescriptorName() + "'"); return new CompanyHandler(assistedObject, descriptorStore); } public CompanySearchHandler createSearchHandler() { AssistedObject assistedObject = new KeyValueObject(CompanyConsts.searchDescriptor); return new CompanySearchHandler(assistedObject, descriptorStore); } public CompanySearchHandler createSearchHandler(AssistedObject assistedObject) { if (!CompanyConsts.searchDescriptor.equals(assistedObject.getDescriptorName())) throw new IllegalArgumentException( "Type incompatibility: handler: '" + CompanyConsts.searchDescriptor + "' assistedObject: '" + assistedObject.getDescriptorName() + "'"); return new CompanySearchHandler(assistedObject, descriptorStore); } public static class CompanyHandler extends AssistedObjectHandler { private CompanyHandler(AssistedObject assistedObject, DescriptorStore descriptorStore) { super(assistedObject, descriptorStore); } public String getName() { return getString(CompanyConsts.k_name); } public void setName(String name) { set(CompanyConsts.k_name, name); } public String getPhone() { return getString(CompanyConsts.k_phone); } public void setPhone(String phone) { set(CompanyConsts.k_phone, phone); } public String getEmail() { return getString(CompanyConsts.k_email); } public void setEmail(String email) { set(CompanyConsts.k_email, email); } public String getWebPage() { return getString(CompanyConsts.k_webPage); } public void setWebPage(String webPage) { set(CompanyConsts.k_webPage, webPage); } public IneList getContacts() { return getList(CompanyConsts.k_contacts); } public void setContacts(IneList contacts) { set(CompanyConsts.k_contacts, contacts); } public Relation getExtData() { return getRelation(CompanyConsts.k_extData); } public void setExtData(Relation extData) { set(CompanyConsts.k_extData, extData); } } public static class CompanySearchHandler extends AssistedObjectHandler { private CompanySearchHandler( AssistedObject assistedObject, DescriptorStore descriptorStore) { super(assistedObject, descriptorStore); } public String getName() { return getString(CompanyConsts.s_name); } public void setName(String name) { set(CompanyConsts.s_name, name); } public String getPhone() { return getString(CompanyConsts.s_phone); } public void setPhone(String phone) { set(CompanyConsts.s_phone, phone); } public String getEmail() { return getString(CompanyConsts.s_email); } public void setEmail(String email) { set(CompanyConsts.s_email, email); } public String getWebPage() { return getString(CompanyConsts.s_webPage); } public void setWebPage(String webPage) { set(CompanyConsts.s_webPage, webPage); } } }
31.836735
96
0.657692
b983987ec6253a0297901330da0f57a71856c271
615
package com.zutubi.android.ant; /** * Removes a uses-permission element with a given permission name from the * manifest, if present. */ public class RemoveUsedPermissionTask extends AbstractManifestUpdateTask { private String permission; /** * Sets the name of the permission to remove. * * @param permission name of the permission to remove */ public void setPermission(final String permission) { this.permission = permission; } @Override protected void updateManifest(final Manifest manifest) { manifest.removeUsedPermission(permission); } }
25.625
74
0.702439
82da4a214b4668d8a11f17d743a9fdb86b1b4482
8,775
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.guvnor.ala.docker.executor; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import javax.inject.Inject; import com.spotify.docker.client.DockerException; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.PortBinding; import org.guvnor.ala.config.Config; import org.guvnor.ala.config.RuntimeConfig; import org.guvnor.ala.docker.access.DockerAccessInterface; import org.guvnor.ala.docker.config.DockerRuntimeConfig; import org.guvnor.ala.docker.config.DockerRuntimeExecConfig; import org.guvnor.ala.docker.model.DockerProvider; import org.guvnor.ala.docker.model.DockerRuntime; import org.guvnor.ala.docker.model.DockerRuntimeEndpoint; import org.guvnor.ala.docker.model.DockerRuntimeInfo; import org.guvnor.ala.docker.model.DockerRuntimeState; import org.guvnor.ala.exceptions.ProvisioningException; import org.guvnor.ala.pipeline.FunctionConfigExecutor; import org.guvnor.ala.registry.RuntimeRegistry; import org.guvnor.ala.runtime.RuntimeBuilder; import org.guvnor.ala.runtime.RuntimeDestroyer; import org.guvnor.ala.runtime.RuntimeId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.guvnor.ala.runtime.RuntimeState.RUNNING; import static org.guvnor.ala.util.RuntimeConfigHelper.buildRuntimeName; public class DockerRuntimeExecExecutor<T extends DockerRuntimeConfig> implements RuntimeBuilder<T, DockerRuntime>, RuntimeDestroyer, FunctionConfigExecutor<T, DockerRuntime> { private final RuntimeRegistry runtimeRegistry; private final DockerAccessInterface docker; protected static final Logger LOG = LoggerFactory.getLogger(DockerRuntimeExecExecutor.class); @Inject public DockerRuntimeExecExecutor(final RuntimeRegistry runtimeRegistry, final DockerAccessInterface docker) { this.runtimeRegistry = runtimeRegistry; this.docker = docker; } @Override public Optional<DockerRuntime> apply(final DockerRuntimeConfig config) { final Optional<DockerRuntime> runtime = create(config); runtime.ifPresent(runtimeRegistry::registerRuntime); return runtime; } private Optional<DockerRuntime> create(final DockerRuntimeConfig runtimeConfig) throws ProvisioningException { if (runtimeConfig.isPull()) { try { LOG.info("Pulling Docker Image: " + runtimeConfig.getImage()); docker.getDockerClient(runtimeConfig.getProviderId()).pull(runtimeConfig.getImage()); } catch (DockerException | InterruptedException ex) { LOG.error(ex.getMessage(), ex); throw new ProvisioningException("Error Pulling Docker Image: " + runtimeConfig.getImage() + "with error: " + ex.getMessage()); } } final String[] ports = {runtimeConfig.getPort()}; final Map<String, List<PortBinding>> portBindings = new HashMap<>(); final Optional<DockerProvider> _dockerProvider = runtimeRegistry.getProvider(runtimeConfig.getProviderId(), DockerProvider.class); if (!_dockerProvider.isPresent()) { return Optional.empty(); } final DockerProvider dockerProvider = _dockerProvider.get(); final List<PortBinding> randomPort = new ArrayList<>(); final PortBinding randomPortBinding = PortBinding.randomPort(dockerProvider.getConfig().getHostIp()); randomPort.add(randomPortBinding); portBindings.put(runtimeConfig.getPort(), randomPort); final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build(); final ContainerConfig containerConfig = ContainerConfig.builder() .hostConfig(hostConfig) .image(runtimeConfig.getImage()) .exposedPorts(ports) .build(); final ContainerCreation creation; try { creation = docker.getDockerClient(runtimeConfig.getProviderId()).createContainer(containerConfig); docker.getDockerClient(runtimeConfig.getProviderId()).startContainer(creation.id()); } catch (DockerException | InterruptedException ex) { LOG.error(ex.getMessage(), ex); throw new ProvisioningException("Error Creating Docker Container with image: " + runtimeConfig.getImage() + "with error: " + ex.getMessage(), ex); } final String id = creation.id(); String shortId = id.substring(0, 12); String host = ""; try { docker.getDockerClient(runtimeConfig.getProviderId()).inspectContainer(id); host = docker.getDockerClient(runtimeConfig.getProviderId()).getHost(); } catch (DockerException | InterruptedException ex) { throw new ProvisioningException("Error Getting Docker Container info: " + id + "with error: " + ex.getMessage(), ex); } DockerRuntimeEndpoint dockerRuntimeEndpoint = new DockerRuntimeEndpoint(); dockerRuntimeEndpoint.setHost(host); dockerRuntimeEndpoint.setPort(Integer.valueOf(runtimeConfig.getPort())); dockerRuntimeEndpoint.setContext(""); return Optional.of(new DockerRuntime(shortId, buildRuntimeName(runtimeConfig, shortId), runtimeConfig, dockerProvider, dockerRuntimeEndpoint, new DockerRuntimeInfo(), new DockerRuntimeState(RUNNING, new Date().toString()))); } @Override public Class<? extends Config> executeFor() { return DockerRuntimeExecConfig.class; } @Override public String outputId() { return "docker-runtime"; } @Override public boolean supports(final RuntimeConfig config) { return config instanceof DockerRuntimeConfig; } @Override public boolean supports(final RuntimeId runtimeId) { return runtimeId instanceof DockerRuntime || runtimeRegistry.getRuntimeById(runtimeId.getId()) instanceof DockerRuntime; } @Override public void destroy(final RuntimeId runtimeId) { try { LOG.info("Killing Container: " + runtimeId.getId()); docker.getDockerClient(runtimeId.getProviderId()).killContainer(runtimeId.getId()); LOG.info("Removing Container: " + runtimeId.getId()); docker.getDockerClient(runtimeId.getProviderId()).removeContainer(runtimeId.getId()); runtimeRegistry.deregisterRuntime(runtimeId); } catch (DockerException | InterruptedException ex) { LOG.debug(ex.getMessage(), ex); try { // Trying to remove the container if it cannot be killed LOG.info("Attempting to Remove Container without Killing: " + runtimeId.getId()); docker.getDockerClient(runtimeId.getProviderId()).removeContainer(runtimeId.getId()); runtimeRegistry.deregisterRuntime(runtimeId); } catch (DockerException | InterruptedException ex2) { LOG.error(ex.getMessage(), ex2); throw new ProvisioningException("Error destroying Docker Runtime: " + ex.getMessage(), ex2); } } } }
44.770408
153
0.64114