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
55f87419177aa26a56706f29085829e32bba0811
2,891
//Project name: Breath of the Bull //Description: Breath of the Bull is an Android mobile application that provides //Zen-based support and techniques such as mindfulness exercises, daily quotes //from Zen masters, and guided meditation sessions to help alleviate stress and anxiety. //Filename: MainActivity.java //Description: This is the file that controls the home screen of the breath of the bull app //Last modified on: 4/24/19 package com.example.breath_of_the_bull; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); //listen for meditate button to be pressed, and bring user to meditation session on press Button meditate = (Button) findViewById(R.id.meditate); meditate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openMeditate(); } }); //listen for quote button to be pressed, and bring user to daily quote activity on press Button quote = (Button) findViewById(R.id.quote); quote.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { openQuote(); } }); } //bring user to meditation session screen public void openMeditate() { Intent intent = new Intent(this, Meditate.class); startActivity(intent); } //bring user to daily quote screen public void openQuote() { Intent intent = new Intent(this, Quote.class); startActivity(intent); } //Code generated by Android Studio @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } //Code generated by Android Studio @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
34.831325
97
0.677966
d17c7b032a496097aa4f61316be0609773deea33
4,738
/* * Copyright (C) 2015 fuwjax.org ([email protected]) * * 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.fuwjax.oss.test; import org.fuwjax.oss.util.io.ByteCountingInputStream; import org.fuwjax.oss.util.io.IntReader; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.Arrays; import static org.fuwjax.oss.util.assertion.Assertions.assertThat; import static org.fuwjax.oss.util.assertion.Assertions.is; public class Utf8ReaderTest { private static final Charset UTF_8 = Charset.forName("UTF-8"); @Test public void testReader() throws IOException { for (int cp = 0; cp < Character.MAX_CODE_POINT; cp++) { if (Character.isDefined(cp) && !Character.isHighSurrogate((char) cp) && !Character.isLowSurrogate((char) cp)) { assertCodepoint(cp, cp); assertThat(realcode(cp), is(fauxcode(cp))); } } } @Test public void testInvalid() throws IOException { // continuation bytes with no leading byte is invalid for (int i = 0x80; i < 0xC0; i++) { assertEncoding(fauxcode(i, 1), 0xFFFD); } // overlong sequences are invalid for (int i = 0; i < 1 << 7; i++) { assertEncoding(fauxcode(i, 2), 0xFFFD); assertEncoding(fauxcode(i, 3), 0xFFFD); assertEncoding(fauxcode(i, 4), 0xFFFD); } for (int i = 1 << 7; i < 1 << 11; i++) { assertEncoding(fauxcode(i, 3), 0xFFFD); assertEncoding(fauxcode(i, 4), 0xFFFD); } for (int i = 1 << 11; i < 1 << 16; i++) { assertEncoding(fauxcode(i, 4), 0xFFFD); } // sequences over max char are invalid for (int i = 0x110000; i < 1 << 21; i++) { assertEncoding(fauxcode(i), 0xFFFD); } // UTF-16 surrogates are invalid for (int i = 0xD800; i < 0xE000; i++) { assertEncoding(fauxcode(i), 0xFFFD); } // underlong sequences are invalid for (int i = 1 << 7; i < 1 << 21; i += 1 << 6) { byte[] bytes = fauxcode(i); while (bytes.length > 1) { assertEncoding(replaceLast(bytes, 0x24), 0xFFFD); bytes = stripLast(bytes); assertEncoding(bytes, 0xFFFD); } } } private static byte[] stripLast(final byte[] bytes) { return Arrays.copyOfRange(bytes, 0, bytes.length - 1); } private static byte[] replaceLast(final byte[] bytes, final int b) { bytes[bytes.length - 1] = (byte) b; return bytes; } private static byte[] fauxcode(final int cp) { if (cp < 1 << 7) { return fauxcode(cp, 1); } if (cp < 1 << 11) { return fauxcode(cp, 2); } if (cp < 1 << 16) { return fauxcode(cp, 3); } return fauxcode(cp, 4); } private static byte[] fauxcode(int cp, final int length) { if (length == 1) { return new byte[]{(byte) cp}; } byte[] bytes = new byte[length]; for (int i = length - 1; i >= 0; i--) { bytes[i] = (byte) (cp & 0x3F); bytes[i] |= 0x80; cp >>= 6; } bytes[0] |= (byte) 0x80 >> length - 1; return bytes; } private static void assertCodepoint(final int cp, final int expected) throws IOException { assertEncoding(fauxcode(cp), expected); } private static byte[] realcode(final int cp) { return new String(Character.toChars(cp)).getBytes(UTF_8); } private static void assertEncoding(final byte[] bytes, final int expected) throws IOException { try (ByteArrayInputStream input = new ByteArrayInputStream(bytes); ByteCountingInputStream counter = new ByteCountingInputStream(input)) { IntReader reader = IntReader.utf8ToCodepoint(counter); int codepoint = reader.read(); assertThat((long) bytes.length, is(counter.count())); assertThat(expected, is(codepoint)); } } }
34.583942
99
0.578092
c920e4a0decd515f89cf6c9760c51debafcd8acd
8,533
package com.google.mobilesafe.utils; import android.content.ContentValues; import org.json.JSONArray; import org.json.JSONObject; import java.util.Iterator; import java.util.Map; /** * ============================================================ * Copyright:Google有限公司版权所有 (c) 2017 * Author: 陈冠杰 * Email: [email protected] * GitHub: https://github.com/JackChen1999 * 博客: http://blog.csdn.net/axi295309066 * 微博: AndroidDeveloper * <p> * Project_Name:MobileSafe * Package_Name:com.google.mobilesafe * Version:1.0 * time:2016/2/15 22:32 * des :手机卫士 * gitVersion:$Rev$ * updateAuthor:$Author$ * updateDate:$Date$ * updateDes:${TODO} * ============================================================ **/ public class JsonUtil { public static void JSONCombine(JSONObject jSONObject, JSONObject jSONObject2) { if (jSONObject != null) { try { Iterator keys = jSONObject2.keys(); while (keys.hasNext()) { String str = (String) keys.next(); jSONObject.put(str, jSONObject2.get(str)); } } catch (Throwable th) { th.printStackTrace(); } } } public static String PubInfoToJson(JSONObject jSONObject) { if (jSONObject == null) { return ""; } try { jSONObject.put("id", jSONObject.optString("pubId")); jSONObject.put("name", jSONObject.optString("pubName")); jSONObject.put("classifyName", jSONObject.optString("pubType")); jSONObject.put("weiboName", jSONObject.optString("weiBoName")); jSONObject.put("weiboUrl", jSONObject.optString("weiBoUrl")); jSONObject.put("weixin", jSONObject.optString("weiXin")); jSONObject.put("logo", jSONObject.optString("rectLogoName")); jSONObject.put("logoc", jSONObject.optString("circleLogoName")); jSONObject.put("website", jSONObject.optString("webSite")); JSONArray optJSONArray = jSONObject.optJSONArray("pubNumInfolist"); if (optJSONArray == null || optJSONArray.length() <= 0) { jSONObject.put("pubnum", ""); } else { int length = optJSONArray.length(); JSONArray jSONArray = new JSONArray(); for (int i = 0; i < length; i++) { JSONObject jSONObject2 = (JSONObject) optJSONArray.get(i); if ("2".equals(jSONObject2.optString("type"))) { JSONObject jSONObject3 = new JSONObject(); jSONObject3.put("purpose", jSONObject2.optString("purpose")); jSONObject3.put("num", jSONObject2.optString("num")); jSONObject3.put("areaCode", jSONObject2.optString("areaCode")); jSONObject3.put("extend", jSONObject2.optString("extend")); jSONArray.put(jSONObject3); } } jSONObject.put("pubnum", jSONArray); } jSONObject.remove("pubId"); jSONObject.remove("pubName"); jSONObject.remove("pubType"); jSONObject.remove("pubTypeCode"); jSONObject.remove("weiXin"); jSONObject.remove("weiBoName"); jSONObject.remove("weiBoUrl"); jSONObject.remove("introduce"); jSONObject.remove("address"); jSONObject.remove("faxNum"); jSONObject.remove("webSite"); jSONObject.remove("versionCode"); jSONObject.remove("email"); jSONObject.remove("parentPubId"); jSONObject.remove("slogan"); jSONObject.remove("rectLogoName"); jSONObject.remove("circleLogoName"); jSONObject.remove("extend"); jSONObject.remove("pubNumInfolist"); jSONObject.remove("loadMenuTime"); jSONObject.remove("updateInfoTime"); jSONObject.remove("hasmenu"); return jSONObject.toString(); } catch (Throwable th) { th.printStackTrace(); return ""; } } public static JSONObject getJsonObject(JSONObject jSONObject, String... strArr) { if (strArr == null || jSONObject == null) { return null; } int length = strArr.length; if (length == 0 || length % 2 != 0) { return null; } int i = 0; while (i < length) { try { if (!(strArr[i] == null || strArr[i + 1] == null)) { jSONObject.put(strArr[i], strArr[i + 1]); } i += 2; } catch (Throwable e) { e.printStackTrace(); return null; } } return jSONObject; } public static JSONObject getJsonObject(String... strArr) { if (strArr == null) { return null; } int length = strArr.length; if (length == 0 || length % 2 != 0) { return null; } try { JSONObject jSONObject = new JSONObject(); int i = 0; while (i < length) { if (!(strArr[i] == null || strArr[i + 1] == null)) { jSONObject.put(strArr[i], strArr[i + 1]); } i += 2; } return jSONObject; } catch (Throwable e) { e.printStackTrace(); return null; } } public static Object getValFromJsonObject(JSONObject jSONObject, String str) { if (!(str == null || jSONObject == null)) { try { if (jSONObject.has(str)) { return jSONObject.get(str); } } catch (Throwable th) { th.printStackTrace(); } } return ""; } public static String getValueFromJson(JSONObject jSONObject, String str, String str2) { if (jSONObject == null) { return str2; } try { String optString = jSONObject.optString(str); return StringUtils.isNull(optString) ? str2 : optString; } catch (Throwable th) { th.printStackTrace(); return str2; } } public static Object getValueFromJsonObject(JSONObject jSONObject, String str) { if (!(str == null || jSONObject == null)) { try { if (jSONObject.has(str)) { return jSONObject.get(str); } } catch (Throwable th) { th.printStackTrace(); } } return null; } public static Object getValueWithMap(Map<String, Object> map, String str) { if (map != null) { try { if (!(map.isEmpty() || StringUtils.isNull(str) || !map.containsKey(str))) { return map.get(str); } } catch (Throwable th) { } } return ""; } public static JSONArray parseStrToJsonArray(String str) { if (!StringUtils.isNull(str)) { try { return new JSONArray(str); } catch (Throwable th) { th.printStackTrace(); } } return null; } public static JSONObject parseStrToJsonObject(String str) { if (!StringUtils.isNull(str)) { try { return new JSONObject(str.trim()); } catch (Throwable th) { th.printStackTrace(); } } return null; } public static void putJsonToConV(ContentValues contentValues, JSONObject jSONObject, String str, String str2) { String optString = jSONObject.optString(str2); if (StringUtils.isNull(optString)) { contentValues.remove(str); } else { contentValues.put(str, optString); } } public static void putJsonToMap(JSONObject jSONObject, Map<String, String> map) { if (jSONObject != null && map != null) { try { Iterator keys = jSONObject.keys(); while (keys.hasNext()) { String str = (String) keys.next(); map.put(str, jSONObject.getString(str)); } } catch (Throwable th) { } } } }
34.269076
115
0.504981
9a481ca59889dbd8de1cae97989be2c87b6d2353
155
/** * <p>Copyright (R) 2014 我是大牛软件股份有限公司。<p> */ package com.woshidaniu.zxzx.aip; public interface SqlCondition { public String getSqlCondition(); }
14.090909
41
0.703226
e6067570f73a9056ee857f849d6f745ffe20206a
4,480
/* Copyright 2016 Samsung Electronics Co., LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.samsungxr; import android.content.Context; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Future; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * This is a small convenience class that makes it easy to unzip a file and load entries as * {@link SXRAndroidResource}s into the SXRf framework. * * For cases where the number of files in an applications gets too large to handle, consider * zipping them and using the {@link ZipLoader} to process them one at a time. * * The class is flexible enough to allow all types of {@link SXRAndroidResource}s to be loaded. * * Note that the * {@link ZipLoader} makes use of a {@link ZipEntryProcessor}. The {@link ZipEntryProcessor} is a * user defined method that is applied to all entries in a zip file. */ public abstract class ZipLoader { private static final String TAG = ZipLoader.class.getSimpleName(); /** * Make use of the {@link ZipEntryProcessor} to process the {@link SXRAndroidResource}s * obtained from the zip file. */ public interface ZipEntryProcessor<T> { /** * This call is made for each entry in the zip file. Use this call to provide the * convenience function to process the {@link SXRAndroidResource}s obtained from the zip * file. For eg. use * {@link SXRContext#loadFutureTexture(SXRAndroidResource, int)} to return * a {@link java.util.concurrent.Future} to the {@link ZipLoader}. * * @param context the SXRf context * @param resource a resource entry obtained from the zip file * @return a processed zip resource entry */ T getItem(SXRContext context, SXRAndroidResource resource); } /** * Use this call to load a zip file using the * {@link ZipLoader} and apply the {@link ZipEntryProcessor} to each entry. The result is a * list of all processed entries obtained from the zip file. * * @param gvrContext the SXRf context * @param zipFileName the name of the zip file. This must be a file in the assets folder. * @param processor the {@link ZipEntryProcessor} to be applied to each zip entry in the file. * @return a list of processed zip file entries. * @throws IOException this function returns an {@link IOException} if there are issues * processing the provided zip file. */ public static <T> List<T> load(SXRContext gvrContext, String zipFileName, ZipEntryProcessor<T> processor) throws IOException { Context context = gvrContext.getContext(); InputStream inputStream = context.getAssets().open(zipFileName); ZipInputStream zipInputStream = new ZipInputStream(inputStream); List<T> result = new ArrayList<T>(); try { ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int count; while ((count = zipInputStream.read(buffer)) != -1) { baos.write(buffer, 0, count); } byte[] bytes = baos.toByteArray(); InputStream resourceInputStream = new ByteArrayInputStream(bytes); SXRAndroidResource androidResource = new SXRAndroidResource(zipEntry.getName(), resourceInputStream); T item = processor.getItem(gvrContext, androidResource); result.add(item); } } finally { zipInputStream.close(); } return result; } }
40.727273
100
0.666741
21070b18c3cd35543994529d1a583d4b737c38b1
424
package com.github.bottomlessarchive.loa.document.view.service; import com.github.bottomlessarchive.loa.document.service.domain.DocumentType; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; @Service public class MediaTypeCalculator { public MediaType calculateMediaType(final DocumentType documentType) { return MediaType.valueOf(documentType.getMimeType()); } }
30.285714
77
0.813679
0345a8149896c4200417801913230df01b6b9f2a
1,472
import java.io.IOException; import java.io.RandomAccessFile; public class fxn { void insert(int rno,String name,String course) //insert fxn { try { RandomAccessFile strecords = new RandomAccessFile("record.txt", "rw"); if(strecords.getFilePointer()==0) //if empty write heading { strecords.writeBytes("===================================================================\n"); strecords.writeBytes("Roll Number\t|\tName\t\t|\tCourse\n"); strecords.writeBytes("===================================================================\n"); } long i=strecords.length(); strecords.seek(i); //write at end of file strecords.writeBytes(rno+"\t\t"+" "+name+"\t\t\t"+" "+course+"\n"); System.out.println("Student "+name+" added Successfully!"); strecords.close(); } catch (IOException e) { e.printStackTrace(); } } void view() //view function { try { RandomAccessFile strecords = new RandomAccessFile("record.txt", "r"); strecords.seek(0); //start to read file from start long tr; long temp=strecords.length(); //last pointer location do { String line=strecords.readLine(); System.out.println(line); // System.out.println(); line=""; tr=strecords.getFilePointer(); //location of pointer at that time }while(tr!=temp); strecords.close(); } catch (IOException e) { e.printStackTrace(); } } }
24.533333
102
0.557745
1111bd12837b225044392e1d6d335bcf7a023881
588
/** * SPDX-License-Identifier: Apache-2.0 */ package com.devonfw.tools.solicitor.common.content.web; import com.devonfw.tools.solicitor.common.content.ContentFactory; /** * A {@link ContentFactory} for {@link WebContent}. */ public class WebContentFactory implements ContentFactory<WebContent> { /** * {@inheritDoc} */ @Override public WebContent fromString(String string) { return new WebContent(string); } /** * {@inheritDoc} */ @Override public WebContent emptyContent() { return new WebContent(null); } }
18.375
70
0.647959
1d456fd5ce40674b64c44347db83f4ca940d9481
2,523
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.glfw; import org.lwjgl.system.*; import org.lwjgl.system.libffi.*; import static org.lwjgl.system.APIUtil.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.libffi.LibFFI.*; /** * The function pointer type for memory deallocation callbacks. * * <p>This is the function pointer type for memory deallocation callbacks. A memory deallocation callback function has the following signature:</p> * * <pre><code> * void function_name(void* block, void* user)</code></pre> * * <p>This function may deallocate the specified memory block. This memory block will have been allocated with the same allocator.</p> * * <p>This function may be called during {@link GLFW#glfwInit Init} but before the library is flagged as initialized, as well as during {@link GLFW#glfwTerminate Terminate} after the library is no * longer flagged as initialized.</p> * * <p>The block address will never be {@code NULL}. Deallocations of {@code NULL} are filtered out before reaching the custom allocator.</p> * * <div style="margin-left: 26px; border-left: 1px solid gray; padding-left: 14px;"><h5>Note</h5> * * <ul> * <li>The specified memory block will not be accessed by GLFW after this function is called.</li> * <li>This function should not call any GLFW function.</li> * <li>This function may be called from any thread that calls GLFW functions.</li> * </ul></div> * * <h3>Type</h3> * * <pre><code> * void (*{@link #invoke}) ( * void *block, * void *user * )</code></pre> * * @since version 3.4 */ @FunctionalInterface @NativeType("GLFWdeallocatefun") public interface GLFWDeallocateCallbackI extends CallbackI { FFICIF CIF = apiCreateCIF( FFI_DEFAULT_ABI, ffi_type_void, ffi_type_pointer, ffi_type_pointer ); @Override default FFICIF getCallInterface() { return CIF; } @Override default void callback(long ret, long args) { invoke( memGetAddress(memGetAddress(args)), memGetAddress(memGetAddress(args + POINTER_SIZE)) ); } /** * Will be called for memory deallocation requests. * * @param block the address of the memory block to deallocate * @param user the user-defined pointer from the allocator */ void invoke(@NativeType("void *") long block, @NativeType("void *") long user); }
32.766234
196
0.688466
7a429ce8a40426b4abcca59846d15109cde9b1e8
1,465
/* * 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 restaurantsystem; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import restaurantsystem.component.auth.Login; public class Main extends JFrame { public static void main(String[] args) { // At first, show the login page and show menu after - // the authentication process completed createRequiredFileIfDoesNotExist(); Login im = new Login(); im.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); im.setVisible(true); } private static void createRequiredFileIfDoesNotExist() { String fileNames []; File rootDir = new File("storage"); rootDir.mkdirs(); fileNames = new String [] {"storage/item.txt", "storage/order.txt", "storage/orderLine.txt"}; for (String fileName : fileNames) { File file = new File(fileName); if(!file.exists()) { try { file.createNewFile(); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } } } }
25.701754
87
0.608874
6d82924d67d59363e8308034ab8d9b80d13226ae
992
//package com.example.modeldemo.service.factory; // //import com.example.modeldemo.init.SpringContextHolder; //import com.example.modeldemo.service.OutputService; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.ApplicationContext; // //import javax.annotation.PostConstruct; //import java.util.HashMap; //import java.util.Map; // //public class ServiceFactory { // // public static Map<String,OutputService> serviceMap ; // // @Autowired // private ApplicationContext ac; // // @PostConstruct // public void init(){ // if(serviceMap == null){ // serviceMap = new HashMap<>(); // } // } // // public static OutputService getServiceByName(String name){ // if(serviceMap.get(name) == null){ // ApplicationContext applicationContext = SpringContextHolder.getApplicationContext(); // applicationContext.getBean(name); // } // // return null; // } //}
28.342857
98
0.671371
755e03d73d9688ef3879f40db2f66da834b5e06a
2,087
package oxygenfactory.com.sasit.module.oxygen.expressProviders.entity; import com.google.gson.annotations.SerializedName; public class ExpressProvidersInfo { @SerializedName("ID") private Integer id;// @SerializedName("NAME") private String name;//名称 @SerializedName("CODE") private String code;//编码 @SerializedName("REMARK") private String remark;//备注 @SerializedName("LOGO") private String logo;// @SerializedName("TYPE") private String type;// @SerializedName("ORDER_BY") private Integer orderBy;// @SerializedName("CONTACTS") private String contacts;// @SerializedName("PHONE_NUMBER") private String phoneNumber;// @SerializedName("AREA_CODE") private String areaCode;// @SerializedName("SERVICE_SHOP_CODE") private String serviceShopCode;// public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getLogo() { return logo; } public void setLogo(String logo) { this.logo = logo; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Integer getOrderBy() { return orderBy; } public void setOrderBy(Integer orderBy) { this.orderBy = orderBy; } public String getContacts() { return contacts; } public void setContacts(String contacts) { this.contacts = contacts; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getAreaCode() { return areaCode; } public void setAreaCode(String areaCode) { this.areaCode = areaCode; } public String getServiceShopCode() { return serviceShopCode; } public void setServiceShopCode(String serviceShopCode) { this.serviceShopCode = serviceShopCode; } }
24.267442
71
0.727839
d6e68ab01dd3462e1e70c6543960b65724543a64
555
package quick.pager.shop.listener.platform; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.stream.annotation.StreamListener; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.stereotype.Component; /** * 发送短信消息监听器 * * @author siguiyang */ @Component @Slf4j public class SMSListener { @StreamListener(target = PlatformMQ.PLATFORM_SEND_SMS_INPUT) public void process(@Payload String payload) { log.info("发送短信接受消息 payload = {}", payload); // fixme 对接第三方短信服务 } }
24.130435
66
0.751351
5af9461358c3293ae7641eae7aaef54a6bc5179e
208
package no.nav.registre.inntekt.exception; public class UgyldigArbeidsforholdException extends RuntimeException { public UgyldigArbeidsforholdException(String message) { super(message); } }
23.111111
70
0.774038
5e889907b87c420b65ac391a9ee665cdd031578c
1,046
package fr.beapp.utils.android.graphics; import android.content.Context; import android.content.res.Resources; import android.util.DisplayMetrics; import android.util.TypedValue; public class UiUtils { private UiUtils() { } /** * Return the ActionBar's height in pixel. * * @param context the caller context * @return 0 if an error occurred, the height in pixels otherwise */ public static int retrieveActionBarHeight(Context context) { if (context == null) return 0; Resources resources = context.getResources(); DisplayMetrics displayMetrics = resources.getDisplayMetrics(); int actionBarHeightComplex = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, displayMetrics); TypedValue tv = new TypedValue(); Resources.Theme theme = context.getTheme(); if (theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) { actionBarHeightComplex = tv.data; } return TypedValue.complexToDimensionPixelSize(actionBarHeightComplex, displayMetrics); } }
28.27027
113
0.736138
a412ab6910dad4fce7cbc2167cd36d1142632973
7,784
/* This file is part of Peers, a java SIP softphone. This program 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 3 of the License, or any later version. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. Copyright 2007, 2008, 2009, 2010 Yohann Martineau */ package net.sourceforge.peers.sip.transport; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import net.sourceforge.peers.Config; import net.sourceforge.peers.Logger; import net.sourceforge.peers.sip.RFC3261; import net.sourceforge.peers.sip.Utils; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderFieldValue; import net.sourceforge.peers.sip.syntaxencoding.SipHeaderParamName; import net.sourceforge.peers.sip.syntaxencoding.SipParserException; import net.sourceforge.peers.sip.transaction.ClientTransaction; import net.sourceforge.peers.sip.transaction.ServerTransaction; import net.sourceforge.peers.sip.transaction.TransactionManager; public abstract class MessageReceiver implements Runnable { public static final int BUFFER_SIZE = 2048;//FIXME should correspond to MTU 1024; public static final String CHARACTER_ENCODING = "US-ASCII"; protected int port; private boolean isListening; //private UAS uas; private SipServerTransportUser sipServerTransportUser; private TransactionManager transactionManager; private TransportManager transportManager; private Config config; protected Logger logger; public MessageReceiver(int port, TransactionManager transactionManager, TransportManager transportManager, Config config, Logger logger) { super(); this.port = port; this.transactionManager = transactionManager; this.transportManager = transportManager; this.config = config; this.logger = logger; isListening = true; } public void run() { while (isListening) { try { listen(); } catch (IOException e) { logger.error("input/output error", e); } } } protected abstract void listen() throws IOException; protected boolean isRequest(byte[] message) { String beginning = null; try { beginning = new String(message, 0, RFC3261.DEFAULT_SIP_VERSION.length(), CHARACTER_ENCODING); } catch (UnsupportedEncodingException e) { logger.error("unsupported encoding", e); } if (RFC3261.DEFAULT_SIP_VERSION.equals(beginning)) { return false; } return true; } protected void processMessage(byte[] message, InetAddress sourceIp, int sourcePort, String transport) throws IOException { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(message); InputStreamReader inputStreamReader = new InputStreamReader( byteArrayInputStream); BufferedReader reader = new BufferedReader(inputStreamReader); String startLine = reader.readLine(); while ("".equals(startLine)) { startLine = reader.readLine(); } if (startLine == null) { return; } if (!startLine.contains(RFC3261.DEFAULT_SIP_VERSION)) { // keep-alive, send back to sender SipTransportConnection sipTransportConnection = new SipTransportConnection(config.getLocalInetAddress(), port, sourceIp, sourcePort, transport); MessageSender messageSender = transportManager.getMessageSender( sipTransportConnection); if (messageSender != null) { messageSender.sendBytes(message); } return; } StringBuffer direction = new StringBuffer(); direction.append("RECEIVED from ").append(sourceIp.getHostAddress()); direction.append("/").append(sourcePort); logger.traceNetwork(new String(message), direction.toString()); SipMessage sipMessage = null; try { sipMessage = transportManager.sipParser.parse( new ByteArrayInputStream(message)); } catch (IOException e) { logger.error("input/output error", e); } catch (SipParserException e) { logger.error("SIP parser error", e); } if (sipMessage == null) { return; } // RFC3261 18.2 if (sipMessage instanceof SipRequest) { SipRequest sipRequest = (SipRequest)sipMessage; SipHeaderFieldValue topVia = Utils.getTopVia(sipRequest); String sentBy = topVia.getParam(new SipHeaderParamName(RFC3261.PARAM_SENTBY)); if (sentBy != null) { int colonPos = sentBy.indexOf(RFC3261.TRANSPORT_PORT_SEP); if (colonPos < 0) { colonPos = sentBy.length(); } sentBy = sentBy.substring(0, colonPos); if (!InetAddress.getByName(sentBy).equals(sourceIp)) { topVia.addParam(new SipHeaderParamName( RFC3261.PARAM_RECEIVED), sourceIp.getHostAddress()); } } //RFC3581 //TODO check rport configuration SipHeaderParamName rportName = new SipHeaderParamName( RFC3261.PARAM_RPORT); String rport = topVia.getParam(rportName); if (rport != null && "".equals(rport)) { topVia.removeParam(rportName); topVia.addParam(rportName, String.valueOf(sourcePort)); } ServerTransaction serverTransaction = transactionManager.getServerTransaction(sipRequest); if (serverTransaction == null) { //uas.messageReceived(sipMessage); sipServerTransportUser.messageReceived(sipMessage); } else { serverTransaction.receivedRequest(sipRequest); } } else { SipResponse sipResponse = (SipResponse)sipMessage; ClientTransaction clientTransaction = transactionManager.getClientTransaction(sipResponse); logger.debug("ClientTransaction = " + clientTransaction); if (clientTransaction == null) { //uas.messageReceived(sipMessage); sipServerTransportUser.messageReceived(sipMessage); } else { clientTransaction.receivedResponse(sipResponse); } } } public synchronized void setListening(boolean isListening) { this.isListening = isListening; } public synchronized boolean isListening() { return isListening; } public void setSipServerTransportUser( SipServerTransportUser sipServerTransportUser) { this.sipServerTransportUser = sipServerTransportUser; } // public void setUas(UAS uas) { // this.uas = uas; // } }
37.603865
85
0.629368
e06885bf6634f2c0c511ed18783133038ed15ab3
522
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.gms.internal.ads; // Referenced classes of package com.google.android.gms.internal.ads: // bmj, biz, bct, bjc public interface bjb { public abstract biz a(int i, bmj bmj); public abstract void a(); public abstract void a(bct bct, boolean flag, bjc bjc); public abstract void a(biz biz); public abstract void b(); }
21.75
69
0.724138
e42a0cb35064750bf0b8cc7ebc797bf58df5f147
1,417
/** * Copyright 2014 LiveRamp * * 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.liveramp.megadesk.recipes.transaction; import com.liveramp.megadesk.base.transaction.BaseDependency; import com.liveramp.megadesk.base.transaction.BaseTransaction; import com.liveramp.megadesk.core.state.Variable; import com.liveramp.megadesk.core.transaction.Context; public class Copy<VALUE> extends BaseTransaction<VALUE> { private final Variable<VALUE> source; private final Variable<VALUE> destination; public Copy(Variable<VALUE> source, Variable<VALUE> destination) { super(BaseDependency.builder().reads(source).writes(destination).build()); this.source = source; this.destination = destination; } @Override public VALUE run(Context context) throws Exception { VALUE value = context.read(source); context.write(destination, value); return value; } }
33.738095
78
0.750882
c04e6a14dd8ff40a0828c145b0c2c37c4433fd43
21,935
package sclean2.com; import anywheresoftware.b4a.BA; import anywheresoftware.b4a.objects.ServiceHelper; import anywheresoftware.b4a.debug.*; public class starter extends android.app.Service{ public static class starter_BR extends android.content.BroadcastReceiver { @Override public void onReceive(android.content.Context context, android.content.Intent intent) { android.content.Intent in = new android.content.Intent(context, starter.class); if (intent != null) in.putExtra("b4a_internal_intent", intent); context.startService(in); } } static starter mostCurrent; public static BA processBA; private ServiceHelper _service; public static Class<?> getObject() { return starter.class; } @Override public void onCreate() { super.onCreate(); mostCurrent = this; if (processBA == null) { processBA = new BA(this, null, null, "sclean2.com", "sclean2.com.starter"); if (BA.isShellModeRuntimeCheck(processBA)) { processBA.raiseEvent2(null, true, "SHELL", false); } try { Class.forName(BA.applicationContext.getPackageName() + ".main").getMethod("initializeProcessGlobals").invoke(null, null); } catch (Exception e) { throw new RuntimeException(e); } processBA.loadHtSubs(this.getClass()); ServiceHelper.init(); } _service = new ServiceHelper(this); processBA.service = this; if (BA.isShellModeRuntimeCheck(processBA)) { processBA.raiseEvent2(null, true, "CREATE", true, "sclean2.com.starter", processBA, _service, anywheresoftware.b4a.keywords.Common.Density); } if (!true && ServiceHelper.StarterHelper.startFromServiceCreate(processBA, false) == false) { } else { processBA.setActivityPaused(false); BA.LogInfo("*** Service (starter) Create ***"); processBA.raiseEvent(null, "service_create"); } processBA.runHook("oncreate", this, null); if (true) { ServiceHelper.StarterHelper.runWaitForLayouts(); } } @Override public void onStart(android.content.Intent intent, int startId) { onStartCommand(intent, 0, 0); } @Override public int onStartCommand(final android.content.Intent intent, int flags, int startId) { if (ServiceHelper.StarterHelper.onStartCommand(processBA, new Runnable() { public void run() { handleStart(intent); }})) ; else { ServiceHelper.StarterHelper.addWaitForLayout (new Runnable() { public void run() { processBA.setActivityPaused(false); BA.LogInfo("** Service (starter) Create **"); processBA.raiseEvent(null, "service_create"); handleStart(intent); ServiceHelper.StarterHelper.removeWaitForLayout(); } }); } processBA.runHook("onstartcommand", this, new Object[] {intent, flags, startId}); return android.app.Service.START_NOT_STICKY; } public void onTaskRemoved(android.content.Intent rootIntent) { super.onTaskRemoved(rootIntent); if (true) processBA.raiseEvent(null, "service_taskremoved"); } private void handleStart(android.content.Intent intent) { BA.LogInfo("** Service (starter) Start **"); java.lang.reflect.Method startEvent = processBA.htSubs.get("service_start"); if (startEvent != null) { if (startEvent.getParameterTypes().length > 0) { anywheresoftware.b4a.objects.IntentWrapper iw = new anywheresoftware.b4a.objects.IntentWrapper(); if (intent != null) { if (intent.hasExtra("b4a_internal_intent")) iw.setObject((android.content.Intent) intent.getParcelableExtra("b4a_internal_intent")); else iw.setObject(intent); } processBA.raiseEvent(null, "service_start", iw); } else { processBA.raiseEvent(null, "service_start"); } } } @Override public void onDestroy() { super.onDestroy(); BA.LogInfo("** Service (starter) Destroy **"); processBA.raiseEvent(null, "service_destroy"); processBA.service = null; mostCurrent = null; processBA.setActivityPaused(true); processBA.runHook("ondestroy", this, null); } @Override public android.os.IBinder onBind(android.content.Intent intent) { return null; }public anywheresoftware.b4a.keywords.Common __c = null; public static anywheresoftware.b4a.cachecleaner.CacheCleaner _cb = null; public static anywheresoftware.b4a.objects.Timer _t2 = null; public static anywheresoftware.b4a.objects.Timer _t3 = null; public static String _name = ""; public static String _apath = ""; public static String _l = ""; public static String[] _types = null; public static String _packname = ""; public static Object[] _app = null; public static int _counter = 0; public static com.rootsoft.customtoast.CustomToast _cts = null; public static anywheresoftware.b4a.objects.collections.List _piclist = null; public static anywheresoftware.b4a.objects.collections.List _obj = null; public static String _date = ""; public static String _time = ""; public static String _dir = ""; public static sclean2.com.keyvaluestore _kvst = null; public static sclean2.com.keyvaluestore _kvsdata = null; public static sclean2.com.keyvaluestore _alist = null; public static sclean2.com.keyvaluestore _dbase = null; public static sclean2.com.keyvaluestore _abase = null; public static sclean2.com.keyvaluestore _qbase = null; public static anywheresoftware.b4a.objects.collections.List _apli = null; public static anywheresoftware.b4a.phone.PackageManagerWrapper _pack = null; public static String _package = ""; public sclean2.com.main _main = null; public sclean2.com.animator _animator = null; public sclean2.com.sub2 _sub2 = null; public static boolean _application_error(anywheresoftware.b4a.objects.B4AException _error,String _stacktrace) throws Exception{ //BA.debugLineNum = 66;BA.debugLine="Sub Application_Error (Error As Exception, StackTr"; //BA.debugLineNum = 67;BA.debugLine="Return True"; if (true) return anywheresoftware.b4a.keywords.Common.True; //BA.debugLineNum = 68;BA.debugLine="End Sub"; return false; } public static String _cb_oncleancompleted(long _cachesize) throws Exception{ //BA.debugLineNum = 148;BA.debugLine="Sub cb_onCleanCompleted(CacheSize As Long)"; //BA.debugLineNum = 149;BA.debugLine="Log(CacheSize&\" cleaned\")"; anywheresoftware.b4a.keywords.Common.Log(BA.NumberToString(_cachesize)+" cleaned"); //BA.debugLineNum = 150;BA.debugLine="kvst.DeleteAll"; _kvst._deleteall(); //BA.debugLineNum = 151;BA.debugLine="kvsdata.Put(\"cz\",FormatFileSize(CacheSize))"; _kvsdata._put("cz",(Object)(_formatfilesize((float) (_cachesize)))); //BA.debugLineNum = 154;BA.debugLine="End Sub"; return ""; } public static String _cb_oncleanstarted() throws Exception{ //BA.debugLineNum = 143;BA.debugLine="Sub cb_onCleanStarted"; //BA.debugLineNum = 145;BA.debugLine="Log(\"Cleaning..\")"; anywheresoftware.b4a.keywords.Common.Log("Cleaning.."); //BA.debugLineNum = 146;BA.debugLine="End Sub"; return ""; } public static String _cb_onscancompleted(Object _appslist) throws Exception{ long _totalsize = 0L; anywheresoftware.b4a.phone.PackageManagerWrapper _pm = null; anywheresoftware.b4a.objects.drawable.BitmapDrawable _icon = null; anywheresoftware.b4a.objects.collections.List _lu = null; int _n = 0; //BA.debugLineNum = 102;BA.debugLine="Sub cb_onScanCompleted(AppsList As Object)"; //BA.debugLineNum = 103;BA.debugLine="Dim totalsize As Long = 0"; _totalsize = (long) (0); //BA.debugLineNum = 104;BA.debugLine="Dim pm As PackageManager"; _pm = new anywheresoftware.b4a.phone.PackageManagerWrapper(); //BA.debugLineNum = 105;BA.debugLine="Private icon As BitmapDrawable"; _icon = new anywheresoftware.b4a.objects.drawable.BitmapDrawable(); //BA.debugLineNum = 106;BA.debugLine="piclist.Clear"; _piclist.Clear(); //BA.debugLineNum = 107;BA.debugLine="obj.Clear"; _obj.Clear(); //BA.debugLineNum = 108;BA.debugLine="alist.DeleteAll"; _alist._deleteall(); //BA.debugLineNum = 110;BA.debugLine="Try"; try { //BA.debugLineNum = 111;BA.debugLine="Dim lu As List = AppsList"; _lu = new anywheresoftware.b4a.objects.collections.List(); _lu.setObject((java.util.List)(_appslist)); //BA.debugLineNum = 112;BA.debugLine="For n = 0 To lu.Size-1"; { final int step9 = 1; final int limit9 = (int) (_lu.getSize()-1); _n = (int) (0) ; for (;(step9 > 0 && _n <= limit9) || (step9 < 0 && _n >= limit9) ;_n = ((int)(0 + _n + step9)) ) { //BA.debugLineNum = 113;BA.debugLine="app= lu.Get(n)"; _app = (Object[])(_lu.Get(_n)); //BA.debugLineNum = 114;BA.debugLine="If app(1) = \"com.android.systemui\" Then Conti"; if ((_app[(int) (1)]).equals((Object)("com.android.systemui"))) { if (true) continue;}; //BA.debugLineNum = 115;BA.debugLine="icon = pm.GetApplicationIcon(app(1))"; _icon.setObject((android.graphics.drawable.BitmapDrawable)(_pm.GetApplicationIcon(BA.ObjectToString(_app[(int) (1)])))); //BA.debugLineNum = 116;BA.debugLine="totalsize = totalsize+app(2)"; _totalsize = (long) (_totalsize+(double)(BA.ObjectToNumber(_app[(int) (2)]))); //BA.debugLineNum = 117;BA.debugLine="alist.Put(app(1),totalsize+app(2))"; _alist._put(BA.ObjectToString(_app[(int) (1)]),(Object)(_totalsize+(double)(BA.ObjectToNumber(_app[(int) (2)])))); //BA.debugLineNum = 118;BA.debugLine="alist.Remove(package)"; _alist._remove(_package); //BA.debugLineNum = 119;BA.debugLine="obj.Add(app(1))"; _obj.Add(_app[(int) (1)]); //BA.debugLineNum = 120;BA.debugLine="kvsdata.PutBitmap(n,icon.Bitmap)"; _kvsdata._putbitmap(BA.NumberToString(_n),(anywheresoftware.b4a.objects.drawable.CanvasWrapper.BitmapWrapper) anywheresoftware.b4a.AbsObjectWrapper.ConvertToWrapper(new anywheresoftware.b4a.objects.drawable.CanvasWrapper.BitmapWrapper(), (android.graphics.Bitmap)(_icon.getBitmap()))); //BA.debugLineNum = 121;BA.debugLine="qbase.Remove(\"com.android.systemui\")"; _qbase._remove("com.android.systemui"); } }; } catch (Exception e21) { processBA.setLastException(e21); //BA.debugLineNum = 124;BA.debugLine="Log(LastException.Message)"; anywheresoftware.b4a.keywords.Common.Log(anywheresoftware.b4a.keywords.Common.LastException(processBA).getMessage()); }; //BA.debugLineNum = 126;BA.debugLine="If lu.size >= 0 Then"; if (_lu.getSize()>=0) { //BA.debugLineNum = 127;BA.debugLine="Log(\"T-Size: \"&FormatFileSize(totalsize))"; anywheresoftware.b4a.keywords.Common.Log("T-Size: "+_formatfilesize((float) (_totalsize))); //BA.debugLineNum = 128;BA.debugLine="kvsdata.Put(\"cp\",totalsize)"; _kvsdata._put("cp",(Object)(_totalsize)); }else { //BA.debugLineNum = 132;BA.debugLine="Log(\"nothing to show\")"; anywheresoftware.b4a.keywords.Common.Log("nothing to show"); //BA.debugLineNum = 133;BA.debugLine="CallSub(Main,\"finish_modul\")"; anywheresoftware.b4a.keywords.Common.CallSubNew(processBA,(Object)(mostCurrent._main.getObject()),"finish_modul"); }; //BA.debugLineNum = 136;BA.debugLine="End Sub"; return ""; } public static String _cb_onscanprogress(int _current,int _total) throws Exception{ //BA.debugLineNum = 96;BA.debugLine="Sub cb_onScanProgress(Current As Int , Total As In"; //BA.debugLineNum = 97;BA.debugLine="kvsdata.Put(\"to\",Total)"; _kvsdata._put("to",(Object)(_total)); //BA.debugLineNum = 98;BA.debugLine="kvsdata.Put(\"c\",Current)"; _kvsdata._put("c",(Object)(_current)); //BA.debugLineNum = 99;BA.debugLine="CallSub(Main,\"update_modul\")"; anywheresoftware.b4a.keywords.Common.CallSubNew(processBA,(Object)(mostCurrent._main.getObject()),"update_modul"); //BA.debugLineNum = 100;BA.debugLine="End Sub"; return ""; } public static String _cb_onscanstarted() throws Exception{ //BA.debugLineNum = 90;BA.debugLine="Sub cb_OnScanStarted"; //BA.debugLineNum = 91;BA.debugLine="Log(\"Started\")"; anywheresoftware.b4a.keywords.Common.Log("Started"); //BA.debugLineNum = 93;BA.debugLine="End Sub"; return ""; } public static String _formatfilesize(float _bytes) throws Exception{ String[] _unit = null; double _po = 0; double _si = 0; int _i = 0; //BA.debugLineNum = 156;BA.debugLine="Sub FormatFileSize(Bytes As Float) As String"; //BA.debugLineNum = 157;BA.debugLine="Private Unit() As String = Array As String(\" Byte"; _unit = new String[]{" Byte"," KB"," MB"," GB"," TB"," PB"," EB"," ZB"," YB"}; //BA.debugLineNum = 158;BA.debugLine="If Bytes = 0 Then"; if (_bytes==0) { //BA.debugLineNum = 159;BA.debugLine="Return \"0 Bytes\""; if (true) return "0 Bytes"; }else { //BA.debugLineNum = 161;BA.debugLine="Private Po, Si As Double"; _po = 0; _si = 0; //BA.debugLineNum = 162;BA.debugLine="Private I As Int"; _i = 0; //BA.debugLineNum = 163;BA.debugLine="Bytes = Abs(Bytes)"; _bytes = (float) (anywheresoftware.b4a.keywords.Common.Abs(_bytes)); //BA.debugLineNum = 164;BA.debugLine="I = Floor(Logarithm(Bytes, 1024))"; _i = (int) (anywheresoftware.b4a.keywords.Common.Floor(anywheresoftware.b4a.keywords.Common.Logarithm(_bytes,1024))); //BA.debugLineNum = 165;BA.debugLine="Po = Power(1024, I)"; _po = anywheresoftware.b4a.keywords.Common.Power(1024,_i); //BA.debugLineNum = 166;BA.debugLine="Si = Bytes / Po"; _si = _bytes/(double)_po; //BA.debugLineNum = 167;BA.debugLine="Return NumberFormat(Si, 1, 2) & Unit(I)"; if (true) return anywheresoftware.b4a.keywords.Common.NumberFormat(_si,(int) (1),(int) (2))+_unit[_i]; }; //BA.debugLineNum = 169;BA.debugLine="End Sub"; return ""; } public static String _info_remote() throws Exception{ int _i = 0; //BA.debugLineNum = 79;BA.debugLine="Sub info_remote"; //BA.debugLineNum = 80;BA.debugLine="apli=pack.GetInstalledPackages"; _apli = _pack.GetInstalledPackages(); //BA.debugLineNum = 81;BA.debugLine="kvst.Put(\"ta\",apli.Size)"; _kvst._put("ta",(Object)(_apli.getSize())); //BA.debugLineNum = 82;BA.debugLine="qbase.DeleteAll"; _qbase._deleteall(); //BA.debugLineNum = 83;BA.debugLine="For i = 0 To apli.Size-1"; { final int step4 = 1; final int limit4 = (int) (_apli.getSize()-1); _i = (int) (0) ; for (;(step4 > 0 && _i <= limit4) || (step4 < 0 && _i >= limit4) ;_i = ((int)(0 + _i + step4)) ) { //BA.debugLineNum = 84;BA.debugLine="qbase.Put(i,apli.Get(i))"; _qbase._put(BA.NumberToString(_i),_apli.Get(_i)); } }; //BA.debugLineNum = 86;BA.debugLine="Log(\"added: \"&kvst.Get(\"ta\"))"; anywheresoftware.b4a.keywords.Common.Log("added: "+BA.ObjectToString(_kvst._get("ta"))); //BA.debugLineNum = 87;BA.debugLine="End Sub"; return ""; } public static String _process_globals() throws Exception{ //BA.debugLineNum = 6;BA.debugLine="Sub Process_Globals"; //BA.debugLineNum = 9;BA.debugLine="Private cb As CacheCleaner"; _cb = new anywheresoftware.b4a.cachecleaner.CacheCleaner(); //BA.debugLineNum = 10;BA.debugLine="Dim t2,t3 As Timer"; _t2 = new anywheresoftware.b4a.objects.Timer(); _t3 = new anywheresoftware.b4a.objects.Timer(); //BA.debugLineNum = 11;BA.debugLine="Private name,apath,l,Types(1),packName As String"; _name = ""; _apath = ""; _l = ""; _types = new String[(int) (1)]; java.util.Arrays.fill(_types,""); _packname = ""; //BA.debugLineNum = 12;BA.debugLine="Dim app() As Object"; _app = new Object[(int) (0)]; { int d0 = _app.length; for (int i0 = 0;i0 < d0;i0++) { _app[i0] = new Object(); } } ; //BA.debugLineNum = 13;BA.debugLine="Dim counter As Int"; _counter = 0; //BA.debugLineNum = 14;BA.debugLine="Private cts As CustomToast"; _cts = new com.rootsoft.customtoast.CustomToast(); //BA.debugLineNum = 15;BA.debugLine="Dim piclist As List"; _piclist = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 16;BA.debugLine="Dim obj As List"; _obj = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 17;BA.debugLine="Dim date,time As String"; _date = ""; _time = ""; //BA.debugLineNum = 18;BA.debugLine="Dim dir As String=File.DirInternal&\"/Bdata\""; _dir = anywheresoftware.b4a.keywords.Common.File.getDirInternal()+"/Bdata"; //BA.debugLineNum = 19;BA.debugLine="Private kvst,kvsdata,alist,dbase,abase,qbase As K"; _kvst = new sclean2.com.keyvaluestore(); _kvsdata = new sclean2.com.keyvaluestore(); _alist = new sclean2.com.keyvaluestore(); _dbase = new sclean2.com.keyvaluestore(); _abase = new sclean2.com.keyvaluestore(); _qbase = new sclean2.com.keyvaluestore(); //BA.debugLineNum = 20;BA.debugLine="Private apli As List"; _apli = new anywheresoftware.b4a.objects.collections.List(); //BA.debugLineNum = 21;BA.debugLine="Private pack As PackageManager"; _pack = new anywheresoftware.b4a.phone.PackageManagerWrapper(); //BA.debugLineNum = 22;BA.debugLine="Private package As String=\"sclean2.com\""; _package = "sclean2.com"; //BA.debugLineNum = 23;BA.debugLine="End Sub"; return ""; } public static String _service_create() throws Exception{ //BA.debugLineNum = 25;BA.debugLine="Sub Service_Create"; //BA.debugLineNum = 29;BA.debugLine="DateTime.TimeFormat=\"HH:mm\""; anywheresoftware.b4a.keywords.Common.DateTime.setTimeFormat("HH:mm"); //BA.debugLineNum = 30;BA.debugLine="DateTime.DateFormat=\"dd.MM.yyy\""; anywheresoftware.b4a.keywords.Common.DateTime.setDateFormat("dd.MM.yyy"); //BA.debugLineNum = 31;BA.debugLine="date=DateTime.Date(DateTime.Now)"; _date = anywheresoftware.b4a.keywords.Common.DateTime.Date(anywheresoftware.b4a.keywords.Common.DateTime.getNow()); //BA.debugLineNum = 32;BA.debugLine="time=DateTime.Time(DateTime.Now)"; _time = anywheresoftware.b4a.keywords.Common.DateTime.Time(anywheresoftware.b4a.keywords.Common.DateTime.getNow()); //BA.debugLineNum = 33;BA.debugLine="kvst.Initialize(File.DirInternal,\"data_time\")"; _kvst._initialize(processBA,anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"data_time"); //BA.debugLineNum = 34;BA.debugLine="kvsdata.Initialize(File.DirInternal,\"data_data\")"; _kvsdata._initialize(processBA,anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"data_data"); //BA.debugLineNum = 35;BA.debugLine="alist.Initialize(File.DirInternal,\"adata_data\")"; _alist._initialize(processBA,anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"adata_data"); //BA.debugLineNum = 36;BA.debugLine="dbase.Initialize(File.DirInternal,\"dbase_data\")"; _dbase._initialize(processBA,anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"dbase_data"); //BA.debugLineNum = 37;BA.debugLine="abase.Initialize(File.DirInternal,\"abase_data\")"; _abase._initialize(processBA,anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"abase_data"); //BA.debugLineNum = 38;BA.debugLine="qbase.Initialize(File.DirInternal,\"qbase_data\")"; _qbase._initialize(processBA,anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"qbase_data"); //BA.debugLineNum = 40;BA.debugLine="piclist.Initialize"; _piclist.Initialize(); //BA.debugLineNum = 41;BA.debugLine="obj.Initialize"; _obj.Initialize(); //BA.debugLineNum = 42;BA.debugLine="cb.initialize(\"cb\")"; _cb.initialize("cb",processBA); //BA.debugLineNum = 43;BA.debugLine="cts.Initialize"; _cts.Initialize(processBA); //BA.debugLineNum = 44;BA.debugLine="apli.Initialize"; _apli.Initialize(); //BA.debugLineNum = 45;BA.debugLine="apli=pack.GetInstalledPackages"; _apli = _pack.GetInstalledPackages(); //BA.debugLineNum = 46;BA.debugLine="counter=0"; _counter = (int) (0); //BA.debugLineNum = 47;BA.debugLine="t2.Initialize(\"t2\",1000)"; _t2.Initialize(processBA,"t2",(long) (1000)); //BA.debugLineNum = 48;BA.debugLine="t3.Initialize(\"t3\",1000)"; _t3.Initialize(processBA,"t3",(long) (1000)); //BA.debugLineNum = 49;BA.debugLine="t3.Enabled=False"; _t3.setEnabled(anywheresoftware.b4a.keywords.Common.False); //BA.debugLineNum = 50;BA.debugLine="If Not(File.IsDirectory(File.DirInternal,\"Bdata\")"; if (anywheresoftware.b4a.keywords.Common.Not(anywheresoftware.b4a.keywords.Common.File.IsDirectory(anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"Bdata"))) { //BA.debugLineNum = 51;BA.debugLine="File.MakeDir(File.DirInternal,\"Bdata/temp\")"; anywheresoftware.b4a.keywords.Common.File.MakeDir(anywheresoftware.b4a.keywords.Common.File.getDirInternal(),"Bdata/temp"); //BA.debugLineNum = 52;BA.debugLine="File.WriteList(dir,\"clist.txt\",obj)"; anywheresoftware.b4a.keywords.Common.File.WriteList(_dir,"clist.txt",_obj); }; //BA.debugLineNum = 54;BA.debugLine="info_remote"; _info_remote(); //BA.debugLineNum = 55;BA.debugLine="End Sub"; return ""; } public static String _service_destroy() throws Exception{ //BA.debugLineNum = 70;BA.debugLine="Sub Service_Destroy"; //BA.debugLineNum = 71;BA.debugLine="t2.Enabled=False"; _t2.setEnabled(anywheresoftware.b4a.keywords.Common.False); //BA.debugLineNum = 72;BA.debugLine="End Sub"; return ""; } public static String _service_start(anywheresoftware.b4a.objects.IntentWrapper _startingintent) throws Exception{ //BA.debugLineNum = 57;BA.debugLine="Sub Service_Start (StartingIntent As Intent)"; //BA.debugLineNum = 59;BA.debugLine="End Sub"; return ""; } public static String _service_taskremoved() throws Exception{ //BA.debugLineNum = 61;BA.debugLine="Sub Service_TaskRemoved"; //BA.debugLineNum = 63;BA.debugLine="End Sub"; return ""; } public static String _start() throws Exception{ //BA.debugLineNum = 74;BA.debugLine="Sub start"; //BA.debugLineNum = 75;BA.debugLine="cb.ScanCache"; _cb.ScanCache(); //BA.debugLineNum = 77;BA.debugLine="End Sub"; return ""; } public static String _start_c() throws Exception{ //BA.debugLineNum = 138;BA.debugLine="Sub start_c"; //BA.debugLineNum = 139;BA.debugLine="cb.CleanCache"; _cb.CleanCache(); //BA.debugLineNum = 140;BA.debugLine="CallSub(Main,\"c_start\")"; anywheresoftware.b4a.keywords.Common.CallSubNew(processBA,(Object)(mostCurrent._main.getObject()),"c_start"); //BA.debugLineNum = 141;BA.debugLine="Log(\"start_c:\")"; anywheresoftware.b4a.keywords.Common.Log("start_c:"); //BA.debugLineNum = 142;BA.debugLine="End Sub"; return ""; } }
46.970021
285
0.719398
2c5e8490df82f7e950f436f258bf7bc961457231
435
/* * Copyright (c) Alexander <[email protected]> Chapchuk * Project name: PinNote * * Licensed under the MIT License. See LICENSE file in the project root for license information. */ package org.bigtows.notebook; /** * Simple interface of credential */ public interface NotebookAccessible { /** * Get token for access to API * * @return token */ String getToken(); boolean hasToken(); }
17.4
96
0.657471
35cb5011382d8a207ffe87df0ae8f766cc10e057
7,381
package org.encryptor4j; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; /** * <p>One-time pad implementation.</p> * * <p></p> * @author Martin * */ public class OneTimePad { /* * Attributes */ private SecureRandom random; private int ioBufferSize; private int workBufferSize; private boolean zeroFill; /* * Constructor(s) */ /** * <p>Constructs a default <code>OneTimePad</code> instance.</p> */ public OneTimePad() { this(1024 * 1024, 256 * 1024); } /** * <p>Constructs a <code>OneTimePad</code> instance with custom buffer sizes.</p> * @param ioBufferSize * @param workBufferSize */ public OneTimePad(int ioBufferSize, int workBufferSize) { this(new SecureRandom(), ioBufferSize, workBufferSize); } /** * <p>Constructs a <code>OneTimePad</code> instance with custom random source and buffer sizes.</p> * @param random * @param ioBufferSize * @param workBufferSize */ public OneTimePad(SecureRandom random, int ioBufferSize, int workBufferSize) { this.random = random; this.ioBufferSize = ioBufferSize; this.workBufferSize = workBufferSize; } /* * Class methods */ /** * <p>Creates a padfile containing random bytes.</p> * @param padFile * @param size */ public void createPadFile(File padFile, long size) { OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(padFile), ioBufferSize); long totalSize = 0; long bytesLeft; byte[] randomBytes = new byte[workBufferSize]; while (totalSize < size) { random.nextBytes(randomBytes); bytesLeft = size - totalSize; if(bytesLeft < workBufferSize) { os.write(randomBytes, 0, (int) bytesLeft); totalSize += bytesLeft; } else { os.write(randomBytes); totalSize += workBufferSize; } } os.flush(); } catch(IOException e) { throw new RuntimeException(e); } finally { if(os != null) { try { os.close(); } catch(IOException e) { e.printStackTrace(); } } } } /** * <p>Reads bytes from <code>inFile</code>, pads them with corresponding offset bytes from <code>padFile</code> * and writes them to <code>outFile</code>.</p> * <p>Returns the new offset for the pad file.</p> * @param inFile * @param outFile * @param padFile * @param offset * @return */ public long padData(File inFile, File outFile, File padFile, long offset) { RandomAccessFile raf = null; InputStream is = null; OutputStream os = null; try { raf = new RandomAccessFile(padFile, zeroFill ? "rw" : "r"); raf.seek(offset); is = new BufferedInputStream(new FileInputStream(inFile), ioBufferSize); os = new BufferedOutputStream(new FileOutputStream(outFile), ioBufferSize); byte[] padBytes = new byte[workBufferSize]; byte[] bytes = new byte[workBufferSize]; int nPadBytes; int nBytes; while(true) { nBytes = is.read(bytes); nPadBytes = raf.read(padBytes); if(nBytes > 0) { if(nPadBytes >= nBytes) { for(int i = 0; i < nBytes; i++) { // Work the magic bytes[i] = (byte) (bytes[i] ^ padBytes[i]); } os.write(bytes, 0, nBytes); if(zeroFill) { // Perform zero-filling raf.seek(offset); for(int i = 0; i < nBytes; i++) { raf.write(0); } } offset += nBytes; } else { throw new IOException("Not enough pad bytes"); } } else { break; } } os.flush(); return offset; } catch(IOException e) { throw new RuntimeException(e); } finally { if(raf != null) { try { raf.close(); } catch (IOException e) { e.printStackTrace(); } } if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * <p>Sets whether padding bytes should be set to <code>0</code> when they have been used. * This potentially increases security because the message can only be padded and unpadded once.</p> * @param zeroFill */ public void setZeroFill(boolean zeroFill) { this.zeroFill = zeroFill; } /* * Static methods */ /** * * @param args */ public static void main(String[] args) { Options options = new Options(); options.addOption( Option.builder("c") .longOpt("create") .hasArg() .argName("file") .desc("create pad file") .build() ); options.addOption( Option.builder("p") .longOpt("pad") .hasArg() .argName("file") .desc("pad file") .build() ); options.addOption( Option.builder("f") .longOpt("offset") .hasArg() .argName("bytes") .desc("offset") .build() ); options.addOption( Option.builder("s") .longOpt("size") .hasArg() .argName("bytes") .desc("size") .build() ); options.addOption( Option.builder("i") .longOpt("in-file") .hasArg() .argName("file") .desc("input file") .build() ); options.addOption( Option.builder("o") .longOpt("out-file") .hasArg() .argName("file") .desc("output file") .build() ); options.addOption( Option.builder("z") .longOpt("zerofill") .desc("overwrite used padding with 0s") .build() ); if(args != null && args.length > 0) { CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { throw new RuntimeException("Could not parse args", e); } OneTimePad otp = new OneTimePad(); if(cmd.hasOption("c")) { File padFile = new File(cmd.getOptionValue("c")); long size = Long.parseLong(cmd.getOptionValue("s")); System.out.println("Creating pad file..."); otp.createPadFile(padFile, size); System.out.println("Done! " + size + " random bytes successfully written to " + padFile); } else if(cmd.hasOption("i") && cmd.hasOption("o") && cmd.hasOption("p")) { File inFile = new File(cmd.getOptionValue("i")); File outFile = new File(cmd.getOptionValue("o")); File padFile = new File(cmd.getOptionValue("p")); long offset = cmd.hasOption("f") ? Long.valueOf(cmd.getOptionValue("f")) : 0L; otp.setZeroFill(cmd.hasOption("z")); System.out.println("Padding data..."); offset = otp.padData(inFile, outFile, padFile, offset); System.out.println("Done! New padding offset: " + offset); } else { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(OneTimePad.class.getSimpleName(), options); } } else { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(OneTimePad.class.getSimpleName(), options); } System.exit(0); } }
23.809677
112
0.63677
7f79132b164b2490ca030958f77c7f402e9690c1
927
/* * WordController.java * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.aleggeup.confagrid.content; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.aleggeup.confagrid.model.Word; @Controller @RequestMapping("/api/v1") public class WordController { private final WordRepository wordRepository; @Autowired public WordController(final WordRepository wordRepository) { this.wordRepository = wordRepository; } @RequestMapping("words") @ResponseBody public List<Word> allWords() { return wordRepository.findAll(); } }
24.394737
64
0.750809
b809d72411c05acde1cd09471f6e482b8d54219e
912
import java.io.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader (System.in)); do{ String s = br.readLine(); System.out.println(rot(s)); } while (br.ready()); } static String rot(String s) { String aux = ""; int ini = 0, fim = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') { ini = (int)'A'; fim = (int)'Z'; } else if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') { ini = (int)'a'; fim = (int)'z'; } else { aux += s.charAt(i); continue; } if (((int)s.charAt(i) + 13) > fim) { aux += (char)(ini + (13 - (fim - (int)s.charAt(i))) - 1); } else { aux += (char)((int)s.charAt(i) + 13); } } return aux; } }
26.057143
82
0.458333
4f9c41bd94d16b8f9a3959d59bc0b46847faaba1
6,720
import static org.junit.Assert.*; import static org.junit.matchers.JUnitMatchers.*; import static org.hamcrest.CoreMatchers.*; import java.sql.Connection; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import model.Car; import model.CarDatabase; import model.Client; import model.ClientDatabase; import model.Manufacturer; import model.Model; import org.junit.Test; import view.FormEvent; import controller.Controller; public class TestController { @Test public void testConnectionValidCredentials() { Controller controller = new Controller(); try { controller.configure("H_B2WKL0", "kassai"); } catch (Exception e) { fail("Database Connection could not be established"); } assertNotNull(controller.getConnection()); } @Test public void testGetClients(){ Controller controller = new Controller(); try { controller.configure("H_B2WKL0", "kassai"); } catch (Exception e) { fail("Database Connection could not be established"); } controller.addClient(new FormEvent(this, "TesztUser", "TestPhoneNum", new Timestamp(Calendar.getInstance().getTimeInMillis()), "Audi", "R8", "AAA-000", "1999", "fekete", 13345)); List<Client> clientList = new ArrayList<Client>(); clientList = controller.getClients(); assertEquals(clientList.size(), 1); } @Test public void testGetCars(){ Controller controller = new Controller(); try { controller.configure("H_B2WKL0", "kassai"); } catch (Exception e) { fail("Database Connection could not be established"); } controller.addClient(new FormEvent(this, "TesztUser", "TestPhoneNum", new Timestamp(Calendar.getInstance().getTimeInMillis()), "Audi", "R8", "AAA-000", "1999", "fekete", 13345)); controller.addCar(new FormEvent(this, "TesztUser", "TestPhoneNum", new Timestamp(Calendar.getInstance().getTimeInMillis()), "Audi", "R8", "AAA-000", "1999", "fekete", 13345)); List<Car> carList = new ArrayList<Car>(); carList = controller.getCars(); assertEquals(carList.size(), 1); } @Test public void testClientAndCarRemoval(){ Controller controller = new Controller(); try { controller.configure("H_B2WKL0", "kassai"); } catch (Exception e) { fail("Database Connection could not be established"); } controller.addClient(new FormEvent(this, "TesztUser", "TestPhoneNum", new Timestamp(Calendar.getInstance().getTimeInMillis()), "Audi", "R8", "AAA-000", "1999", "fekete", 13345)); controller.addCar(new FormEvent(this, "TesztUser", "TestPhoneNum", new Timestamp(Calendar.getInstance().getTimeInMillis()), "Audi", "R8", "AAA-000", "1999", "fekete", 13345)); controller.removeClient(0); List<Client> clientList = new ArrayList<Client>(); clientList = controller.getClients(); assertEquals(clientList.get(0).isMarkedForDeletion(), true); List<Car> carList = new ArrayList<Car>(); carList = controller.getCars(); assertEquals(carList.get(0).isMarkedForDeletion(), true); } @Test(expected = IndexOutOfBoundsException.class) public void testDatabaseRelatedMethods() throws SQLException{ Controller controller = new Controller(); try { controller.configure("H_B2WKL0", "kassai"); } catch (Exception e) { fail("Database Connection could not be established"); } Connection connection = controller.getConnection(); connection.setAutoCommit(false); try{ controller.addClient(new FormEvent(this, "TesztUser", "TestPhoneNum", new Timestamp(Calendar.getInstance().getTimeInMillis()), "Audi", "R8", "AAA-000", "1999", "fekete", 13345)); controller.addCar(new FormEvent(this, "TesztUser", "TestPhoneNum", new Timestamp(Calendar.getInstance().getTimeInMillis()), "Audi", "R8", "AAA-000", "1999", "fekete", 13345)); controller.save(); controller.load(); List<Client> clientList = new ArrayList<Client>(); clientList = controller.getClients(); assertEquals(clientList.get(0).getName(), "TesztUser"); List<Car> carList = new ArrayList<Car>(); carList = controller.getCars(); assertEquals(carList.get(0).getClientName(), "TesztUser"); controller.removeClient(0); controller.remove(); controller.load(); clientList = new ArrayList<Client>(); clientList = controller.getClients(); assertNull(clientList.get(0).getName()); } finally { connection.rollback(); connection.close(); } } @Test public void testListManufacturers() throws SQLException{ Controller controller = new Controller(); try { controller.configure("H_B2WKL0", "kassai"); } catch (Exception e) { fail("Database Connection could not be established"); } List<Manufacturer> manList = new ArrayList<Manufacturer>(); manList = controller.loadManufacturers(); assertNotNull(manList.size()); } @Test public void testListModels() throws SQLException{ Controller controller = new Controller(); try { controller.configure("H_B2WKL0", "kassai"); } catch (Exception e) { fail("Database Connection could not be established"); } List<Model> modList = new ArrayList<Model>(); modList = controller.loadModels("Audi"); assertNotNull(modList.size()); } @Test public void testConnectAndDisconnect() throws SQLException{ Controller controller = new Controller(); try { controller.configure("H_B2WKL0", "kassai"); } catch (Exception e) { fail("Database Connection could not be established"); } controller.disconnect(); assertEquals(controller.getConnection().isClosed(), true); Controller controller2 = new Controller(); try { controller2.configure("H_B2WKL0", "kassai"); } catch (Exception e) { fail("Database Connection could not be established"); } try { controller2.connect(); } catch (Exception e) { fail("Database Connection could not be established"); } assertTrue(controller2.getConnection().isValid(10)); } @Test public void testAddClient(){ Controller controller = new Controller(); controller.addClient(new FormEvent(this, "TesztUser", "TestPhoneNum", new Timestamp(Calendar.getInstance().getTimeInMillis()), "Audi", "R8", "AAA-000", "1999", "fekete", 13345)); List<Client> clientList = new ArrayList<Client>(); clientList = controller.getClients(); assertEquals(clientList.get(0).getName(), "TesztUser"); } @Test public void testAddCar(){ Controller controller = new Controller(); controller.addCar(new FormEvent(this, "TesztUser", "TestPhoneNum", new Timestamp(Calendar.getInstance().getTimeInMillis()), "Audi", "R8", "AAA-000", "1999", "fekete", 13345)); List<Car> carList = new ArrayList<Car>(); carList = controller.getCars(); assertEquals(carList.get(0).getColor(), "fekete"); } }
33.103448
181
0.707887
e2d267c6f55253b1041c3b126e5f1ddfcdcc5ffe
219
package xdean.reflect.getter.internal.util; import java.util.concurrent.Callable; @FunctionalInterface public interface FuncE0<R, E extends Exception> extends Callable<R> { @Override R call() throws E; }
21.9
70
0.744292
214761f5f9b09c508abf20615ce80f330dfa72d4
1,839
package ua.arlabunakty.examples.jackson.serializer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.junit.jupiter.api.Test; import ua.arlabunakty.examples.jackson.model.Person; import java.util.Arrays; import java.util.List; public class CustomPersonCollectionToMapSerializerTest extends BaseTest { private final ObjectMapper objectMapper = new ObjectMapper(); @Test void serialize() throws JsonProcessingException { Person batMan = new Person(); batMan.setFirstName("Bruce"); batMan.setLastName("Wayne"); batMan.setSsn(1234567890L); Person batGirl = new Person(); batGirl.setFirstName("Barbara"); batGirl.setLastName("Gordon"); batGirl.setSsn(1234567891L); PersonLookup personLookup = new PersonLookup(Arrays.asList(batMan, batGirl)); String json = objectMapper.writeValueAsString(personLookup); assertEquals(aposToQuotes("{'personList':{'1234567890':'Bruce Wayne','1234567891':'Barbara Gordon'}}"), json); } public static class CustomPersonCollectionToMapSerializer extends StdCollectionToMapSerializer<Person> { @Override protected Object getMapValue(Person value) { return String.format("%s %s", value.getFirstName(), value.getLastName()); } @Override protected String getMapKey(Person value) { return value.getSsn().toString(); } } public class PersonLookup { @JsonSerialize(using = CustomPersonCollectionToMapSerializer.class) private final List<Person> personList; PersonLookup(List<Person> personList) { this.personList = personList; } } }
30.65
118
0.699837
ceb5594c452f5f882b70f7f02f855e33cc08540a
1,722
The central classes in Java for working with Date and Time are Date, DateFormat and Calendar. Date and Calendar classes are present in java.util package, while DateFormat is present in java.text package. Starting with Java version 8, many new classes and enhancements were introduced for handling date and time, these are bundled in a new package named java.time. We will learn about the new classes introduced in Java version 8 later. Since a lot of code written before Java 8, heavily use Date, DateFormat and Calendar classes, we will first learn about them. Date - represents an instance in time (stored as a primitive long). For example this moment. Though the name might suggest that it represents only a calendar date, like 7th July 1977, we should also remember that it actually has the time component to the precision of a millisecond. DateFormat - provides the formating for dates and times on an given Locale Calendar - provides methods to work with the instance of time represented by Date. It is important to note that earlier Unix systems used a 32-bit signed integer to store time. They started counting time with the value 0 representing 1970-1-1 00:00:00. This is referred as the epoch time. The time component represented by the Date object counts the milliseconds passed from the above mentioned epoch time. See and retype the below code. package q11315; import java.util.*; public class DateDemo { public static void main(String ... args) { Date thisMoment = new Date(); long millisecondsSinceEpochStart = thisMoment.getTime(); System.out.println("This Moment : " + thisMoment); System.out.println("Total milli seconds from epoch to this moment : " + millisecondsSinceEpochStart); } }
59.37931
282
0.787456
61ebeecbc3e4bb7f4b1fb06e2d66c2e9a2d6cbfa
3,514
package org.apereo.cas.web; import org.apereo.cas.configuration.model.support.captcha.GoogleRecaptchaProperties; import org.apereo.cas.services.RegisteredServiceProperty; import org.apereo.cas.services.ServicesManager; import org.apereo.cas.util.RegexUtils; import org.apereo.cas.web.support.WebUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.StringUtils; import org.apereo.inspektr.common.web.ClientInfo; import org.apereo.inspektr.common.web.ClientInfoHolder; import org.springframework.webflow.execution.RequestContext; import java.util.Optional; import java.util.Set; /** * This is {@link DefaultCaptchaActivationStrategy}. * * @author Misagh Moayyed * @since 6.5.0 */ @RequiredArgsConstructor @Slf4j public class DefaultCaptchaActivationStrategy implements CaptchaActivationStrategy { private final ServicesManager servicesManager; private static Optional<GoogleRecaptchaProperties> evaluateResult(final boolean result, final GoogleRecaptchaProperties properties) { return result ? Optional.of(properties) : Optional.empty(); } @Override public Optional<GoogleRecaptchaProperties> shouldActivate(final RequestContext requestContext, final GoogleRecaptchaProperties properties) { val service = WebUtils.getService(requestContext); val registeredService = servicesManager.findServiceBy(service); if (RegisteredServiceProperty.RegisteredServiceProperties.CAPTCHA_ENABLED.isAssignedTo(registeredService)) { LOGGER.trace("Checking for activation of captcha defined for service [{}]", registeredService); if (RegisteredServiceProperty.RegisteredServiceProperties.CAPTCHA_IP_ADDRESS_PATTERN.isAssignedTo(registeredService)) { val ip = Optional.ofNullable(ClientInfoHolder.getClientInfo()) .map(ClientInfo::getClientIpAddress).orElse(StringUtils.EMPTY).trim(); LOGGER.trace("Checking for activation of captcha defined for service [{}] based on IP address [{}]", registeredService, ip); val ipPattern = RegisteredServiceProperty.RegisteredServiceProperties.CAPTCHA_IP_ADDRESS_PATTERN.getPropertyValues(registeredService, Set.class); val result = ipPattern.stream().anyMatch(pattern -> RegexUtils.find(pattern.toString().trim(), ip)); return evaluateResult(result, properties); } val result = RegisteredServiceProperty.RegisteredServiceProperties.CAPTCHA_ENABLED.getPropertyBooleanValue(registeredService); return evaluateResult(result, properties); } if (StringUtils.isNotBlank(properties.getActivateForIpAddressPattern())) { val ip = Optional.ofNullable(ClientInfoHolder.getClientInfo()) .map(ClientInfo::getClientIpAddress).orElse(StringUtils.EMPTY); LOGGER.debug("Remote IP address [{}] will be checked against [{}]", ip, properties.getActivateForIpAddressPattern()); val activate = RegexUtils.find(properties.getActivateForIpAddressPattern(), ip); return evaluateResult(activate, properties); } LOGGER.trace("Checking for activation of captcha defined under site key [{}]", properties.getSiteKey()); return evaluateResult(properties.isEnabled(), properties); } }
50.2
161
0.7214
3e13640f6bbec93bb6bddc3ff7fbeec66cce6d0d
103
package br.com.zupacademy.haline.proposta.carteira; public enum TipoCarteira { PAYPAL, SAMSUNGPAY }
14.714286
51
0.796117
361def3175b8a96975e57e248d8b3f153e91508a
3,437
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kazzz.nfc; import net.kazzz.util.Util; import android.content.Intent; import android.os.Parcel; import android.os.Parcelable; /** * NFC規格で使用するタグを抽象化したクラス提供します * * @author Kazzz, k_morishita * @date 2011/02/19 * @since Android API Level 9 * */ public class NfcTag implements Parcelable { //private static String TAG = "NfcTag"; public static final String ANDROID_NFC_EXTRA_TAG = "android.nfc.extra.TAG"; public static final Parcelable.Creator<NfcTag> CREATOR = new Parcelable.Creator<NfcTag>() { public NfcTag createFromParcel(Parcel in) { return new NfcTag(in); } public NfcTag[] newArray(int size) { return new NfcTag[size]; } }; protected byte[] idbytes; protected Parcelable nfcTag; /** * デフォルトコンストラクタ */ public NfcTag() { } /** * コンストラクタ * @param in */ public NfcTag(Parcel in) { this(); this.readFromParcel(in); } /** * コンストラクタ * * @param nfcTag NfcTagをセット * @param id タグを識別するバイト列をセット */ public NfcTag(Parcelable nfcTag, byte[] id) { this(); this.nfcTag = nfcTag; this.idbytes = id; } /** * Nfcタグを取得します * @return Parcelable 内部に格納したNfcTagが戻ります */ public Parcelable getNfcTag() { return nfcTag; } /* (non-Javadoc) * @see android.os.Parcelable#describeContents() */ @Override public int describeContents() { return 0; } /* (non-Javadoc) * @see android.os.Parcelable#writeToParcel(android.os.Parcel, int) */ @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.idbytes.length); dest.writeByteArray(this.idbytes); dest.writeParcelable(this.nfcTag, 0); } /** * Parcel内からインスタンスを構成します * @param source パーセルオブジェクトをセット */ public void readFromParcel(Parcel source) { this.idbytes = new byte[source.readInt()]; source.readByteArray(this.idbytes); this.nfcTag = source.readParcelable(this.getClass().getClassLoader()); } /** * インテントをタグ情報をセットします * @param intent インテントをセット */ public void putTagService(Intent intent) { intent.putExtra(ANDROID_NFC_EXTRA_TAG, this.nfcTag); } /** * IDを取得します * @return byte[] IDが戻ります */ public byte[] getId() { return idbytes; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("NfcTag \n"); sb.append(" idbytes:" + Util.getHexString(this.idbytes) + "\n"); sb.append(" nfcTag: " + this.nfcTag.toString() + "\n"); return sb.toString(); } }
26.438462
79
0.60867
b209084dc68c4048a8d896b3c6199b9dbb723c17
311
package models.headout; import com.google.gson.annotations.SerializedName; /** * Created by madki on 17/06/16. */ public class Currency { public String code; @SerializedName("currencyName") public String name; public String symbol; public String localSymbol; public int precision; }
19.4375
50
0.713826
9a9d3ec502d941cec152e95911d3ed62929c2276
2,774
package exercise; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Fractional_Knapsack { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); List<Item> items = new ArrayList<>(); double capacity = Double.parseDouble(reader.readLine().split(": ")[1]); double itemsCount = Double.parseDouble(reader.readLine().split(": ")[1]); for (int i = 0; i < itemsCount; i++) { double[] tokens = Arrays.stream(reader.readLine() .split(" -> ")) .mapToDouble(Double::parseDouble) .toArray(); Item currentItem = new Item(tokens[0], tokens[1]); items.add(currentItem); } items.sort((x, y) -> { double ratioFirstItem = x.getPrice() / x.getWeight(); double ratioSecondItem = y.getPrice() / y.getWeight(); if (ratioFirstItem >= ratioSecondItem) { return -1; } return 1; }); int count = 0; double totalPrice = 0; while (capacity > 0 && count < itemsCount) { double currentItemPrice = items.get(count).getPrice(); double currentItemWeight = items.get(count).getWeight(); if (capacity >= currentItemWeight) { capacity -= currentItemWeight; System.out.println(String.format("Take 100%% of item with price %.2f and weight %.2f", currentItemPrice, currentItemWeight)); } else { double percentage = (capacity / currentItemWeight)* 100; System.out.println(String.format("Take %.2f%% of item with price %.2f and weight %.2f", percentage, currentItemPrice, currentItemWeight)); capacity -= currentItemWeight; currentItemPrice = (percentage / 100) * currentItemPrice; } count++; totalPrice += currentItemPrice; } System.out.println(String.format("Total price: %.2f", totalPrice)); } } class Item { private double price; private double weight; public Item(double price, double weight) { this.price = price; this.weight = weight; } public double getPrice() { return this.price; } public void setPrice(double price) { this.price = price; } public double getWeight() { return this.weight; } public void setWeight(double weight) { this.weight = weight; } }
28.597938
103
0.569214
79481b693627f939928343e17c74ad8945d956c2
1,891
package de.metas.jmx; import java.util.Arrays; import java.util.Properties; import org.adempiere.ad.migration.logger.MigrationScriptFileLoggerHolder; import org.adempiere.ad.trx.api.ITrxManager; import org.adempiere.util.trxConstraints.api.IOpenTrxBL; import org.compiere.util.Env; import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.stereotype.Service; import ch.qos.logback.classic.Level; import de.metas.cache.CacheMgt; import de.metas.logging.LogManager; import de.metas.util.Services; @Service @ManagedResource(objectName = "de.metas:type=metasfresh", description = "Provides basic operations on the running metasfresh instance") public class Metasfresh { @ManagedOperation public String[] getActiveTrxNames() { return Services.get(ITrxManager.class) .getActiveTransactionsList() .stream() .map((trx) -> trx.getTrxName()) .toArray((size) -> new String[size]); } @ManagedOperation public String getStrackTrace(String trxName) { return Services.get(IOpenTrxBL.class).getCreationStackTrace(trxName); } @ManagedOperation public String[] getServerContext() { final Properties ctx = Env.getCtx(); String[] context = Env.getEntireContext(ctx); Arrays.sort(context); return context; } @ManagedOperation public void setLogLevel(String levelName) { LogManager.setLevel(levelName); } @ManagedOperation public String getLogLevel() { final Level level = LogManager.getLevel(); return level == null ? null : level.toString(); } @ManagedOperation public void runFinalization() { System.runFinalization(); } @ManagedOperation public void resetLocalCache() { CacheMgt.get().reset(); } @ManagedOperation public void rotateMigrationScriptFile() { MigrationScriptFileLoggerHolder.closeMigrationScriptFiles(); } }
23.6375
135
0.769963
fd0868184526582e32a6b84cad059f786d3d66ef
219
package controller.character.helpers; /** * Classes in this package contain constants to determine a character's starting * attributes, and distributable points (like money or skills). * @author Daradics Levente */
31.285714
80
0.771689
82738baf4504a6ea81b137f55c4866fef1da0e7f
1,973
import java.util.Scanner; public class Fetchingfromarray { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // int rollnumber[] = new int[5]; // String name[] = new String[5]; // long phno[] = new long[5]; // for(int i=0; i<5; i++) // { // System.out.println("\nEnter roll number:"); // rollnumber[i] = sc.nextInt(); // System.out.println("\n Enter name:"); // name[i] = sc.next(); // System.out.println("\n Enter phone number:"); // phno[i] = sc.nextLong(); // } int rollnumber[] = {101,102,103,104,105}; String name[] = {"Gokul","Balaji","Dharmesh","Arul","Shiva"}; long phno[] = {7339261262l,9999999999l,777777777777l,1234566777l,173333333333l}; System.out.println("Enter number "); int n = sc.nextInt(); switch(n) { case 1: System.out.println("Enter the roll number to search:"); int a =sc.nextInt(); for(int i=0;i<5;i++) { if(a==rollnumber[i]) { // System.out.println(i); System.out.println("Rollnumber:"+rollnumber[i]+"\n Name:"+name[i]+"\n Phone Number:"+phno[i]); break; } } break; case 2: System.out.println("Enter the name to search:"); String b= sc.next(); for(int i=0;i<5;i++) { if(b.equalsIgnoreCase(name[i])) { // System.out.println(i); System.out.println("Rollnumber:"+rollnumber[i]+"\n Name:"+name[i]+"\n Phone Number:"+phno[i]); break; } } break; case 3: System.out.println("Enter the phone number to search:"); long ph = sc.nextLong(); for(int i=0;i<5;i++) { if(ph == phno[i]) { // System.out.println(i); System.out.println("Rollnumber:"+rollnumber[i]+"\n Name:"+name[i]+"\n Phone Number:"+phno[i]); break; } } break; default: System.out.println("Invalid number"); } } }
20.768421
99
0.535732
a8be468f23c0be5eda8bd19898d601951ac260e3
5,458
/******************************************************************************* * Copyright (C) 2017, Paul Scerri, Sean R Owens * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ /* * UnattendedGroundSensor.java * * Created on March 8, 2006, 3:50 PM * */ package AirSim.Environment.Assets; import AirSim.Machinetta.Messages.RPMessage; import java.util.LinkedList; /** * * @author pscerri */ public class UnattendedGroundSensor extends Asset { public final static double DEFAULT_RANGE = 3000.0; private boolean detectAir = false; private boolean directional = false; private boolean strengthIndicator = false; private boolean typeIndicator = false; private double range = DEFAULT_RANGE; protected LinkedList possible; /** Creates a new instance of UnattendedGroundSensor */ public UnattendedGroundSensor(String name, int x, int y, double range) { super(name, x, y, 0, null, 0.0); super.reportLocationRate = -1; this.range = range; hasProxy = true; } public UnattendedGroundSensor(String name, int x, int y) { this(name, x, y, DEFAULT_RANGE); } private long senseCounter = 0, notFound = 0; public void sense() { if (++senseCounter % 300 == 0) { possible = null; if (detectAir) { possible = env.getAssetsInBox((int)(location.x-range), (int)(location.y-range), 0, (int)(location.x+range), (int)(location.y+range), 10000); } else { possible = env.getAssetsInBox((int)(location.x-range), (int)(location.y-range), -50, (int)(location.x+range), (int)(location.y+range), 50); } // @todo Handle type, direction, etc. indicators boolean found = false; for (Object o: possible) { Asset a = (Asset)o; if (a != this) { // System.out.println("Sensing : " + a); found = true; } } if (found) { // Send up a sensor reading RPMessage msg = new RPMessage(RPMessage.MessageTypes.SEARCH_SENSOR_READING); msg.params.add((int)location.x); msg.params.add((int)location.y); msg.params.add(true); sendToProxy(msg); notFound = 0; } else { notFound++; if (notFound % 10 == 0) { RPMessage msg = new RPMessage(RPMessage.MessageTypes.SEARCH_SENSOR_READING); msg.params.add((int)location.x); msg.params.add((int)location.y); msg.params.add(false); sendToProxy(msg); } } } } public Asset.Types getType() { return Asset.Types.UGS; } public boolean isDetectAir() { return detectAir; } public void setDetectAir(boolean detectAir) { this.detectAir = detectAir; } public boolean isDirectional() { return directional; } public void setDirectional(boolean directional) { this.directional = directional; } public boolean isStrengthIndicator() { return strengthIndicator; } public void setStrengthIndicator(boolean strengthIndicator) { this.strengthIndicator = strengthIndicator; } public boolean isTypeIndicator() { return typeIndicator; } public void setTypeIndicator(boolean typeIndicator) { this.typeIndicator = typeIndicator; } public double getRange() { return range; } public void setRange(double range) { this.range = range; } }
34.544304
101
0.59399
e374da2c354257707208a234d718bf19b13a7877
4,926
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.analytics.financial.forex.definition; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import org.testng.annotations.Test; import org.threeten.bp.ZonedDateTime; import com.opengamma.analytics.financial.forex.derivative.ForexOptionSingleBarrier; import com.opengamma.analytics.financial.model.option.definition.Barrier; import com.opengamma.analytics.financial.model.option.definition.Barrier.BarrierType; import com.opengamma.analytics.financial.model.option.definition.Barrier.KnockType; import com.opengamma.analytics.financial.model.option.definition.Barrier.ObservationType; import com.opengamma.util.money.Currency; import com.opengamma.util.time.DateUtils; /** * */ public class ForexOptionSingleBarrierDefinitionTest { private static final Currency CCY1 = Currency.AUD; private static final Currency CCY2 = Currency.CAD; private static final ZonedDateTime EXCHANGE = DateUtils.getUTCDate(2011, 12, 5); private static final double AMOUNT = 1000; private static final double RATE = 1.5; private static final double REBATE = 0.5; private static final ForexDefinition FOREX = new ForexDefinition(CCY1, CCY2, EXCHANGE, AMOUNT, RATE); private static final ZonedDateTime EXPIRY = DateUtils.getUTCDate(2011, 12, 1); private static final boolean IS_CALL = true; private static final boolean IS_LONG = true; private static final ForexOptionVanillaDefinition UNDERLYING = new ForexOptionVanillaDefinition(FOREX, EXPIRY, IS_CALL, IS_LONG); private static final Barrier BARRIER = new Barrier(KnockType.IN, BarrierType.DOWN, ObservationType.CLOSE, 1); private static final ForexOptionSingleBarrierDefinition OPTION = new ForexOptionSingleBarrierDefinition(UNDERLYING, BARRIER); private static final ForexOptionSingleBarrierDefinition OPTION_REBATE = new ForexOptionSingleBarrierDefinition(UNDERLYING, BARRIER, REBATE); private static final ZonedDateTime DATE = DateUtils.getUTCDate(2011, 7, 1); @Test(expectedExceptions = IllegalArgumentException.class) public void testNullUnderlying() { new ForexOptionSingleBarrierDefinition(null, BARRIER); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullBarrier() { new ForexOptionSingleBarrierDefinition(UNDERLYING, null); } @SuppressWarnings("deprecation") @Test(expectedExceptions = IllegalArgumentException.class) public void testNullDateDeprecated() { OPTION.toDerivative(null, "A", "B"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullDate() { OPTION.toDerivative(null); } @SuppressWarnings("deprecation") @Test(expectedExceptions = IllegalArgumentException.class) public void testNullNames() { OPTION.toDerivative(DATE, (String[]) null); } @Test public void testObject() { assertEquals(UNDERLYING, OPTION.getUnderlyingOption()); assertEquals(BARRIER, OPTION.getBarrier()); assertEquals(0.0, OPTION.getRebate(), 1.0E-10); assertEquals(UNDERLYING, OPTION_REBATE.getUnderlyingOption()); assertEquals(BARRIER, OPTION_REBATE.getBarrier()); assertEquals(REBATE, OPTION_REBATE.getRebate(), 1.0E-10); assertEquals(OPTION, OPTION); ForexOptionSingleBarrierDefinition other = new ForexOptionSingleBarrierDefinition(UNDERLYING, BARRIER); assertEquals(OPTION, other); assertEquals(OPTION.hashCode(), other.hashCode()); final ForexOptionSingleBarrierDefinition otherRebate = new ForexOptionSingleBarrierDefinition(UNDERLYING, BARRIER, REBATE); assertEquals(OPTION_REBATE, otherRebate); assertEquals(OPTION_REBATE.hashCode(), otherRebate.hashCode()); other = new ForexOptionSingleBarrierDefinition(new ForexOptionVanillaDefinition(FOREX, EXPIRY, !IS_CALL, IS_LONG), BARRIER); assertFalse(other.equals(OPTION)); other = new ForexOptionSingleBarrierDefinition(UNDERLYING, new Barrier(KnockType.OUT, BarrierType.DOWN, ObservationType.CLOSE, 1)); assertFalse(other.equals(OPTION)); assertFalse(OPTION_REBATE.equals(OPTION)); assertFalse(OPTION_REBATE.equals(BARRIER)); assertFalse(OPTION_REBATE.equals(null)); } @SuppressWarnings("deprecation") @Test public void testToDerivativeDeprecated() { final String[] names = new String[] {"USD", "EUR"}; final ForexOptionSingleBarrier derivative = OPTION.toDerivative(DATE, names); assertEquals(derivative.getUnderlyingOption(), UNDERLYING.toDerivative(DATE, names)); assertEquals(derivative.getBarrier(), BARRIER); } @Test public void testToDerivative() { final ForexOptionSingleBarrier derivative = OPTION.toDerivative(DATE); assertEquals(derivative.getUnderlyingOption(), UNDERLYING.toDerivative(DATE)); assertEquals(derivative.getBarrier(), BARRIER); } }
45.192661
142
0.784612
2d29df15e9149ffa3290ecbde401863f9add980f
2,423
package com.anair.demo.component.movieratingsplitter.service; import com.anair.demo.component.movieratingsplitter.model.Film; import com.anair.demo.component.movieratingsplitter.model.FilmRating; import com.anair.demo.component.movieratingsplitter.model.Movie; import com.anair.demo.component.movieratingsplitter.util.JSONUtil; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Collections; import java.util.Iterator; import static com.anair.demo.component.movieratingsplitter.util.SplitterConstants.MOVIE_TITLE; import static com.anair.demo.component.movieratingsplitter.util.SplitterConstants.NUM_RATINGS; import static com.anair.demo.component.movieratingsplitter.util.SplitterHelper.isEmpty; @Component public class RatingsTransformer implements Processor { private static final Logger LOGGER = LoggerFactory.getLogger(RatingsTransformer.class); @Override public void process(final Exchange exchange) { Movie movie = exchange.getIn().getBody(Movie.class); LOGGER.info("Received Movie titled [{}] with [{}] movie ratings", exchange.getProperty(MOVIE_TITLE, String.class), exchange.getProperty(NUM_RATINGS, Integer.class)); if (isEmpty(movie.getRatings())) { exchange.getIn().setBody( Collections.singletonList(createUnratedRatings(movie)).iterator()); } else { Iterator<String> ratingsIterator = movie.getRatings().stream() .map(ratings -> new FilmRating(ratings.getSource(), ratings.getValue(), new Film(movie))) .map(filmRating -> { try { return JSONUtil.toJsonString(filmRating); } catch (IOException e) { throw new UncheckedIOException(e); } }).iterator(); exchange.getIn().setBody(ratingsIterator); } } private String createUnratedRatings(Movie movie) { try { return JSONUtil.toJsonString(new FilmRating("Unrated", "Unrated", new Film(movie))); } catch (IOException e) { throw new UncheckedIOException(e); } } }
39.080645
109
0.678085
541dd49f5181ea2fb55ae96643daab37ac5b4b44
4,005
package com.example.hajken.helpers; import android.content.Context; import android.graphics.PointF; import android.util.AndroidRuntimeException; import android.util.Log; import java.lang.reflect.Array; import java.util.ArrayList; public class MathUtility { private static final String TAG = "MathUtility"; private static MathUtility mInstance = null; private Context myContext; private MathUtility(Context context){ myContext = context; } public static MathUtility getInstance(Context context){ if (mInstance == null){ mInstance = new MathUtility(context); } return mInstance; } private double perpendicularDistance (PointF point, PointF lineStart, PointF lineEnd){ double dx = lineEnd.x - lineStart.x; double dy = lineEnd.y - lineStart.y; double mag = Math.hypot(dx,dy); if (mag > 0.0) { dx /= mag; dy /= mag; } double pvx = point.x - lineStart.x; double pvy = point.y - lineStart.y; double pvdot = dx * pvx + dy * pvy; double ax = pvx - pvdot * dx; double ay = pvy - pvdot * dy; return Math.hypot(ax, ay); } //https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker_algorithm ArrayList<PointF> rdpSimplifier(ArrayList<PointF> listOfCoordinates, double epsilon){ double dmax = 0.0; int index = 0; int end = listOfCoordinates.size() - 1; for (int i = 2; i < end ; i++) { double d = perpendicularDistance(listOfCoordinates.get(i) , listOfCoordinates.get(0), listOfCoordinates.get(end)); if (d > dmax){ index = i; dmax = d; } } ArrayList<PointF> resultList = new ArrayList<>(); if (dmax > epsilon) { ArrayList<PointF> subList1 = new ArrayList<>(listOfCoordinates.subList(0, index)); ArrayList<PointF> subList2 = new ArrayList<>(listOfCoordinates.subList(index+1, end)); ArrayList<PointF> recResults1 = rdpSimplifier( subList1, epsilon); ArrayList<PointF> recResults2 = rdpSimplifier( subList2, epsilon); resultList.addAll(recResults1); resultList.addAll(recResults2); } else { Log.d(TAG, "rdpSimplifier: ELSE " + listOfCoordinates.toString()); resultList.add(listOfCoordinates.get(0)); resultList.add(listOfCoordinates.get(end)); } return resultList; } float getMagnitude(PointF pointA, PointF pointB){ return (float) Math.sqrt(Math.pow((pointB.x-pointA.x),2)+Math.pow((pointB.y-pointA.y),2)); } ArrayList<Float> getRotation(PointF pointA, PointF pointB, float prevDegrees){ float diffY = pointB.y - pointA.y; float diffX = pointB.x - pointA.x; float atan = (float) Math.atan(Math.abs(diffY) / Math.abs(diffX)); float degrees = (float) Math.toDegrees(atan); float actualRotation; ArrayList<Float> angles = new ArrayList<>(); if (diffY > 0){ //in quadrant 1 --- rotate right if (diffX > 0){ degrees = 90 - degrees; } else { // in quadrant 2 --- rotate left degrees = (90-degrees)*-1; } } else { //in quadrant 3 ----- rotate left if (diffX < 0){ degrees = (degrees+90)*-1; } else { //in quadrant 4 --- rotate right degrees = degrees+90; } } actualRotation = degrees-prevDegrees; if (actualRotation > 180){ actualRotation = actualRotation-180; } if (actualRotation < -180){ actualRotation = 360 + actualRotation; } angles.add(actualRotation); angles.add(degrees); Log.d(TAG, "degree : here "); return angles; } }
27.62069
126
0.571536
04b144d9fc4db8ab7ecb45b27200bc7f7b4530a2
1,001
package commandline.language.parser.specific; import commandline.exception.ArgumentNullException; import commandline.language.parser.ArgumentParseException; import commandline.language.parser.ArgumentParser; import org.jetbrains.annotations.NotNull; /** * User: gno, Date: 09.07.13 - 10:46 */ public class BooleanArgumentParser extends ArgumentParser<Boolean> { public BooleanArgumentParser() { super(); } @Override public boolean isCompatibleWithOutputClass(@NotNull Class<?> clazz) { return clazz.isAssignableFrom(boolean.class) || clazz.isAssignableFrom(Boolean.class); } @NotNull @Override public Boolean parse(@NotNull String value) { if (value == null) { throw new ArgumentNullException(); } if (!value.equals("true") && !value.equals("false")) { throw new ArgumentParseException(String.format( "The value \"%s\" could not been parsed to a boolean, because only the values true and false are accepted.", value)); } return Boolean.valueOf(value); } }
28.6
113
0.746254
e408fc1ca2fa4a323002fc444ec59be24270e9cd
4,835
package com.example.betterbuy; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.HashMap; public class RegisterActivity extends AppCompatActivity { private Button CreateAccountButton; private EditText InputName, InputPhoneNumber, InputPassword; private ProgressDialog loadingBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); CreateAccountButton = (Button) findViewById(R.id.register_btn); InputName = (EditText) findViewById(R.id.register_username_input); InputPhoneNumber = (EditText) findViewById(R.id.register_phone_number_input); InputPassword = (EditText) findViewById(R.id.register_password_input); CreateAccountButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CreateAccount(); } }); } public void CreateAccount() { String name = InputName.getText().toString(); String phone = InputPhoneNumber.getText().toString(); String password = InputPassword.getText().toString(); loadingBar = new ProgressDialog(this); if(TextUtils.isEmpty(name)) { Toast.makeText(this,"Please write your name...",Toast.LENGTH_SHORT).show(); } else if(TextUtils.isEmpty(phone)) { Toast.makeText(this,"Please write your phone...",Toast.LENGTH_SHORT).show(); } else if(TextUtils.isEmpty(password)) { Toast.makeText(this,"Please write your password...",Toast.LENGTH_SHORT).show(); } else{ loadingBar.setTitle("Create Account"); loadingBar.setMessage("Please wait,while we are checking the credentials"); loadingBar.setCanceledOnTouchOutside(false); loadingBar.show(); ValidatephoneNumber(name,phone,password); } } private void ValidatephoneNumber(String name,String phone,String password){ final DatabaseReference RootRef; RootRef = FirebaseDatabase.getInstance().getReference(); RootRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if(!(dataSnapshot.child("users").child(phone).exists())) { HashMap<String,Object>userdataMap = new HashMap<>(); userdataMap.put("phone",phone); userdataMap.put("password",password); userdataMap.put("name",name); RootRef.child("users").child(phone).updateChildren(userdataMap) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { Toast.makeText(RegisterActivity.this,"Congratulations,your account has been created",Toast.LENGTH_SHORT).show(); loadingBar.dismiss(); Intent intent = new Intent(RegisterActivity.this,LoginActivity.class); startActivity(intent); } else{ Toast.makeText(RegisterActivity.this,"Network Error:Please try again after some time...",Toast.LENGTH_SHORT).show(); loadingBar.dismiss(); } } }); } else{ Toast.makeText(RegisterActivity.this,"This"+ phone + "already exists",Toast.LENGTH_SHORT).show(); loadingBar.dismiss(); Toast.makeText(RegisterActivity.this,"Please try again using another phone number",Toast.LENGTH_SHORT).show(); Intent intent = new Intent(RegisterActivity.this,MainActivity.class); startActivity(intent); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } }
39.308943
148
0.637435
6500ae8c015eba23aa218e81f0bab08d2ccc5710
1,362
/* https://leetcode.com/problems/largest-rectangle-in-histogram/description/ Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]. The largest rectangle is shown in the shaded area, which has area = 10 unit. Example: Input: [2,1,5,6,2,3] Output: 10 */ class Solution { private int solve(int[] h, int s, int e) { if (s == e) { return h[s]; } int m = s + (e-s)/2; int max = Math.max(solve(h,s,m),solve(h,m+1,e)); int l = m; int r = m+1; int height = Math.min(h[l],h[r]); max = Math.max(max, height * (r - l + 1)); while (l > s || r < e) { if (r >= e || (l > s && h[l-1] > h[r+1])) { l--; height = Math.min(height,h[l]); } else { r++; height = Math.min(height,h[r]); } max = Math.max(max,height * (r - l + 1)); } return max; } public int largestRectangleArea(int[] heights) { if (heights.length == 0) { return 0; } return solve(heights, 0, heights.length -1); } }
23.482759
156
0.490455
86f4ad8c9b9b6edbf3344ffba809df633c46d725
1,232
import java.util.*; public class RemoveInRangeSplit{ public static void main(String[] args){ Scanner console = new Scanner(System.in); System.out.print("\nPlease enter an alphabetical sequence of strings separated\n"+ "by spaces. The end of the sequence must be signified using\n"+ "the sentinel value lastString, followed by a return.\n\n"); String input = console.nextLine(); String[] tempArr = input.split(" "); ArrayList<String> inputs = new ArrayList<String>(); for (int i = 0; i < tempArr.length; i++){ if (tempArr[i].equals("lastString")){ break; } inputs.add(tempArr[i]); } System.out.println("Your original list: " + inputs.toString()); System.out.println("\nNow please enter your start String\n"); String begin = console.nextLine(); System.out.println("Finally, please enter your end String\n"); String end = console.nextLine(); ArrayList<String> reduced = new ArrayList<String>(); for (int i = 0; i < inputs.size(); i++){ String current = inputs.get(i); if (current.compareTo(begin) < 0){ reduced.add(current); } else if (current.compareTo(end) > 0){ reduced.add(current); } } System.out.print("Your reduced list: " + reduced.toString() + "\n"); } }
37.333333
209
0.671266
86cba6352e2a0f0d2ceeae7fd20f5f28e048e3bf
1,835
/* * 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.sling.testing.mock.sling; import javax.jcr.RepositoryException; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.commons.testing.jcr.RepositoryProvider; import org.apache.sling.jcr.api.SlingRepository; import org.apache.sling.jcr.resource.internal.helper.jcr.PathMapper; import org.apache.sling.testing.mock.osgi.MockOsgi; import org.osgi.framework.BundleContext; public class MockResolverProvider { private MockResolverProvider() { } public static ResourceResolver getResourceResolver() throws RepositoryException, LoginException { final SlingRepository repository = RepositoryProvider.instance().getRepository(); final BundleContext bundleContext = MockOsgi.newBundleContext(); bundleContext.registerService(PathMapper.class.getName(), new PathMapper(), null); return new MockJcrResourceResolverFactory(repository, bundleContext).getAdministrativeResourceResolver(null); } }
45.875
117
0.782016
2bc9bc6c2f1e6ff127e5247e34fe64ccd72b8571
3,327
package com.kaba.planner.entity; import java.io.Serializable; import java.util.Collection; import java.util.Objects; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * City entity * * @author Kaba N'faly * @since 12/02/2016 * @version 2.0 */ @Entity @Table(name = "city") @XmlRootElement public class City implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Basic(optional = false) @Column(name = "name") private String name; @Basic(optional = false) @Column(name = "country") private String country; @JoinTable(name = "city_has_employee", joinColumns = { @JoinColumn(name = "city_id", referencedColumnName = "id")}, inverseJoinColumns = { @JoinColumn(name = "employee_id", referencedColumnName = "id") }) @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Collection<Employee> employeeCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "city", fetch = FetchType.LAZY) private Collection<Workplace> workplaceCollection; public City() { } public City(String name, String country) { this.name = name; this.country = country; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Collection<Employee> getEmployeeCollection() { return employeeCollection; } public void setEmployeeCollection(Collection<Employee> employeeCollection) { this.employeeCollection = employeeCollection; } @XmlTransient public Collection<Workplace> getWorkplaceCollection() { return workplaceCollection; } public void setWorkplaceCollection(Collection<Workplace> workplaceCollection) { this.workplaceCollection = workplaceCollection; } @Override public int hashCode() { return Objects.hash(id); } @Override public boolean equals(Object object) { if (!(object instanceof City)) { return false; } City other = (City) object; if (!Objects.equals(id, other.id)) { return false; } return true; } @Override public String toString() { return String.format("City[ id = %d, Name = %s , Country = %s ]\n", id, name, country); } }
24.463235
95
0.658251
529f4d023099db03e4f730b4fe963f20c34b525f
2,921
package com.sequenceiq.cloudbreak.cloud.aws.connector.resource; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import java.util.Collections; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import com.sequenceiq.cloudbreak.cloud.context.AuthenticatedContext; import com.sequenceiq.cloudbreak.cloud.model.DatabaseServer; import com.sequenceiq.cloudbreak.cloud.model.DatabaseStack; import com.sequenceiq.cloudbreak.cloud.notification.PersistenceNotifier; public class AwsResourceConnectorTest { private static final String DB_INSTANCE_IDENTIFIER = "dbInstance"; @Mock private AuthenticatedContext authenticatedContext; @Mock private DatabaseStack dbStack; @Mock private DatabaseServer databaseServer; @Mock private AwsRdsStatusLookupService awsRdsStatusLookupService; @Mock private AwsRdsModifyService awsRdsModifyService; @Mock private AwsRdsTerminateService awsRdsTerminateService; @InjectMocks private AwsResourceConnector awsResourceConnector; @Before public void initTests() { initMocks(this); when(dbStack.getDatabaseServer()).thenReturn(databaseServer); when(databaseServer.getServerId()).thenReturn(DB_INSTANCE_IDENTIFIER); } @Test public void terminateDatabaseServerWithDeleteProtectionTest() throws Exception { PersistenceNotifier persistenceNotifier = mock(PersistenceNotifier.class); when(awsRdsStatusLookupService.isDeleteProtectionEnabled(authenticatedContext, dbStack)).thenReturn(true); awsResourceConnector.terminateDatabaseServer(authenticatedContext, dbStack, Collections.emptyList(), persistenceNotifier, true); verify(awsRdsModifyService, times(1)).disableDeleteProtection(any(), any()); verify(awsRdsTerminateService, times(1)).terminate(authenticatedContext, dbStack, true, persistenceNotifier, Collections.emptyList()); } @Test public void terminateDatabaseServerWithOutDeleteProtectionTest() throws Exception { PersistenceNotifier persistenceNotifier = mock(PersistenceNotifier.class); when(awsRdsStatusLookupService.isDeleteProtectionEnabled(authenticatedContext, dbStack)).thenReturn(false); awsResourceConnector.terminateDatabaseServer(authenticatedContext, dbStack, Collections.emptyList(), persistenceNotifier, true); verify(awsRdsModifyService, times(0)).disableDeleteProtection(any(), any()); verify(awsRdsTerminateService, times(1)).terminate(authenticatedContext, dbStack, true, persistenceNotifier, Collections.emptyList()); } }
36.974684
115
0.772681
1a3ca5f4feb8a041576de109b3a75dbfd1159177
1,703
/** * Copyright 2019 Sven Loesekann 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 ch.xxx.manager.usecase.service; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; public class ServiceUtils { public final static String PORTFOLIO_MARKER = "äüè"; private final static int SYMBOL_LENGTH = 15; public static String generateRandomPortfolioSymbol() { return generateRandomString(SYMBOL_LENGTH - PORTFOLIO_MARKER.length()) + PORTFOLIO_MARKER; } public static String generateRandomString(long length) { int leftLimit = 48; // numeral '0' int rightLimit = 122; // letter 'z' Random random = new Random(); return random.ints(leftLimit, rightLimit + 1).filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97)) .limit(length).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); } public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } }
38.704545
105
0.736348
527042576c8a2b70a648f3b2b6ad7f9274f67947
2,903
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.data.mongo; import com.mongodb.MongoClient; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.data.ConditionalOnRepositoryType; import org.springframework.boot.autoconfigure.data.RepositoryType; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import org.springframework.data.mongodb.repository.config.MongoRepositoryConfigurationExtension; import org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean; /** * {@link EnableAutoConfiguration Auto-configuration} for Spring Data's Mongo * Repositories. * <p> * Activates when there is no bean of type * {@link org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean} * configured in the context, the Spring Data Mongo * {@link org.springframework.data.mongodb.repository.MongoRepository} type is on the * classpath, the Mongo client driver API is on the classpath, and there is no other * configured {@link org.springframework.data.mongodb.repository.MongoRepository}. * <p> * Once in effect, the auto-configuration is the equivalent of enabling Mongo repositories * using the {@link EnableMongoRepositories @EnableMongoRepositories} annotation. * * @author Dave Syer * @author Oliver Gierke * @author Josh Long * @since 1.0.0 * @see EnableMongoRepositories */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ MongoClient.class, MongoRepository.class }) @ConditionalOnMissingBean({ MongoRepositoryFactoryBean.class, MongoRepositoryConfigurationExtension.class }) @ConditionalOnRepositoryType(store = "mongodb", type = RepositoryType.IMPERATIVE) @Import(MongoRepositoriesRegistrar.class) @AutoConfigureAfter(MongoDataAutoConfiguration.class) public class MongoRepositoriesAutoConfiguration { }
46.079365
108
0.815363
9f4cfbc7e2e772bb43c2be5fcfb40e5a1c230121
866
package com.it.vo; import java.util.List; public class FlowChartVO { private String code; //类型名称 private String name; //横坐标 private List<String> x; //纵坐标-流量 private List<Long> y; public FlowChartVO() { super(); // TODO Auto-generated constructor stub } public FlowChartVO(String code, String name, List<String> x, List<Long> y) { super(); this.code = code; this.name = name; this.x = x; this.y = y; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getX() { return x; } public void setX(List<String> x) { this.x = x; } public List<Long> getY() { return y; } public void setY(List<Long> y) { this.y = y; } }
10.691358
77
0.616628
28e172ae8adf40909834e57f496720a90efca23d
891
package de.webis.sigir2021; import java.util.List; import org.approvaltests.Approvals; import org.junit.Test; import de.webis.sigir2021.App; import de.webis.sigir2021.trec.JudgedDocuments; import net.sourceforge.argparse4j.inf.Namespace; public class AppArgsParsingTest { @Test public void testWeb2009WithTopic34() { List<String> judgedDocuments = judgedDocuments( "-o", "foo-bar", "--task", "WEB_2009", "--topic", "34" ); Approvals.verifyAsJson(judgedDocuments); } @Test public void testWeb2010WithTopic64() { List<String> judgedDocuments = judgedDocuments( "-o", "foo-bar", "--task", "WEB_2010", "--topic", "64" ); Approvals.verifyAsJson(judgedDocuments); } private static List<String> judgedDocuments(String...args) { Namespace parsedArgs = App.validArgumentsOrNull(args); return JudgedDocuments.judgedDocuments(parsedArgs); } }
21.214286
61
0.721661
7c59a92be4146d6225e61fa9344a02dacb5f96d0
6,456
/** * PostFinance Checkout SDK * * This library allows to interact with the PostFinance Checkout payment service. * * 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 ch.postfinance.sdk.model; import java.util.Objects; import java.util.Arrays; import ch.postfinance.sdk.model.Account; import ch.postfinance.sdk.model.DatabaseTranslatedString; import ch.postfinance.sdk.model.Permission; import ch.postfinance.sdk.model.RoleState; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; import java.util.*; import java.time.OffsetDateTime; /** * */ @ApiModel(description = "") public class Role { @JsonProperty("account") protected Account account = null; @JsonProperty("id") protected Long id = null; @JsonProperty("name") protected DatabaseTranslatedString name = null; @JsonProperty("permissions") protected List<Permission> permissions = null; @JsonProperty("plannedPurgeDate") protected OffsetDateTime plannedPurgeDate = null; @JsonProperty("state") protected RoleState state = null; @JsonProperty("twoFactorRequired") protected Boolean twoFactorRequired = null; @JsonProperty("version") protected Integer version = null; /** * The account to which this role belongs to. This role can only be assigned within the assigned account and the sub accounts of the assigned account. * @return account **/ @ApiModelProperty(value = "The account to which this role belongs to. This role can only be assigned within the assigned account and the sub accounts of the assigned account.") public Account getAccount() { return account; } /** * The ID is the primary key of the entity. The ID identifies the entity uniquely. * @return id **/ @ApiModelProperty(value = "The ID is the primary key of the entity. The ID identifies the entity uniquely.") public Long getId() { return id; } /** * The name of this role is used to identify the role within administrative interfaces. * @return name **/ @ApiModelProperty(value = "The name of this role is used to identify the role within administrative interfaces.") public DatabaseTranslatedString getName() { return name; } /** * Set of permissions that are granted to this role. * @return permissions **/ @ApiModelProperty(value = "Set of permissions that are granted to this role.") public List<Permission> getPermissions() { return permissions; } /** * The planned purge date indicates when the entity is permanently removed. When the date is null the entity is not planned to be removed. * @return plannedPurgeDate **/ @ApiModelProperty(value = "The planned purge date indicates when the entity is permanently removed. When the date is null the entity is not planned to be removed.") public OffsetDateTime getPlannedPurgeDate() { return plannedPurgeDate; } /** * * @return state **/ @ApiModelProperty(value = "") public RoleState getState() { return state; } /** * Defines whether having been granted this role will force a user to use two-factor authentication. * @return twoFactorRequired **/ @ApiModelProperty(value = "Defines whether having been granted this role will force a user to use two-factor authentication.") public Boolean isTwoFactorRequired() { return twoFactorRequired; } /** * The version number indicates the version of the entity. The version is incremented whenever the entity is changed. * @return version **/ @ApiModelProperty(value = "The version number indicates the version of the entity. The version is incremented whenever the entity is changed.") public Integer getVersion() { return version; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Role role = (Role) o; return Objects.equals(this.account, role.account) && Objects.equals(this.id, role.id) && Objects.equals(this.name, role.name) && Objects.equals(this.permissions, role.permissions) && Objects.equals(this.plannedPurgeDate, role.plannedPurgeDate) && Objects.equals(this.state, role.state) && Objects.equals(this.twoFactorRequired, role.twoFactorRequired) && Objects.equals(this.version, role.version); } @Override public int hashCode() { return Objects.hash(account, id, name, permissions, plannedPurgeDate, state, twoFactorRequired, version); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Role {\n"); sb.append(" account: ").append(toIndentedString(account)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" permissions: ").append(toIndentedString(permissions)).append("\n"); sb.append(" plannedPurgeDate: ").append(toIndentedString(plannedPurgeDate)).append("\n"); sb.append(" state: ").append(toIndentedString(state)).append("\n"); sb.append(" twoFactorRequired: ").append(toIndentedString(twoFactorRequired)).append("\n"); sb.append(" version: ").append(toIndentedString(version)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
30.027907
178
0.701053
c334825d01a647451be887330244244f20ea483c
1,249
package com.sorakasugano.pasteboard; import java.util.*; import java.text.*; import redis.clients.jedis.*; public class Setter extends Writer { public String owner = null; public Map<String, String> object = null; public boolean replace = true; private static String ISOString(Date date) { DateFormat iso = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); iso.setTimeZone(TimeZone.getTimeZone("UTC")); return iso.format(date); } private String list() { return (owner == null ? "" : owner + ":") + type + "-list"; } @Override public Boolean call(Jedis jedis) throws Exception { String key = type + ":" + id; boolean exists = jedis.exists(key); if (!exists || replace) { Date date = new Date(); String time = ISOString(date); if (!exists) object.put("created_time", time); object.put("modified_time", time); jedis.hmset(key, object); jedis.zadd(list(), date.getTime(), id); } return !exists; } @Override public Map<String, Boolean> keys() { Map<String, Boolean> keys = super.keys(); keys.put(list(), true); return keys; } }
31.225
78
0.580464
afe41427e38e44ce356b6f77a6f87e70c8610afc
1,815
package x.mvmn.jhexedit.gui; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.io.File; import java.util.Collection; import java.util.Iterator; import java.util.function.Consumer; import javax.swing.JComponent; import javax.swing.TransferHandler; public class FileDropTransferHandler extends TransferHandler { private static final long serialVersionUID = -3917969466507836476L; private final Consumer<File> fileConsumer; private final Consumer<Throwable> exceptionHandler; public FileDropTransferHandler(Consumer<File> fileConsumer, Consumer<Throwable> exceptionHandler) { if (fileConsumer == null) { throw new IllegalArgumentException("Parameter fileConsumer cannot be null"); } this.fileConsumer = fileConsumer; this.exceptionHandler = exceptionHandler; } @Override public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { for (DataFlavor df : transferFlavors) { if (df.getMimeType().equals(DataFlavor.javaFileListFlavor.getMimeType())) { return true; } } return super.canImport(comp, transferFlavors); } @Override public boolean importData(JComponent comp, Transferable transferable) { boolean result = false; try { Object drop = transferable.getTransferData(DataFlavor.javaFileListFlavor); if (drop instanceof Collection) { Collection<?> dropCollection = (Collection<?>) drop; Iterator<?> iterator = dropCollection.iterator(); while (iterator.hasNext()) { Object singleDrop = iterator.next(); if (singleDrop instanceof File) { fileConsumer.accept((File) singleDrop); result = true; } } } } catch (Throwable t) { if (exceptionHandler != null) { exceptionHandler.accept(t); } else { t.printStackTrace(); } } return result; } }
29.274194
100
0.741047
a3d585799079c48dd3e6efeae071e3e9e52b8dd1
392
package consulo.java.library; import com.intellij.ide.highlighter.JavaClassFileType; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.libraries.ui.FileTypeBasedRootFilter; public class JavaJarRootFilter extends FileTypeBasedRootFilter { public JavaJarRootFilter() { super(OrderRootType.CLASSES, true, JavaClassFileType.INSTANCE, "jar directory"); } }
28
82
0.829082
1465e62a3a3dc464c70220870a3f32b1caf3ba39
10,289
package jp.sourceforge.ea2ddl.dao.bsentity.dbmeta; import java.util.List; import java.util.Map; import org.seasar.dbflute.Entity; import org.seasar.dbflute.dbmeta.AbstractDBMeta; import org.seasar.dbflute.dbmeta.info.*; import org.seasar.dbflute.helper.StringKeyMap; import jp.sourceforge.ea2ddl.dao.exentity.TObjectrisks; /** * The DB meta of t_objectrisks. (Singleton) * @author DBFlute(AutoGenerator) */ public class TObjectrisksDbm extends AbstractDBMeta { // =================================================================================== // Singleton // ========= private static final TObjectrisksDbm _instance = new TObjectrisksDbm(); private TObjectrisksDbm() {} public static TObjectrisksDbm getInstance() { return _instance; } // =================================================================================== // Table Info // ========== public String getTableDbName() { return "t_objectrisks"; } public String getTablePropertyName() { return "TObjectrisks"; } public String getTableSqlName() { return "t_objectrisks"; } // =================================================================================== // Column Info // =========== protected ColumnInfo _columnObjectId = cci("Object_ID", null, "objectId", java.lang.Integer.class, false, false, null, null); protected ColumnInfo _columnRisk = cci("Risk", null, "risk", String.class, false, false, 255, 0); protected ColumnInfo _columnRisktype = cci("RiskType", null, "risktype", String.class, false, false, 12, 0); protected ColumnInfo _columnEvalue = cci("EValue", null, "evalue", java.math.BigDecimal.class, false, false, null, null); protected ColumnInfo _columnNotes = cci("Notes", null, "notes", String.class, false, false, 2147483647, 0); public ColumnInfo columnObjectId() { return _columnObjectId; } public ColumnInfo columnRisk() { return _columnRisk; } public ColumnInfo columnRisktype() { return _columnRisktype; } public ColumnInfo columnEvalue() { return _columnEvalue; } public ColumnInfo columnNotes() { return _columnNotes; } { initializeInformationResource(); } // =================================================================================== // Unique Info // =========== // ----------------------------------------------------- // Primary Element // --------------- public UniqueInfo getPrimaryUniqueInfo() { throw new UnsupportedOperationException("The table does not have primary key: " + getTableDbName()); } public boolean hasPrimaryKey() { return false; } public boolean hasTwoOrMorePrimaryKeys() { return false; } // =================================================================================== // Relation Info // ============= // ----------------------------------------------------- // Foreign Property // ---------------- // ----------------------------------------------------- // Referrer Property // ----------------- // =================================================================================== // Various Info // ============ // =================================================================================== // Type Name // ========= public String getEntityTypeName() { return "jp.sourceforge.ea2ddl.dao.exentity.TObjectrisks"; } public String getConditionBeanTypeName() { return "jp.sourceforge.ea2ddl.dao.cbean.bs.TObjectrisksCB"; } public String getDaoTypeName() { return "jp.sourceforge.ea2ddl.dao.exdao.TObjectrisksDao"; } public String getBehaviorTypeName() { return "jp.sourceforge.ea2ddl.dao.exbhv.TObjectrisksBhv"; } // =================================================================================== // Object Type // =========== public Class<TObjectrisks> getEntityType() { return TObjectrisks.class; } // =================================================================================== // Object Instance // =============== public Entity newEntity() { return newMyEntity(); } public TObjectrisks newMyEntity() { return new TObjectrisks(); } // =================================================================================== // Entity Handling // =============== // ----------------------------------------------------- // Accept // ------ public void acceptPrimaryKeyMap(Entity entity, Map<String, ? extends Object> primaryKeyMap) { doAcceptPrimaryKeyMap((TObjectrisks)entity, primaryKeyMap, _epsMap); } public void acceptPrimaryKeyMapString(Entity entity, String primaryKeyMapString) { MapStringUtil.acceptPrimaryKeyMapString(primaryKeyMapString, entity); } public void acceptColumnValueMap(Entity entity, Map<String, ? extends Object> columnValueMap) { doAcceptColumnValueMap((TObjectrisks)entity, columnValueMap, _epsMap); } public void acceptColumnValueMapString(Entity entity, String columnValueMapString) { MapStringUtil.acceptColumnValueMapString(columnValueMapString, entity); } // ----------------------------------------------------- // Extract // ------- public String extractPrimaryKeyMapString(Entity entity) { return MapStringUtil.extractPrimaryKeyMapString(entity); } public String extractPrimaryKeyMapString(Entity entity, String startBrace, String endBrace, String delimiter, String equal) { return doExtractPrimaryKeyMapString(entity, startBrace, endBrace, delimiter, equal); } public String extractColumnValueMapString(Entity entity) { return MapStringUtil.extractColumnValueMapString(entity); } public String extractColumnValueMapString(Entity entity, String startBrace, String endBrace, String delimiter, String equal) { return doExtractColumnValueMapString(entity, startBrace, endBrace, delimiter, equal); } // ----------------------------------------------------- // Convert // ------- public List<Object> convertToColumnValueList(Entity entity) { return newArrayList(convertToColumnValueMap(entity).values()); } public Map<String, Object> convertToColumnValueMap(Entity entity) { return doConvertToColumnValueMap(entity); } public List<String> convertToColumnStringValueList(Entity entity) { return newArrayList(convertToColumnStringValueMap(entity).values()); } public Map<String, String> convertToColumnStringValueMap(Entity entity) { return doConvertToColumnStringValueMap(entity); } // =================================================================================== // Entity Property Setup // ===================== // It's very INTERNAL! protected Map<String, Eps<TObjectrisks>> _epsMap = StringKeyMap.createAsFlexibleConcurrent(); { setupEps(_epsMap, new EpsObjectId(), columnObjectId()); setupEps(_epsMap, new EpsRisk(), columnRisk()); setupEps(_epsMap, new EpsRisktype(), columnRisktype()); setupEps(_epsMap, new EpsEvalue(), columnEvalue()); setupEps(_epsMap, new EpsNotes(), columnNotes()); } public boolean hasEntityPropertySetupper(String propertyName) { return _epsMap.containsKey(propertyName); } public void setupEntityProperty(String propertyName, Object entity, Object value) { findEps(_epsMap, propertyName).setup((TObjectrisks)entity, value); } public static class EpsObjectId implements Eps<TObjectrisks> { public void setup(TObjectrisks e, Object v) { e.setObjectId((java.lang.Integer)v); } } public static class EpsRisk implements Eps<TObjectrisks> { public void setup(TObjectrisks e, Object v) { e.setRisk((String)v); } } public static class EpsRisktype implements Eps<TObjectrisks> { public void setup(TObjectrisks e, Object v) { e.setRisktype((String)v); } } public static class EpsEvalue implements Eps<TObjectrisks> { public void setup(TObjectrisks e, Object v) { e.setEvalue((java.math.BigDecimal)v); } } public static class EpsNotes implements Eps<TObjectrisks> { public void setup(TObjectrisks e, Object v) { e.setNotes((String)v); } } }
65.955128
143
0.462824
ade280a03800d524dab4bb24e3df9cb3731ba284
3,480
/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*- * * Copyright © 2017-2018 microBean. * * 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.microbean.configuration.spi; import java.io.Serializable; import java.util.Collections; import java.util.Map; import java.util.Set; import org.microbean.configuration.api.ConfigurationValue; /** * An {@link AbstractConfiguration} providing access to {@linkplain * System#getenv(String) environment variabes}. * * @author <a href="https://about.me/lairdnelson" * target="_parent">Laird Nelson</a> * * @see #getValue(Map, String) */ public final class EnvironmentVariablesConfiguration extends AbstractConfiguration implements Ranked, Serializable { /* * Static fields. */ /** * The version of this class for {@linkplain Serializable * serialization} purposes. */ private static final long serialVersionUID = 1L; /* * Constructors. */ /** * Creates a new {@link EnvironmentVariablesConfiguration}. */ public EnvironmentVariablesConfiguration() { super(); } /* * Instance methods. */ @Override public final int getRank() { return 200; } /** * Returns a {@link ConfigurationValue} representing the {@linkplain * System#getenv(String) environment variable} identified by the * supplied {@code name}, or {@code null}. * * @param coordinates the configuration coordinates in effect for * the current request; may be {@code null} * * @param name the name of the configuration property for which to * return a {@link ConfigurationValue}; may be {@code null} * * @return a {@link ConfigurationValue}, or {@code null} */ @Override public final ConfigurationValue getValue(final Map<String, String> coordinates, final String name) { ConfigurationValue returnValue = null; if (name != null) { final String propertyValue = System.getenv(name); if (propertyValue != null) { returnValue = new ConfigurationValue(this, null /* deliberately null coordinates */, name, propertyValue, false); } } return returnValue; } /** * Returns a {@link Set} of the names of all {@link * ConfigurationValue}s that might be returned by this {@link * Configuration}. * * <p>This implementation does not return {@code null}.</p> * * <p>This implementation returns the equivalent of {@link * System#getenv() System.getenv().keySet()}.</p> * * @return a non-{@code null} {@link Set} of names */ @Override public final Set<String> getNames() { return System.getenv().keySet(); } @Override public final int hashCode() { return System.getenv().hashCode(); } @Override public final boolean equals(final Object other) { return other instanceof EnvironmentVariablesConfiguration; } @Override public final String toString() { return System.getenv().toString(); } }
26.165414
121
0.684483
016218e952ad34ddeee002ea2c8dbcd742a15188
18,878
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|coprocessor package|; end_package begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertEquals import|; end_import begin_import import|import name|com operator|. name|google operator|. name|protobuf operator|. name|ByteString import|; end_import begin_import import|import name|com operator|. name|google operator|. name|protobuf operator|. name|ServiceException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseClassTestRule import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseTestingUtility import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|TableName import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Admin import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|ColumnFamilyDescriptor import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|ColumnFamilyDescriptorBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Put import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|Table import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|TableDescriptorBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|coprocessor operator|. name|Batch import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|coprocessor operator|. name|protobuf operator|. name|generated operator|. name|ColumnAggregationProtos import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|ipc operator|. name|CoprocessorRpcUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|CoprocessorTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|MediumTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|Bytes import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|AfterClass import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|BeforeClass import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|ClassRule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Rule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|experimental operator|. name|categories operator|. name|Category import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|rules operator|. name|TestName import|; end_import begin_class annotation|@ name|Category argument_list|( block|{ name|CoprocessorTests operator|. name|class block|, name|MediumTests operator|. name|class block|} argument_list|) specifier|public class|class name|TestCoprocessorTableEndpoint block|{ annotation|@ name|ClassRule specifier|public specifier|static specifier|final name|HBaseClassTestRule name|CLASS_RULE init|= name|HBaseClassTestRule operator|. name|forClass argument_list|( name|TestCoprocessorTableEndpoint operator|. name|class argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|byte index|[] name|TEST_FAMILY init|= name|Bytes operator|. name|toBytes argument_list|( literal|"TestFamily" argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|byte index|[] name|TEST_QUALIFIER init|= name|Bytes operator|. name|toBytes argument_list|( literal|"TestQualifier" argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|byte index|[] name|ROW init|= name|Bytes operator|. name|toBytes argument_list|( literal|"testRow" argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|int name|ROWSIZE init|= literal|20 decl_stmt|; specifier|private specifier|static specifier|final name|int name|rowSeperator1 init|= literal|5 decl_stmt|; specifier|private specifier|static specifier|final name|int name|rowSeperator2 init|= literal|12 decl_stmt|; specifier|private specifier|static specifier|final name|byte index|[] index|[] name|ROWS init|= name|makeN argument_list|( name|ROW argument_list|, name|ROWSIZE argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|HBaseTestingUtility name|TEST_UTIL init|= operator|new name|HBaseTestingUtility argument_list|() decl_stmt|; annotation|@ name|Rule specifier|public name|TestName name|name init|= operator|new name|TestName argument_list|() decl_stmt|; annotation|@ name|BeforeClass specifier|public specifier|static name|void name|setupBeforeClass parameter_list|() throws|throws name|Exception block|{ name|TEST_UTIL operator|. name|startMiniCluster argument_list|( literal|2 argument_list|) expr_stmt|; block|} annotation|@ name|AfterClass specifier|public specifier|static name|void name|tearDownAfterClass parameter_list|() throws|throws name|Exception block|{ name|TEST_UTIL operator|. name|shutdownMiniCluster argument_list|() expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testCoprocessorTableEndpoint parameter_list|() throws|throws name|Throwable block|{ specifier|final name|TableName name|tableName init|= name|TableName operator|. name|valueOf argument_list|( name|name operator|. name|getMethodName argument_list|() argument_list|) decl_stmt|; name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor name|tableDescriptor init|= operator|new name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor argument_list|( name|tableName argument_list|) decl_stmt|; name|ColumnFamilyDescriptor name|familyDescriptor init|= operator|new name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor argument_list|( name|TEST_FAMILY argument_list|) decl_stmt|; name|tableDescriptor operator|. name|setColumnFamily argument_list|( name|familyDescriptor argument_list|) expr_stmt|; name|tableDescriptor operator|. name|setCoprocessor argument_list|( name|ColumnAggregationEndpoint operator|. name|class operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|createTable argument_list|( name|tableDescriptor argument_list|) expr_stmt|; name|verifyTable argument_list|( name|tableName argument_list|) expr_stmt|; block|} annotation|@ name|Test specifier|public name|void name|testDynamicCoprocessorTableEndpoint parameter_list|() throws|throws name|Throwable block|{ specifier|final name|TableName name|tableName init|= name|TableName operator|. name|valueOf argument_list|( name|name operator|. name|getMethodName argument_list|() argument_list|) decl_stmt|; name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor name|tableDescriptor init|= operator|new name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor argument_list|( name|tableName argument_list|) decl_stmt|; name|ColumnFamilyDescriptor name|familyDescriptor init|= operator|new name|ColumnFamilyDescriptorBuilder operator|. name|ModifyableColumnFamilyDescriptor argument_list|( name|TEST_FAMILY argument_list|) decl_stmt|; name|tableDescriptor operator|. name|setColumnFamily argument_list|( name|familyDescriptor argument_list|) expr_stmt|; name|createTable argument_list|( name|tableDescriptor argument_list|) expr_stmt|; name|tableDescriptor operator|. name|setCoprocessor argument_list|( name|ColumnAggregationEndpoint operator|. name|class operator|. name|getName argument_list|() argument_list|) expr_stmt|; name|updateTable argument_list|( name|tableDescriptor argument_list|) expr_stmt|; name|verifyTable argument_list|( name|tableName argument_list|) expr_stmt|; block|} specifier|private specifier|static name|byte index|[] index|[] name|makeN parameter_list|( name|byte index|[] name|base parameter_list|, name|int name|n parameter_list|) block|{ name|byte index|[] index|[] name|ret init|= operator|new name|byte index|[ name|n index|] index|[] decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|n condition|; name|i operator|++ control|) block|{ name|ret index|[ name|i index|] operator|= name|Bytes operator|. name|add argument_list|( name|base argument_list|, name|Bytes operator|. name|toBytes argument_list|( name|String operator|. name|format argument_list|( literal|"%02d" argument_list|, name|i argument_list|) argument_list|) argument_list|) expr_stmt|; block|} return|return name|ret return|; block|} specifier|private specifier|static name|Map argument_list|< name|byte index|[] argument_list|, name|Long argument_list|> name|sum parameter_list|( specifier|final name|Table name|table parameter_list|, specifier|final name|byte index|[] name|family parameter_list|, specifier|final name|byte index|[] name|qualifier parameter_list|, specifier|final name|byte index|[] name|start parameter_list|, specifier|final name|byte index|[] name|end parameter_list|) throws|throws name|ServiceException throws|, name|Throwable block|{ return|return name|table operator|. name|coprocessorService argument_list|( name|ColumnAggregationProtos operator|. name|ColumnAggregationService operator|. name|class argument_list|, name|start argument_list|, name|end argument_list|, operator|new name|Batch operator|. name|Call argument_list|< name|ColumnAggregationProtos operator|. name|ColumnAggregationService argument_list|, name|Long argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|Long name|call parameter_list|( name|ColumnAggregationProtos operator|. name|ColumnAggregationService name|instance parameter_list|) throws|throws name|IOException block|{ name|CoprocessorRpcUtils operator|. name|BlockingRpcCallback argument_list|< name|ColumnAggregationProtos operator|. name|SumResponse argument_list|> name|rpcCallback init|= operator|new name|CoprocessorRpcUtils operator|. name|BlockingRpcCallback argument_list|<> argument_list|() decl_stmt|; name|ColumnAggregationProtos operator|. name|SumRequest operator|. name|Builder name|builder init|= name|ColumnAggregationProtos operator|. name|SumRequest operator|. name|newBuilder argument_list|() decl_stmt|; name|builder operator|. name|setFamily argument_list|( name|ByteString operator|. name|copyFrom argument_list|( name|family argument_list|) argument_list|) expr_stmt|; if|if condition|( name|qualifier operator|!= literal|null operator|&& name|qualifier operator|. name|length operator|> literal|0 condition|) block|{ name|builder operator|. name|setQualifier argument_list|( name|ByteString operator|. name|copyFrom argument_list|( name|qualifier argument_list|) argument_list|) expr_stmt|; block|} name|instance operator|. name|sum argument_list|( literal|null argument_list|, name|builder operator|. name|build argument_list|() argument_list|, name|rpcCallback argument_list|) expr_stmt|; return|return name|rpcCallback operator|. name|get argument_list|() operator|. name|getSum argument_list|() return|; block|} block|} argument_list|) return|; block|} specifier|private specifier|static specifier|final name|void name|createTable parameter_list|( specifier|final name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor name|tableDescriptor parameter_list|) throws|throws name|Exception block|{ name|Admin name|admin init|= name|TEST_UTIL operator|. name|getAdmin argument_list|() decl_stmt|; name|admin operator|. name|createTable argument_list|( name|tableDescriptor argument_list|, operator|new name|byte index|[] index|[] block|{ name|ROWS index|[ name|rowSeperator1 index|] block|, name|ROWS index|[ name|rowSeperator2 index|] block|} argument_list|) expr_stmt|; name|TEST_UTIL operator|. name|waitUntilAllRegionsAssigned argument_list|( name|tableDescriptor operator|. name|getTableName argument_list|() argument_list|) expr_stmt|; name|Table name|table init|= name|TEST_UTIL operator|. name|getConnection argument_list|() operator|. name|getTable argument_list|( name|tableDescriptor operator|. name|getTableName argument_list|() argument_list|) decl_stmt|; try|try block|{ for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|ROWSIZE condition|; name|i operator|++ control|) block|{ name|Put name|put init|= operator|new name|Put argument_list|( name|ROWS index|[ name|i index|] argument_list|) decl_stmt|; name|put operator|. name|addColumn argument_list|( name|TEST_FAMILY argument_list|, name|TEST_QUALIFIER argument_list|, name|Bytes operator|. name|toBytes argument_list|( name|i argument_list|) argument_list|) expr_stmt|; name|table operator|. name|put argument_list|( name|put argument_list|) expr_stmt|; block|} block|} finally|finally block|{ name|table operator|. name|close argument_list|() expr_stmt|; block|} block|} specifier|private specifier|static name|void name|updateTable parameter_list|( specifier|final name|TableDescriptorBuilder operator|. name|ModifyableTableDescriptor name|tableDescriptor parameter_list|) throws|throws name|Exception block|{ name|Admin name|admin init|= name|TEST_UTIL operator|. name|getAdmin argument_list|() decl_stmt|; name|admin operator|. name|disableTable argument_list|( name|tableDescriptor operator|. name|getTableName argument_list|() argument_list|) expr_stmt|; name|admin operator|. name|modifyTable argument_list|( name|tableDescriptor argument_list|) expr_stmt|; name|admin operator|. name|enableTable argument_list|( name|tableDescriptor operator|. name|getTableName argument_list|() argument_list|) expr_stmt|; block|} specifier|private specifier|static specifier|final name|void name|verifyTable parameter_list|( name|TableName name|tableName parameter_list|) throws|throws name|Throwable block|{ name|Table name|table init|= name|TEST_UTIL operator|. name|getConnection argument_list|() operator|. name|getTable argument_list|( name|tableName argument_list|) decl_stmt|; try|try block|{ name|Map argument_list|< name|byte index|[] argument_list|, name|Long argument_list|> name|results init|= name|sum argument_list|( name|table argument_list|, name|TEST_FAMILY argument_list|, name|TEST_QUALIFIER argument_list|, name|ROWS index|[ literal|0 index|] argument_list|, name|ROWS index|[ name|ROWS operator|. name|length operator|- literal|1 index|] argument_list|) decl_stmt|; name|int name|sumResult init|= literal|0 decl_stmt|; name|int name|expectedResult init|= literal|0 decl_stmt|; for|for control|( name|Map operator|. name|Entry argument_list|< name|byte index|[] argument_list|, name|Long argument_list|> name|e range|: name|results operator|. name|entrySet argument_list|() control|) block|{ name|sumResult operator|+= name|e operator|. name|getValue argument_list|() expr_stmt|; block|} for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|ROWSIZE condition|; name|i operator|++ control|) block|{ name|expectedResult operator|+= name|i expr_stmt|; block|} name|assertEquals argument_list|( literal|"Invalid result" argument_list|, name|expectedResult argument_list|, name|sumResult argument_list|) expr_stmt|; comment|// scan: for region 2 and region 3 name|results operator|. name|clear argument_list|() expr_stmt|; name|results operator|= name|sum argument_list|( name|table argument_list|, name|TEST_FAMILY argument_list|, name|TEST_QUALIFIER argument_list|, name|ROWS index|[ name|rowSeperator1 index|] argument_list|, name|ROWS index|[ name|ROWS operator|. name|length operator|- literal|1 index|] argument_list|) expr_stmt|; name|sumResult operator|= literal|0 expr_stmt|; name|expectedResult operator|= literal|0 expr_stmt|; for|for control|( name|Map operator|. name|Entry argument_list|< name|byte index|[] argument_list|, name|Long argument_list|> name|e range|: name|results operator|. name|entrySet argument_list|() control|) block|{ name|sumResult operator|+= name|e operator|. name|getValue argument_list|() expr_stmt|; block|} for|for control|( name|int name|i init|= name|rowSeperator1 init|; name|i operator|< name|ROWSIZE condition|; name|i operator|++ control|) block|{ name|expectedResult operator|+= name|i expr_stmt|; block|} name|assertEquals argument_list|( literal|"Invalid result" argument_list|, name|expectedResult argument_list|, name|sumResult argument_list|) expr_stmt|; block|} finally|finally block|{ name|table operator|. name|close argument_list|() expr_stmt|; block|} block|} block|} end_class end_unit
13.552046
813
0.807607
e36708e7f8a2fc1a6b59b6865273957dd192cf09
2,078
package it.linksmt.cts2.plugin.sti.db.commands.search; import java.util.List; import org.hibernate.Session; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import it.linksmt.cts2.plugin.sti.db.hibernate.HibernateCommand; import it.linksmt.cts2.plugin.sti.db.model.CodeSystem; import it.linksmt.cts2.plugin.sti.db.model.CodeSystemVersion; import it.linksmt.cts2.plugin.sti.service.exception.StiAuthorizationException; import it.linksmt.cts2.plugin.sti.service.exception.StiHibernateException; import it.linksmt.cts2.plugin.sti.service.util.StiConstants; import it.linksmt.cts2.plugin.sti.service.util.StiServiceUtil; public class GetCodeSystemVersions extends HibernateCommand { private String codeSystemName = null; private StiConstants.STATUS_CODES status = null; public GetCodeSystemVersions(final String codeSystemName, final StiConstants.STATUS_CODES status) { this.codeSystemName = codeSystemName; this.status = status; } @Override public void checkPermission(final Session session) throws StiAuthorizationException, StiHibernateException { if (userInfo == null) { throw new StiAuthorizationException("Occorre effettuare il login per utilizzare il servizio."); } } @Override public List<CodeSystemVersion> execute(final Session session) throws StiAuthorizationException, StiHibernateException { if (StiServiceUtil.isNull(codeSystemName)) { throw new StiHibernateException("Occorre specificare il nome del Code System."); } CodeSystem cs = (CodeSystem)session.createCriteria(CodeSystem.class).add( Restrictions.ilike("name", StiServiceUtil.trimStr(codeSystemName), MatchMode.EXACT)).uniqueResult(); if (cs == null) { throw new StiHibernateException("Nessuna occorrenza trovata per: " + codeSystemName); } return session.createCriteria(CodeSystemVersion.class) .add(Restrictions.eq("codeSystem.id", cs.getId().longValue())) .add(Restrictions.eq("status", status.getCode())) .addOrder(Order.asc("releaseDate")).list(); } }
36.45614
109
0.790183
365bb12ee3e8cf870434f5cb6164d2b6c3ea18c9
5,258
package seedu.address.testutil; import static seedu.address.logic.parser.CliSyntax.PREFIX_DATE; import static seedu.address.logic.parser.CliSyntax.PREFIX_DURATION; import static seedu.address.logic.parser.CliSyntax.PREFIX_ENDAMOUNT; import static seedu.address.logic.parser.CliSyntax.PREFIX_GAMETYPE; import static seedu.address.logic.parser.CliSyntax.PREFIX_LOCATION; import static seedu.address.logic.parser.CliSyntax.PREFIX_STARTAMOUNT; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Set; import seedu.address.logic.commands.AddCommand; import seedu.address.logic.commands.EditCommand.EditGameEntryDescriptor; import seedu.address.model.gameentry.GameEntry; import seedu.address.model.tag.Tag; /** * A utility class for GameEntry. */ public class GameEntryUtil { private static final DateFormat DATE_FORMAT_WITH_MINUTES = new SimpleDateFormat("dd/MM/yy HH:mm"); private static final DateFormat DATE_FORMAT_WITHOUT_MINUTES = new SimpleDateFormat("dd/MM/yy"); /** * Returns an add command string for adding the {@code gameEntry}. */ public static String getAddCommand(GameEntry gameEntry) { return AddCommand.COMMAND_WORD + " " + getGameEntryDetails(gameEntry); } /** * Returns the part of command string for the given {@code gameEntry}'s details. */ public static String getGameEntryDetails(GameEntry gameEntry) { StringBuilder sb = new StringBuilder(); boolean containsTime = gameEntry.getDate().getIsTimeIndicated(); String date; if (containsTime) { try { date = DATE_FORMAT_WITH_MINUTES.format(new SimpleDateFormat("yyyy-MM-dd HH:mm") .parse(gameEntry.getDate().toString())); } catch (ParseException e) { e.printStackTrace(); date = null; } } else { try { date = DATE_FORMAT_WITHOUT_MINUTES.format(new SimpleDateFormat("yyyy-MM-dd") .parse(gameEntry.getDate().toString())); } catch (ParseException e) { e.printStackTrace(); date = null; } } sb.append(PREFIX_GAMETYPE + gameEntry.getGameType().toString() + " "); sb.append(PREFIX_STARTAMOUNT + gameEntry.getStartAmount().toString() + " "); sb.append(PREFIX_ENDAMOUNT + gameEntry.getEndAmount().toString() + " "); sb.append(PREFIX_DATE + date + " "); sb.append(PREFIX_DURATION + gameEntry.getDuration().toString() + " "); sb.append(PREFIX_LOCATION + gameEntry.getLocation().toString() + " "); if (gameEntry.hasTags()) { sb.append(PREFIX_TAG + " "); sb.append(gameEntry .getTags() .stream() .map(x -> x.toString()) .reduce("", (x, y) -> x + ", " + y)); } return sb.toString(); } /** * Returns the part of command string for the given {@code EditGameEntryDescriptor}'s details. */ public static String getEditGameEntryDescriptorDetails(EditGameEntryDescriptor descriptor) { StringBuilder sb = new StringBuilder(); descriptor.getDate().ifPresent(date -> { boolean containsTime = date.getIsTimeIndicated(); String dateString = date.toString(); if (containsTime) { try { dateString = DATE_FORMAT_WITH_MINUTES.format(new SimpleDateFormat("yyyy-MM-dd HH:mm") .parse(dateString)); } catch (ParseException e) { e.printStackTrace(); } } else { try { dateString = DATE_FORMAT_WITHOUT_MINUTES.format(new SimpleDateFormat("yyyy-MM-dd") .parse(dateString)); } catch (ParseException e) { e.printStackTrace(); } } sb.append(PREFIX_DATE + "" + dateString + " "); }); descriptor.getGameType().ifPresent(game -> sb.append(PREFIX_GAMETYPE + "" + descriptor.getGameType().get() + " ")); descriptor.getStartAmount().ifPresent(start -> sb.append(PREFIX_STARTAMOUNT + "" + descriptor.getStartAmount().get() + " ")); descriptor.getEndAmount().ifPresent(end -> sb.append(PREFIX_ENDAMOUNT + "" + descriptor.getEndAmount().get() + " ")); descriptor.getDuration().ifPresent(duration -> sb.append(PREFIX_DURATION + "" + descriptor.getDuration().get() + " ")); descriptor.getLocation().ifPresent(location -> sb.append(PREFIX_LOCATION + "" + descriptor.getLocation().get() + " ")); if (descriptor.getTags().isPresent()) { Set<Tag> tags = descriptor.getTags().get(); if (tags.isEmpty()) { sb.append(PREFIX_TAG); } else { tags.forEach(s -> sb.append(PREFIX_TAG).append(s.tagName).append(" ")); } } return sb.toString(); } }
42.403226
105
0.597946
2a103c36b42e435466d501c5c4dbcd70a5e3cad3
428
package com.totvs.guavaworkshop.coffeeandcode.strings.joiner.examples; import com.google.common.base.Joiner; public class Example05 { public static void main(String[] args) { String[] operacoes = { "1000", "1002", null, "1005", "1008" }; String where = Joiner.on(", ").skipNulls().join(operacoes); String sql = "... WHERE CD_OPERACAO IN ( " + where + " ) ..."; System.out.println(sql); } }
21.4
71
0.630841
0abb760c04637b647f7360c5c919319e06813872
3,537
package com.cs18.anabeesh.salem.ui.SendAnswer; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.cs18.anabeesh.R; import com.cs18.anabeesh.beshary.store.AuthRepo; import com.cs18.anabeesh.salem.Adapters.AllAnswersAdapter; import com.cs18.anabeesh.salem.Others.GlideApp; import com.cs18.anabeesh.salem.model.AllAnswers; import com.rxmuhammadyoussef.core.util.PreferencesUtil; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class SendAnswerActivity extends AppCompatActivity implements SendAnswerView { private final String QuestionId = "1";//getIntent().getStringExtra("QuestionId"); @BindView(R.id.iv_user_post) ImageView posterUserImageActivity; @BindView(R.id.tv_poster_user_name) TextView posterUserNameActivity; @BindView(R.id.tv_poster_tittle) TextView postTittle; @BindView(R.id.tv_poster_detail) TextView postDetail; @BindView(R.id.rv_comments) RecyclerView commentsRecyclerView; @BindView(R.id.tb_send_answer) Toolbar sendAnswerToolbar; private SendAnswerPressnter sendAnswerPressnter; private AllAnswersAdapter answersAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_send_answer); ButterKnife.bind(this); sendAnswerPressnter = new SendAnswerPressnter(this, new AuthRepo(new PreferencesUtil(this))); InitializeViews(); sendAnswerPressnter.CreateUI(); } //The Question Detail Views void InitializeViews() { String postUserName = getIntent().getStringExtra("poster_user_name"); String PostTittle = getIntent().getStringExtra("post_tittle"); String PostDesc = getIntent().getStringExtra("post_descr"); String postUserImg = getIntent().getStringExtra("poster_user_img"); GlideApp.with(this) .load(postUserImg) .placeholder(R.mipmap.ic_launcher_round) .into(posterUserImageActivity); posterUserNameActivity.setText(postUserName); postTittle.setText(PostTittle); postDetail.setText(PostDesc); } @Override public void setupToolBar() { setSupportActionBar(sendAnswerToolbar); if (sendAnswerToolbar != null) { getSupportActionBar().setTitle(R.string.question_details); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); sendAnswerToolbar.setNavigationOnClickListener(view -> onBackPressed()); } } @Override public void setUpAnswerRecyclerView(List<AllAnswers> allAnswersList) { answersAdapter = new AllAnswersAdapter(allAnswersList, this); commentsRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); commentsRecyclerView.setAdapter(answersAdapter); } @Override public void showResponseMsg(String Msg) { Toast.makeText(this, Msg, Toast.LENGTH_SHORT).show(); } @OnClick(R.id.fab_send_comment) void sendComment() { sendAnswerPressnter.inisializeCutomDailog(this,QuestionId); } }
35.727273
114
0.736783
8c597f132762e4c0633eff9ed0997c2dfff5f4d6
1,101
package com.epam.cisen.jenkins; import com.epam.cisen.core.api.dto.ConfigDTO; public class JenkinsConfig extends ConfigDTO { private String baseURL; private String login; private String pass; private String jobName; public JenkinsConfig() { super("Jenkins", BaseType.CI); } public JenkinsConfig(String baseURL, String login, String pass, String jobName) { this(); this.baseURL = baseURL; this.login = login; this.pass = pass; this.jobName = jobName; } public String getBaseURL() { return baseURL; } public void setBaseURL(String baseURL) { this.baseURL = baseURL; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } }
19.660714
85
0.603996
b97b34ff7b6b8d1c0c5885a364211dff2baf0612
498
package ch.itenengineering.relations.r7.ejb; import javax.ejb.Remote; @Remote public interface R7ManagerRemote { public void clear(); public void book(int studentId, int courseId); public void cancel(int studentId, int courseId); public Object persist(Object entity); public Object merge(Object entity); @SuppressWarnings("unchecked") public Object find(Class clazz, Object primaryKey); @SuppressWarnings("unchecked") public void remove(Class clazz, Object primaryKey); } // end
19.92
52
0.767068
2bcc8fb97c1d5d76e01113d86fdabe375987abce
11,639
/* * This software is distributed under following license based on modified BSD * style license. * ---------------------------------------------------------------------- * * Copyright 2003 The Nimbus Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE NIMBUS PROJECT ``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 NIMBUS PROJECT 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the Nimbus Project. */ package jp.ossc.nimbus.service.cache; import java.util.*; import java.io.*; import jp.ossc.nimbus.core.*; import jp.ossc.nimbus.service.io.Externalizer; /** * ファイルキャッシュサービス。<p> * 以下に、キャッシュオブジェクトをJVMのテンポラリディレクトリに直列化してキャッシュするファイルキャッシュサービスのサービス定義例を示す。<br> * <pre> * &lt;?xml version="1.0" encoding="Shift_JIS"?&gt; * * &lt;server&gt; * * &lt;manager name="Sample"&gt; * * &lt;service name="FileCache" * code="jp.ossc.nimbus.service.cache.FileCacheService"/&gt; * * &lt;/manager&gt; * * &lt;/server&gt; * </pre> * * @author M.Takata */ public class FileCacheService extends AbstractCacheService implements java.io.Serializable, FileCacheServiceMBean{ private static final long serialVersionUID = 4587745705534545655L; private static final String JVM_TMP_DIR = "java.io.tmpdir"; private String outputDirectory; private File directory; private String prefix; private String suffix = DEFAULT_SUFFIX; private boolean isDeleteOnExitWithJVM = true; private boolean isLoadOnStart; private boolean isCheckFileOnLoad; private boolean isDeleteOnCheckFileError; private ServiceName externalizerServiceName; private Externalizer externalizer; // FileCacheServiceMBeanのJavaDoc public void setOutputDirectory(String outputDirectory){ this.outputDirectory = outputDirectory; } // FileCacheServiceMBeanのJavaDoc public String getOutputDirectory(){ return outputDirectory; } // FileCacheServiceMBeanのJavaDoc public void setOutputPrefix(String prefix){ this.prefix = prefix; } // FileCacheServiceMBeanのJavaDoc public String getOutputPrefix(){ return prefix; } // FileCacheServiceMBeanのJavaDoc public void setOutputSuffix(String suffix){ this.suffix = suffix; } // FileCacheServiceMBeanのJavaDoc public String getOutputSuffix(){ return suffix; } // FileCacheServiceMBeanのJavaDoc public void setLoadOnStart(boolean isLoad){ isLoadOnStart = isLoad; } // FileCacheServiceMBeanのJavaDoc public boolean isLoadOnStart(){ return isLoadOnStart; } // FileCacheServiceMBeanのJavaDoc public void setCheckFileOnLoad(boolean isCheck){ isCheckFileOnLoad = isCheck; } // FileCacheServiceMBeanのJavaDoc public boolean isCheckFileOnLoad(){ return isCheckFileOnLoad; } // FileCacheServiceMBeanのJavaDoc public void setDeleteOnCheckFileError(boolean isDelete){ isDeleteOnCheckFileError = isDelete; } // FileCacheServiceMBeanのJavaDoc public boolean isDeleteOnCheckFileError(){ return isDeleteOnCheckFileError; } // FileCacheServiceMBeanのJavaDoc public void setExternalizerServiceName(ServiceName name){ externalizerServiceName = name; } // FileCacheServiceMBeanのJavaDoc public ServiceName getExternalizerServiceName(){ return externalizerServiceName; } public void setExternalizer(Externalizer ext){ externalizer = ext; } public Externalizer getExternalizer(){ return externalizer; } /** * 指定されたキャッシュオブジェクトを保存するファイルを作成する。<p> * * @param obj キャッシュオブジェクト * @return キャッシュオブジェクトを保存するファイル * @exception IOException ファイルが作成できなかった場合 */ protected File createFile(Object obj) throws IOException{ File file = null; String prefix = this.prefix; if(prefix == null){ if(obj != null){ synchronized(obj){ prefix = obj.toString(); } }else{ prefix = "null"; } } if(directory != null){ file = File.createTempFile( createPrefix(prefix), suffix, directory ); }else{ file = File.createTempFile( createPrefix(prefix), suffix ); } if(isDeleteOnExitWithJVM()){ file.deleteOnExit(); } return file; } private String createPrefix(String prefix){ if(prefix.length() > 2){ return prefix; }else{ final StringBuilder buf = new StringBuilder(prefix); for(int i = 0, max = 3 - prefix.length(); i < max; i++){ buf.append('_'); } return buf.toString(); } } // FileCacheServiceMBeanのJavaDoc public void setDeleteOnExitWithJVM(boolean isDeleteOnExit){ isDeleteOnExitWithJVM = isDeleteOnExit; } // FileCacheServiceMBeanのJavaDoc public boolean isDeleteOnExitWithJVM(){ return isDeleteOnExitWithJVM; } /** * サービスの開始処理を行う。<p> * * @exception Exception サービスの開始処理に失敗した場合 */ public void startService() throws Exception{ if(externalizerServiceName != null){ externalizer = (Externalizer)ServiceManagerFactory.getServiceObject(externalizerServiceName); } if(outputDirectory != null){ final File dir = new File(outputDirectory); if(dir.exists()){ if(!dir.isDirectory()){ throw new IllegalArgumentException( "Path is illegal : " + outputDirectory ); } }else{ if(!dir.mkdirs()){ throw new IllegalArgumentException( "Path is illegal : " + outputDirectory ); } } directory = dir; } if(isLoadOnStart()){ load(); } } /** * キャッシュファイルの読み込みを行う。<p> * * @exception Exception キャッシュファイルの読み込みに失敗した場合 */ protected void load() throws Exception{ File dir = directory; if(dir == null){ final String tmpFileStr = System.getProperty(JVM_TMP_DIR); if(tmpFileStr != null){ final File tmpFile = new File(tmpFileStr); if(tmpFile.exists() && tmpFile.isDirectory()){ dir = tmpFile; } } } if(dir != null){ final File[] list = dir.listFiles( new FilenameFilter(){ private final String pre = prefix != null ? createPrefix(prefix) : null; public boolean accept(File dir, String name){ if(pre == null){ return name.endsWith(suffix); }else{ return name.startsWith(pre) && name.endsWith(suffix); } } } ); Arrays.sort( list, new Comparator(){ public int compare(Object o1, Object o2){ File f1 = (File)o1; File f2 = (File)o2; long diff = f1.lastModified() - f2.lastModified(); return diff == 0 ? 0 : (diff > 0 ? 1 : -1); } } ); for(int i = 0; i < list.length; i++){ if(!containsFile(list[i])){ FileCachedReference ref = new FileCachedReference(list[i], externalizer); if(isCheckFileOnLoad){ try{ ref.deserializeObject(); add(ref); }catch(IOException e){ if(isDeleteOnCheckFileError){ list[i].delete(); } }catch(ClassNotFoundException e){ if(isDeleteOnCheckFileError){ list[i].delete(); } } }else{ add(ref); } } } } } /** * このキャッシュに指定されたキャッシュファイルのキャッシュ参照が含まれているか調べる。<p> * * @param file キャッシュファイル * @return 含まれている場合true */ protected boolean containsFile(File file){ if(references == null || file == null){ return false; } boolean result = false; synchronized(references){ final Iterator refs = references.iterator(); while(refs.hasNext()){ FileCachedReference ref = (FileCachedReference)refs.next(); if(file.equals(ref.getFile())){ return true; } } } return result; } /** * ファイルキャッシュ参照を生成する。<p> * ファイルキャッシュ参照の生成に失敗した場合は、nullを返す。 * * @param obj キャッシュオブジェクト * @return ファイルキャッシュ参照 */ protected CachedReference createCachedReference(Object obj){ File file = null; try{ file = createFile(obj); return new FileCachedReference( file, obj, externalizer ); }catch(IOException e){ if(file != null){ file.delete(); } return null; } } }
32.330556
106
0.537847
993d4c313b3b89e704bcbc598dd33ab8b05a1c63
459
package com.saas.training.request; import com.saas.pub.QueryParam; import com.zpsenior.graphql4j.annotation.Input; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @Data @ToString(callSuper = true) @EqualsAndHashCode(callSuper = false) @Input("QueryTeacherParam") public class QueryTeacherParam extends QueryParam { private String tenantId; private long staffId; public QueryTeacherParam() { super("staff_id"); } }
18.36
51
0.782135
ea0355835e82ccbd1c99d3046b98c6976d02e674
4,226
package com.bosssoft.hr.train.j2se.basic.example.socket; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Calendar; import java.util.Iterator; /** * @author HetFrame * @Description 服务端 * @date 2020/5/31 21:57 */ @Slf4j public class NioServerSocket implements Starter { private static final int PORT = 6789; private static final String LINE = "------------------------------------------------"; @Override public boolean start() { ServerSocketChannel serverSocket = null; try { //服务初始化 serverSocket = ServerSocketChannel.open(); //设置为非阻塞 serverSocket.configureBlocking(false); //绑定端口 serverSocket.bind(new InetSocketAddress("localhost", PORT)); //注册OP_ACCEPT事件(即监听该事件,如果有客户端发来连接请求,则该键在select()后被选中) Selector selector = Selector.open(); serverSocket.register(selector, SelectionKey.OP_ACCEPT); Calendar ca = Calendar.getInstance(); log.info("服务端启动"); log.info(LINE); //轮询服务 int flag = 0; while (flag < 100) { //选择准备好的事件 selector.select(); //已选择的键集 Iterator<SelectionKey> it = selector.selectedKeys().iterator(); //处理已选择键集事件 while (it.hasNext()) { SelectionKey key = it.next(); //处理掉后将键移除,避免重复消费(因为下次选择后,还在已选择键集中) it.remove(); //处理连接请求 if (key.isAcceptable()) { //处理请求 SocketChannel socket = serverSocket.accept(); socket.configureBlocking(false); //注册read,监听客户端发送的消息 socket.register(selector, SelectionKey.OP_READ); //keys为所有键,除掉serverSocket注册的键就是已连接socketChannel的数量 String message = "Hello Client" + (selector.keys().size() - 1) + "!"; //向客户端发送消息 socket.write(ByteBuffer.wrap(message.getBytes())); InetSocketAddress address = (InetSocketAddress) socket.getRemoteAddress(); //输出客户端地址 log.info(ca.getTime() + "\t" + address.getHostString() + ":" + address.getPort() + "\t"); log.info("客户端已连接"); log.info(LINE); } if (key.isReadable()) { SocketChannel socket = (SocketChannel) key.channel(); InetSocketAddress address = (InetSocketAddress) socket.getRemoteAddress(); log.info(ca.getTime() + "\t" + address.getHostString() + ":" + address.getPort() + "\t"); ByteBuffer bf = ByteBuffer.allocate(1024 * 4); int len = 0; byte[] res = new byte[1024 * 4]; //捕获异常,因为在客户端关闭后会发送FIN报文,会触发read事件,但连接已关闭,此时read()会产生异常 while ((len = socket.read(bf)) != 0) { bf.flip(); bf.get(res, 0, len); log.info(new String(res, 0, len)); bf.clear(); } log.info(LINE); } } flag++; } } catch (IOException e) { log.error(e.toString()); log.info("服务器错误,服务器停止"); log.info(LINE); return false; } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { log.error(e.getMessage()); } } } return true; } }
37.732143
98
0.471368
d1c0485065c3e015fd5575cade3edff4334bb1e8
2,640
package org.infinispan.persistence.cloud.configuration; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.Properties; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.testng.annotations.Test; @Test(groups = "unit", testName = "persistence.cloud.configuration.ConfigurationTest") public class ConfigurationTest { public void testCacheStoreConfiguration() { Properties props = new Properties(); props.put("key1", "val1"); props.put("key2", "val2"); ConfigurationBuilder b = new ConfigurationBuilder(); b.persistence().addStore(CloudStoreConfigurationBuilder.class) .provider("transient") .location("test-location") .identity("me") .credential("s3cr3t") .container("test-container") .endpoint("http://test.endpoint") .compress(true) .properties(props) .normalizeCacheNames(true); Configuration configuration = b.build(); CloudStoreConfiguration store = (CloudStoreConfiguration) configuration.persistence().stores().get(0); assertEquals(store.provider(), "transient"); assertEquals(store.location(), "test-location"); assertEquals(store.identity(), "me"); assertEquals(store.credential(), "s3cr3t"); assertEquals(store.container(), "test-container"); assertEquals(store.endpoint(), "http://test.endpoint"); assertTrue(store.compress()); assertEquals(store.properties().get("key1"), "val1"); assertEquals(store.properties().get("key2"), "val2"); assertTrue(store.normalizeCacheNames()); b = new ConfigurationBuilder(); b.persistence().addStore(CloudStoreConfigurationBuilder.class).read(store); Configuration configuration2 = b.build(); CloudStoreConfiguration store2 = (CloudStoreConfiguration) configuration2.persistence().stores() .get(0); assertEquals(store2.provider(), "transient"); assertEquals(store2.location(), "test-location"); assertEquals(store2.identity(), "me"); assertEquals(store2.credential(), "s3cr3t"); assertEquals(store2.container(), "test-container"); assertEquals(store2.endpoint(), "http://test.endpoint"); assertTrue(store2.compress()); assertEquals(store2.properties().get("key1"), "val1"); assertEquals(store2.properties().get("key2"), "val2"); assertTrue(store2.normalizeCacheNames()); assertTrue(store2.normalizeCacheNames()); } }
42.580645
108
0.679924
38debf2b85347f6b91c61d4dce304115b5f6f492
144
package com.springboot.service; import com.springboot.entity.Role; public interface RoleService { public Role findRoleById(long roleId); }
14.4
39
0.791667
bdec19fca4ff9eb05330308a2e29d09e6b116185
4,824
package py.com.sodep.mobileforms.api.entities.forms.elements; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Transient; import py.com.sodep.mobileforms.api.entities.SodepEntity; import py.com.sodep.mobileforms.api.entities.dynamicvalues.Filter; import py.com.sodep.mobileforms.api.entities.forms.common.interfaces.IInstanceId; import py.com.sodep.mobileforms.api.entities.forms.elements.ElementPrototype.InstantiabilityType; @Entity @Table(schema = "forms", name = "element_instances") @SequenceGenerator(name = "seq_element_instances", sequenceName = "forms.seq_element_instances") public class ElementInstance extends SodepEntity implements IInstanceId { /** * */ private static final long serialVersionUID = 1L; private ElementPrototype prototype; private Integer position; private Boolean visible; private Boolean required; private String fieldName; private Long defaultValueLookup; private String defaultValueColumn; private String instanceId; private List<Filter> filters; public ElementInstance(){ } @Override public void prePersist() { super.prePersist(); if (prototype.getInstantiability() == InstantiabilityType.TEMPLATE) { throw new RuntimeException("A template prototype cannot be a template"); } } @Override public void preUpdate() { super.preUpdate(); if (prototype.getInstantiability() == InstantiabilityType.TEMPLATE) { throw new RuntimeException("A template prototype cannot be a template"); } } @Override @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "seq_element_instances") @Column(unique = true, nullable = false) public Long getId() { return id; } @ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST }) @JoinColumn(name = "prototype_id") public ElementPrototype getPrototype() { return prototype; } public void setPrototype(ElementPrototype prototype) { this.prototype = prototype; } @Column(nullable = false) public Integer getPosition() { return position; } public void setPosition(Integer position) { this.position = position; } public Boolean getVisible() { return visible; } public void setVisible(Boolean visible) { this.visible = visible; } public Boolean getRequired() { return required; } public void setRequired(Boolean required) { this.required = required; } @Column(name = "field_name") public String getFieldName() { if (fieldName == null) { return getInstanceId(); } return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } @Override public ElementInstance clone() throws CloneNotSupportedException { ElementInstance clone = (ElementInstance) super.clone(); clone.id = null; if (prototype.getInstantiability().equals(ElementPrototype.InstantiabilityType.EMBEDDED)) { clone.prototype = prototype.clone(); } if (filters != null && !filters.isEmpty()) { clone.filters = new ArrayList<Filter>(); for (Filter f : filters) { Filter fClone = f.clone(); fClone.setElementInstance(clone); clone.filters.add(fClone); } } else { clone.filters = null; } return clone; } @Transient public Boolean isEmbedded() { return prototype.isEmbedded(); } // Long ago I created this field but for some // reason I wasn't told of, it was made transient. It utterly // defeated the original purpose. // // jmpr 22/12/2012 @Override @Column(name = "instance_id") public String getInstanceId() { if (instanceId != null) { return instanceId; } if (id != null) { return "element" + id; } return null; } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } @OneToMany(mappedBy = "elementInstance", cascade = { CascadeType.PERSIST }) public List<Filter> getFilters() { return filters; } public void setFilters(List<Filter> filters) { this.filters = filters; } @Column(name="default_value_lookup") public Long getDefaultValueLookupTableId() { return defaultValueLookup; } public void setDefaultValueLookupTableId(Long defaultValueLookup) { this.defaultValueLookup = defaultValueLookup; } @Column(name="default_value_column") public String getDefaultValueColumn() { return defaultValueColumn; } public void setDefaultValueColumn(String defaultValueColumn) { this.defaultValueColumn = defaultValueColumn; } }
23.881188
97
0.748134
03d38eab9a9aefb80cdc387e2d6a62f6d273cd1e
1,294
package ejemplo2; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; // La clase Paso define un cerrojo con un Condition para la variable booleana cerrado // que es comprobada por un proceso. // Si vale false(abierto) el proceso puede continuar. Si es true(cerrado) el proceso se detiene public class Paso { private boolean cerrado=false; private Lock cerrojo = new ReentrantLock(); private Condition parar = cerrojo.newCondition(); public void mirar() { try { cerrojo.lock(); while(cerrado) { try { parar.await(); } catch(InterruptedException ie){ } } } finally { cerrojo.unlock(); } } public void abrir() { try { cerrojo.lock(); cerrado=false; parar.signalAll(); } finally { cerrojo.unlock(); } } public void cerrar() { try { cerrojo.lock(); cerrado=true; } finally { cerrojo.unlock(); } } }
20.870968
95
0.502318
e2182e32ccd0badd86f735e8ceccfe8ec07f4c22
1,675
package com.twu.biblioteca.servicetest; import com.twu.biblioteca.entity.UserEntity; import com.twu.biblioteca.service.UserService; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Created by Qiaoying Zhao on 2017/2/25. */ public class UserServiceTest { @Before public void setUp() throws Exception { UserService userService = UserService.getInstance(); List<UserEntity> userEntityList = new ArrayList<UserEntity>(); } /** * Method: init() * ?How to Test Method like this? */ @Test public void testInitIsOk() throws Exception { List<UserEntity> userList = null; UserService userService = UserService.getInstance(); userService.init(); } /** * Method: checkUser(String userName, String password) */ @Test public void testCheckUserReturnTrue() throws Exception { String name = "Nicole Zhao"; String password = "123456"; assertEquals(true,UserService.getInstance().checkUser(name,password)); } /** * Method: checkUser(String userName, String password) */ @Test public void testCheckUserReturnFalse() throws Exception { String name = "Zhao"; String password = "123456"; assertEquals(false,UserService.getInstance().checkUser(name,password)); } @After public void after() throws Exception { } }
26.171875
80
0.648955
b526796bf752a95e35cf587184814cfd6005eeb5
4,173
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.CRCustomerEligibilityAssessmentEvaluateOutputModelCustomerEligibilityAssessmentInstanceRecord; import javax.validation.Valid; /** * CRCustomerEligibilityAssessmentExecuteOutputModel */ public class CRCustomerEligibilityAssessmentExecuteOutputModel { private CRCustomerEligibilityAssessmentEvaluateOutputModelCustomerEligibilityAssessmentInstanceRecord customerEligibilityAssessmentInstanceRecord = null; private String date = null; private String customerEligibilityAssessmentExecuteActionTaskReference = null; private Object customerEligibilityAssessmentExecuteActionTaskRecord = null; private String executeRecordReference = null; private Object executeResponseRecord = null; /** * Get customerEligibilityAssessmentInstanceRecord * @return customerEligibilityAssessmentInstanceRecord **/ public CRCustomerEligibilityAssessmentEvaluateOutputModelCustomerEligibilityAssessmentInstanceRecord getCustomerEligibilityAssessmentInstanceRecord() { return customerEligibilityAssessmentInstanceRecord; } public void setCustomerEligibilityAssessmentInstanceRecord(CRCustomerEligibilityAssessmentEvaluateOutputModelCustomerEligibilityAssessmentInstanceRecord customerEligibilityAssessmentInstanceRecord) { this.customerEligibilityAssessmentInstanceRecord = customerEligibilityAssessmentInstanceRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::DateTime general-info: The date time of the assessment * @return date **/ public String getDate() { return date; } public void setDate(String date) { this.date = date; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to a Customer Eligibility Assessment instance execute service call * @return customerEligibilityAssessmentExecuteActionTaskReference **/ public String getCustomerEligibilityAssessmentExecuteActionTaskReference() { return customerEligibilityAssessmentExecuteActionTaskReference; } public void setCustomerEligibilityAssessmentExecuteActionTaskReference(String customerEligibilityAssessmentExecuteActionTaskReference) { this.customerEligibilityAssessmentExecuteActionTaskReference = customerEligibilityAssessmentExecuteActionTaskReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The execute service call consolidated processing record * @return customerEligibilityAssessmentExecuteActionTaskRecord **/ public Object getCustomerEligibilityAssessmentExecuteActionTaskRecord() { return customerEligibilityAssessmentExecuteActionTaskRecord; } public void setCustomerEligibilityAssessmentExecuteActionTaskRecord(Object customerEligibilityAssessmentExecuteActionTaskRecord) { this.customerEligibilityAssessmentExecuteActionTaskRecord = customerEligibilityAssessmentExecuteActionTaskRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the execute transaction/record * @return executeRecordReference **/ public String getExecuteRecordReference() { return executeRecordReference; } public void setExecuteRecordReference(String executeRecordReference) { this.executeRecordReference = executeRecordReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: Details of the execute action service response * @return executeResponseRecord **/ public Object getExecuteResponseRecord() { return executeResponseRecord; } public void setExecuteResponseRecord(Object executeResponseRecord) { this.executeResponseRecord = executeResponseRecord; } }
36.605263
216
0.823628
37ce12563025c8ff90fb53cb146474ded0168652
3,979
/** */ package com.github.lbroudoux.dsl.eip.impl; import com.github.lbroudoux.dsl.eip.EipPackage; import com.github.lbroudoux.dsl.eip.Metadata; import com.github.lbroudoux.dsl.eip.Metadatable; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Metadatable</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link com.github.lbroudoux.dsl.eip.impl.MetadatableImpl#getOwnedMetadatas <em>Owned Metadatas</em>}</li> * </ul> * </p> * * @generated */ public abstract class MetadatableImpl extends MinimalEObjectImpl.Container implements Metadatable { /** * The cached value of the '{@link #getOwnedMetadatas() <em>Owned Metadatas</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOwnedMetadatas() * @generated * @ordered */ protected EList<Metadata> ownedMetadatas; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected MetadatableImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return EipPackage.Literals.METADATABLE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Metadata> getOwnedMetadatas() { if (ownedMetadatas == null) { ownedMetadatas = new EObjectContainmentEList<Metadata>(Metadata.class, this, EipPackage.METADATABLE__OWNED_METADATAS); } return ownedMetadatas; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case EipPackage.METADATABLE__OWNED_METADATAS: return ((InternalEList<?>)getOwnedMetadatas()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case EipPackage.METADATABLE__OWNED_METADATAS: return getOwnedMetadatas(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case EipPackage.METADATABLE__OWNED_METADATAS: getOwnedMetadatas().clear(); getOwnedMetadatas().addAll((Collection<? extends Metadata>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case EipPackage.METADATABLE__OWNED_METADATAS: getOwnedMetadatas().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case EipPackage.METADATABLE__OWNED_METADATAS: return ownedMetadatas != null && !ownedMetadatas.isEmpty(); } return super.eIsSet(featureID); } } //MetadatableImpl
26.006536
127
0.621764
ef743c46c03482f4767e098e4b99e1f9462f2539
233
package me.coopersully.Cursecraft.blocks.AdvancedWorkbench; import com.google.gson.JsonObject; public class AdvancedWorkbenchJSONFormat { JsonObject inputA; JsonObject inputB; String outputItem; int outputAmount; }
21.181818
59
0.785408
a2075bf4a96d87501faa230491dcf63713a14e9f
808
package io.graversen.rust.rcon.objects.rust; import com.google.gson.annotations.SerializedName; public class ServerChat implements IChat { @SerializedName("Message") private String message; @SerializedName("UserId") private String steamId; @SerializedName("Username") private String displayName; @SerializedName("Color") private String colorHex; @SerializedName("Time") private Long timestamp; @Override public String getMessage() { return message; } public String getSteamId() { return steamId; } public String getDisplayName() { return displayName; } public String getColorHex() { return colorHex; } public Long getTimestamp() { return timestamp; } }
16.833333
50
0.639851
aa51bec724f42049be7aee6edbe239efbb64e4ed
3,786
package kr.co.daou.sdev.altong.controller.admin; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.inject.Provider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import kr.co.daou.sdev.altong.domain.admin.AdminUser; import kr.co.daou.sdev.altong.domain.project.DaouService; import kr.co.daou.sdev.altong.service.AdminUserService; import kr.co.daou.sdev.altong.service.DaouServiceService; import lombok.extern.slf4j.Slf4j; @Slf4j @Controller public class AdminUserController { @Autowired private Provider<AdminUser> adminUserProvider; @Autowired private AdminUserService adminUserService; @Autowired private DaouServiceService daouServiceService; @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST}) public String login() { return "login"; } /** * 운영자 리스트 * @param model model * @param pageable pageable * @return view */ @Secured("ROLE_ADMIN") @GetMapping(value = "/admins") public String getAdmins(Model model, @PageableDefault(sort = "lastLoginDate", direction = Sort.Direction.DESC) Pageable pageable) { Page<AdminUser> pageResult = adminUserService.getAllAdminUsers(pageable); model.addAttribute("pageResult", pageResult); return "admin/admins"; } /** * 운영자 등록 폼 * @return view */ @Secured("ROLE_ADMIN") @GetMapping(value = "/admins", params = "write") public String adminWriteForm() { return "admin/admin-form-modal"; } /** * 운영자 수정 폼 * @param model model * @return view */ @Secured("ROLE_ADMIN") @GetMapping(value = "/admins/{userId}") public String adminModifyForm(Model model, @PathVariable("userId") String userId) { model.addAttribute("adminUser", adminUserService.loadUserByUsername(userId)); return "admin/admin-form-modal"; } /** * 나의 비밀번호 변경 폼 * @return view */ @Secured("ROLE_USER") @GetMapping(value = "/admins/password") public String passwordForm() { return "admin/password-form-modal"; } /** * 나의 정보 변경 * @param model model * @return view */ @Secured("ROLE_USER") @GetMapping(value = "/admins/user-info") public String userInfoForm(Model model) { AdminUser adminUser = adminUserProvider.get(); model.addAttribute("adminUser", adminUserService.loadUserByUsername(adminUser.getUserId())); return "admin/admin-form-modal"; } @Secured("ROLE_ADMIN") @GetMapping(value = "/admins/{userId}/services") public String adminUserServicesModal(Model model, @PathVariable String userId) { Set<DaouService> allServices = daouServiceService.getAllDaouServices(); AdminUser adminUser = adminUserService.getAdminUser(userId); log.debug("allServices.size()={}", allServices.size()); List<DaouService> unusedServices = new ArrayList<>(); boolean isUnused = true; for (DaouService service : allServices) { for (DaouService adminService : adminUser.getServices()) { if (service.equals(adminService)) { isUnused = false; break; } } if (isUnused) { unusedServices.add(service); } isUnused = true; } model.addAttribute("allServices", unusedServices); model.addAttribute("adminUser", adminUser); return "/admin/admin-services-modal"; } }
26.851064
132
0.745114
8659f6f66eda77ed49206808c0f62ba9ceb3f050
1,216
package Javis; import java.io.IOException; import java.net.ServerSocket; import java.util.ArrayList; public class Server { ServerSocket server; ArrayList<ChatServer> Chats; int server_number; Server() { server_number = 0; Chats = new ArrayList<ChatServer>(); try { server = new ServerSocket(9090); } catch (IOException e) { e.printStackTrace(); } } Rsocket accept_socket() { if (server != null) { try { Rsocket client = new Rsocket(server.accept()); System.out.println("connected"); client.send("connect"); return client; } catch (IOException e) { e.printStackTrace(); } } return null; } User new_user() { Rsocket rs = accept_socket(); if (rs != null) { rs.send("id:"); String id = rs.recieve(); User user = new User(rs, id, id, this); return user; } return null; } void new_server() { server_number += 1; Chats.add(new ChatServer("" + (server_number), this)); } }
22.943396
62
0.502467
f00c54f42c034f1d8f3753044d6d6ab498918357
13,532
package cz.geek.fio.model; import lombok.Data; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.datatype.XMLGregorianCalendar; import java.math.BigDecimal; import java.math.BigInteger; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "column22", "column0", "column1", "column14", "column2", "column10", "column3", "column12", "column4", "column5", "column6", "column7", "column16", "column8", "column9", "column18", "column25", "column26", "column17" }) @Data public class Transaction { @XmlElement(name = "column_22", namespace = "http://www.fio.cz/IBSchema", required = true) protected Column22 column22; @XmlElement(name = "column_0", namespace = "http://www.fio.cz/IBSchema", required = true) protected Column0 column0; @XmlElement(name = "column_1", namespace = "http://www.fio.cz/IBSchema", required = true) protected Column1 column1; @XmlElement(name = "column_14", namespace = "http://www.fio.cz/IBSchema", required = true) protected Column14 column14; @XmlElement(name = "column_2", namespace = "http://www.fio.cz/IBSchema") protected Column2 column2; @XmlElement(name = "column_10", namespace = "http://www.fio.cz/IBSchema") protected Column10 column10; @XmlElement(name = "column_3", namespace = "http://www.fio.cz/IBSchema") protected Column3 column3; @XmlElement(name = "column_12", namespace = "http://www.fio.cz/IBSchema") protected Column12 column12; @XmlElement(name = "column_4", namespace = "http://www.fio.cz/IBSchema") protected Column4 column4; @XmlElement(name = "column_5", namespace = "http://www.fio.cz/IBSchema") protected Column5 column5; @XmlElement(name = "column_6", namespace = "http://www.fio.cz/IBSchema") protected Column6 column6; @XmlElement(name = "column_7", namespace = "http://www.fio.cz/IBSchema") protected Column7 column7; @XmlElement(name = "column_16", namespace = "http://www.fio.cz/IBSchema") protected Column16 column16; @XmlElement(name = "column_8", namespace = "http://www.fio.cz/IBSchema") protected Column8 column8; @XmlElement(name = "column_9", namespace = "http://www.fio.cz/IBSchema") protected Column9 column9; @XmlElement(name = "column_18", namespace = "http://www.fio.cz/IBSchema") protected Column18 column18; @XmlElement(name = "column_25", namespace = "http://www.fio.cz/IBSchema") protected Column25 column25; @XmlElement(name = "column_26", namespace = "http://www.fio.cz/IBSchema") protected Column26 column26; @XmlElement(name = "column_17", namespace = "http://www.fio.cz/IBSchema") protected Column17 column17; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column0 { @XmlValue @XmlSchemaType(name = "date") protected XMLGregorianCalendar value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column1 { @XmlValue protected BigDecimal value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column10 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column12 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) public static class Column14 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getName() { return name; } public void setName(String value) { this.name = value; } public BigInteger getId() { return id; } public void setId(BigInteger value) { this.id = value; } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column16 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column17 { @XmlValue protected long value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column18 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column2 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column22 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column25 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column26 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column3 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column4 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column5 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column6 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column7 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column8 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @Data public static class Column9 { @XmlValue protected String value; @XmlAttribute(name = "name", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "token") protected String name; @XmlAttribute(name = "id", required = true) @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger id; } }
28.791489
94
0.610922
9bcc7472b205780888da0154468ea0af332f862c
194
package github.banana.design.factory; /** * 4.2 自行车产品工厂类 */ public class BikeFactory implements TransFactory { @Override public Trans getTrans() { return new Bike(); } }
14.923077
50
0.649485
2fde1ad6ff3f90f6323005efb80739d81bf4542f
753
package com.herbertgao.telegram.database.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.herbertgao.telegram.database.entity.Lunar; import com.herbertgao.telegram.database.mapper.LunarMapper; import org.springframework.stereotype.Service; import java.time.LocalDate; /** * 农历服务 * * @author HerbertGao * @date 2020-11-29 */ @Service public class LunarService extends ServiceImpl<LunarMapper, Lunar> { public Lunar getLunarByDate(LocalDate date) { QueryWrapper<Lunar> wrapper = new QueryWrapper<>(); wrapper.lambda() .eq(Lunar::getGregoriandatetime, date); return this.getOne(wrapper); } }
27.888889
67
0.747676
941623ac7ca6d0224c2ed300f7b3f1a68cf9c0ea
2,072
package ru.geracimov.otus.spring.lighthouse.managementserver.feign; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import feign.Response; import feign.codec.ErrorDecoder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import ru.geracimov.otus.spring.lighthouse.managementserver.feign.exception.FeignClientException; import ru.geracimov.otus.spring.lighthouse.managementserver.feign.exception.FeignServerException; import java.io.IOException; import java.io.Reader; public class FeignErrorDecoder implements ErrorDecoder { @Override public Exception decode(String methodKey, Response response) { ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); String reason = ""; try (Reader reader = response.body() .asReader()) { String reasonJson = readValue(reader); ExceptionMessage exceptionMessage = mapper.readValue(reasonJson, ExceptionMessage.class); reason = exceptionMessage.message; } catch (IOException e) { e.printStackTrace(); } return response.status() >= 400 && response.status() <= 499 ? new FeignClientException(response.status(), reason) : new FeignServerException(response.status(), reason); } @Getter @Setter @NoArgsConstructor private static class ExceptionMessage { private String timestamp; private int status; private String error; private String message; private String path; } private String readValue(Reader reader) throws IOException { StringBuilder to = new StringBuilder(); char[] buf = new char[2048]; int nRead; while ((nRead = reader.read(buf)) != -1) { to.append(buf, 0, nRead); } return to.toString(); } }
33.967213
97
0.653958
ce4bdbfd2411ec8e6cbdc3222181f0eed318eddf
467
package com.example.dealball.main.plus; import com.example.dealball.main.base.BaseUiOperate; import com.example.dealball.main.base.BaseView; import java.util.Date; public interface PlusContact { interface View extends BaseUiOperate { void showToast(String meg); } interface Presenter{ void post(Integer allNumber, double longitude, double latitude, String time, Integer type, String context, boolean haveBall, String token); } }
24.578947
147
0.745182
acd491fe280b872400ea68b560ee69fb5b648bfa
848
package cn.toside.music.mobile.cache; import android.os.AsyncTask; import com.facebook.react.bridge.Promise; // https://github.com/midas-gufei/react-native-clear-app-cache/tree/master/android/src/main/java/com/learnta/clear public class CacheClearAsyncTask extends AsyncTask<Integer,Integer,String> { public CacheModule cacheModule = null; public Promise promise; public CacheClearAsyncTask(CacheModule clearCacheModule, Promise promise) { super(); this.cacheModule = clearCacheModule; this.promise = promise; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); promise.resolve(null); } @Override protected String doInBackground(Integer... params) { cacheModule.clearCache(); return null; } }
24.941176
114
0.740566
37aed02ef0c7bfafdda78fe3b3241ee9d99a1dff
5,685
package com.westlake.air.propro.algorithm.peak; import com.westlake.air.propro.domain.bean.analyse.*; import com.westlake.air.propro.domain.bean.score.IonPeak; import com.westlake.air.propro.domain.bean.score.PeptideFeature; import com.westlake.air.propro.domain.bean.score.PeakGroup; import com.westlake.air.propro.domain.db.AnalyseDataDO; import com.westlake.air.propro.algorithm.feature.RtNormalizerScorer; import com.westlake.air.propro.domain.params.DeveloperParams; import com.westlake.air.propro.service.AnalyseDataService; import com.westlake.air.propro.service.AnalyseOverviewService; import com.westlake.air.propro.service.TaskService; import com.westlake.air.propro.service.PeptideService; import com.westlake.air.propro.utils.MathUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.HashMap; import java.util.List; /** * Created by Nico Wang Ruimin * Time: 2018-08-20 15:47 */ @Component("featureExtractor") public class FeatureExtractor { public final Logger logger = LoggerFactory.getLogger(FeatureExtractor.class); @Autowired AnalyseDataService analyseDataService; @Autowired AnalyseOverviewService analyseOverviewService; @Autowired PeptideService peptideService; @Autowired GaussFilter gaussFilter; @Autowired PeakPicker peakPicker; @Autowired SignalToNoiseEstimator signalToNoiseEstimator; @Autowired ChromatogramPicker chromatogramPicker; @Autowired FeatureFinder featureFinder; @Autowired RtNormalizerScorer RTNormalizerScorer; @Autowired TaskService taskService; /** * @param dataDO XIC后的数据对象 * @param intensityMap 得到标准库中peptideRef对应的碎片和强度的键值对 * @param sigmaSpacing * @return */ public PeptideFeature getExperimentFeature(AnalyseDataDO dataDO, HashMap<String, Float> intensityMap, SigmaSpacing sigmaSpacing) { if (dataDO.getIntensityMap() == null || dataDO.getIntensityMap().size() == 0) { return new PeptideFeature(false); } HashMap<String, RtIntensityPairsDouble> ionPeaks = new HashMap<>(); HashMap<String, List<IonPeak>> ionPeakParams = new HashMap<>(); //对每一个chromatogram进行运算,dataDO中不含有ms1 HashMap<String, double[]> noise1000Map = new HashMap<>(); HashMap<String, Double[]> intensitiesMap = new HashMap<>(); //将没有提取到信号的CutInfo过滤掉,同时将Float类型的参数调整为Double类型进行计算 for (String cutInfo : intensityMap.keySet()) { //获取对应的XIC数据 Float[] intensityArray = dataDO.getIntensityMap().get(cutInfo); //如果没有提取到信号,dataDO为null if (intensityArray == null) { continue; } Double[] intensityDoubleArray = new Double[intensityArray.length]; for (int k = 0; k < intensityArray.length; k++) { intensityDoubleArray[k] = Double.parseDouble(intensityArray[k].toString()); } intensitiesMap.put(cutInfo, intensityDoubleArray); } if (intensitiesMap.size() == 0) { return new PeptideFeature(false); } //计算GaussFilter Double[] rtDoubleArray = new Double[dataDO.getRtArray().length]; for (int k = 0; k < rtDoubleArray.length; k++) { rtDoubleArray[k] = Double.parseDouble(dataDO.getRtArray()[k].toString()); } PeptideSpectrum peptideSpectrum = new PeptideSpectrum(rtDoubleArray, intensitiesMap); HashMap<String, Double[]> smoothIntensitiesMap = gaussFilter.filter(rtDoubleArray, intensitiesMap, sigmaSpacing); //对每一个片段离子选峰 double libIntSum = MathUtil.sum(intensityMap.values()); HashMap<String, Double> normedLibIntMap = new HashMap<>(); for (String cutInfo : intensitiesMap.keySet()) { //计算两个信噪比 double[] noises200 = signalToNoiseEstimator.computeSTN(rtDoubleArray, smoothIntensitiesMap.get(cutInfo), 200, 30); double[] noisesOri1000 = signalToNoiseEstimator.computeSTN(rtDoubleArray, intensitiesMap.get(cutInfo), 1000, 30); //根据信噪比和峰值形状选择最高峰,用降噪200及平滑过后的图去挑选Peak峰 RtIntensityPairsDouble maxPeakPairs = peakPicker.pickMaxPeak(rtDoubleArray, smoothIntensitiesMap.get(cutInfo), noises200); //根据信噪比和最高峰选择谱图 if (maxPeakPairs == null) { logger.info("Error: MaxPeakPairs were null!" + rtDoubleArray.length); break; } List<IonPeak> ionPeakList = chromatogramPicker.pickChromatogram(rtDoubleArray, intensitiesMap.get(cutInfo), smoothIntensitiesMap.get(cutInfo), noisesOri1000, maxPeakPairs); ionPeaks.put(cutInfo, maxPeakPairs); ionPeakParams.put(cutInfo, ionPeakList); noise1000Map.put(cutInfo, noisesOri1000); normedLibIntMap.put(cutInfo, intensityMap.get(cutInfo) / libIntSum); } if (ionPeakParams.size() == 0) { return new PeptideFeature(false); } List<PeakGroup> peakGroupFeatureList; if (DeveloperParams.USE_NEW_PEAKGROUP_SELECTOR) { peakGroupFeatureList = featureFinder.findFeaturesNew(peptideSpectrum, ionPeaks, ionPeakParams, noise1000Map); }else { peakGroupFeatureList = featureFinder.findFeatures(peptideSpectrum, ionPeaks, ionPeakParams, noise1000Map); } PeptideFeature featureResult = new PeptideFeature(true); featureResult.setPeakGroupList(peakGroupFeatureList); featureResult.setNormedLibIntMap(normedLibIntMap); return featureResult; } }
41.801471
184
0.697801
94be929a88e5bd243717d31c9c0fd3962bc0b236
4,660
package com.github.zkoalas.jwts; import com.github.zkoalas.jwts.annotation.Logical; import com.github.zkoalas.jwts.annotation.RequiresPermissions; import com.github.zkoalas.jwts.annotation.RequiresRoles; import com.github.zkoalas.jwts.exception.ErrorTokenException; import com.github.zkoalas.jwts.exception.ExpiredTokenException; import com.github.zkoalas.jwts.exception.UnauthorizedException; import com.github.zkoalas.jwts.provider.*; import com.github.zkoalas.jwts.util.SubjectUtil; import com.github.zkoalas.jwts.util.TokenUtil; import io.jsonwebtoken.ExpiredJwtException; import lombok.extern.slf4j.Slf4j; import org.springframework.util.ObjectUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; import java.math.BigInteger; /** * 拦截器 */ @Slf4j public class TokenInterceptor extends HandlerInterceptorAdapter { private BaseTokenStore baseTokenStore; public TokenInterceptor(BaseTokenStore tokenStore, Integer maxToken) { setTokenStore(tokenStore); setMaxToken(maxToken); } public TokenInterceptor(BaseTokenStore localTokenStore) { this.baseTokenStore = localTokenStore; } public void setTokenStore(BaseTokenStore baseTokenStore) { this.baseTokenStore = baseTokenStore; } public void setMaxToken(Integer maxToken) { Config.getInstance().setMaxToken(maxToken); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String access_token = request.getParameter("access_token"); if (access_token == null || access_token.trim().isEmpty()) { access_token = request.getHeader("Authorization"); if (access_token != null && access_token.length() >= 7) { access_token = access_token.substring(7); } } if (access_token == null || access_token.trim().isEmpty()) { throw new ErrorTokenException("token不能为空"); } String subject; try { String tokenKey = baseTokenStore.getTokenKey(); log.debug("-------------------------------------------"); log.debug("开始解析token:" + access_token); log.debug("使用tokenKey:" + tokenKey); subject = TokenUtil.parseToken(access_token, tokenKey); } catch (ExpiredJwtException e) { log.debug("token已过期"); throw new ExpiredTokenException(); } catch (Exception e) { log.debug(e.getMessage()); throw new ErrorTokenException(); } Token token = baseTokenStore.findToken(subject, access_token); if (token == null) { log.debug("token不在系统中"); throw new ErrorTokenException(); } // 检查权限 if (handler instanceof HandlerMethod) { Method method = ((HandlerMethod) handler).getMethod(); if (method != null) { if (!checkPermission(method, token) || !checkRole(method, token)) { throw new UnauthorizedException(); } } } request.setAttribute(SubjectUtil.REQUEST_TOKEN_NAME, token); log.debug("-------------------------------------------"); return super.preHandle(request, response, handler); } private boolean checkPermission(Method method, Token token) { RequiresPermissions annotation = method.getAnnotation(RequiresPermissions.class); if (annotation == null) { annotation = method.getDeclaringClass().getAnnotation(RequiresPermissions.class); if (annotation == null) { return true; } } String[] requiresPermissions = annotation.value(); Logical logical = annotation.logical(); return SubjectUtil.hasPermission(token, requiresPermissions, logical); } private boolean checkRole(Method method, Token token) { RequiresRoles annotation = method.getAnnotation(RequiresRoles.class); if (annotation == null) { annotation = method.getDeclaringClass().getAnnotation(RequiresRoles.class); if (annotation == null) { return true; } } String[] requiresRoles = annotation.value(); Logical logical = annotation.logical(); return SubjectUtil.hasRole(token, requiresRoles, logical); } }
38.833333
121
0.653863
b15b612b152ca8da295019f28566da72a54ea695
6,037
package gov.usgs.traveltime.tables; import gov.usgs.traveltime.AllBrnRef; import gov.usgs.traveltime.AuxTtRef; import gov.usgs.traveltime.ModConvert; import gov.usgs.traveltime.TtStatus; import java.io.IOException; import java.util.ArrayList; /** * Travel-time table generation driver. * * @author Ray Buland */ public class MakeTables { EarthModel refModel; TauModel finModel; ArrayList<BranchData> brnData; /** * Initialize the reference Earth model. This needs to happen in the constructor to ensure that * the travel-time properties file has been read. * * @param earthModel Name of the Earth model */ public MakeTables(String earthModel) { refModel = new EarthModel(earthModel, true); } /** * Create the travel-time tables out of whole cloth. * * @param modelFile Name of the Earth model file * @param phaseFile Name of the file of desired phases * @return Model read status * @throws Exception If an integration interval is illegal */ public TtStatus buildModel(String modelFile, String phaseFile) throws Exception { EarthModel locModel; ModConvert convert; TauModel depModel; SampleSlowness sample; Integrate integrate; DecTTbranch decimate; MakeBranches layout; TtStatus status; // Read the model. status = refModel.readModel(modelFile); // If it read OK, process it. if (status == TtStatus.SUCCESS) { if (TablesUtil.deBugLevel > 2) { // Print the shell summaries. refModel.printShells(); // Print out the radial version. refModel.printModel(); } // Interpolate the model. convert = refModel.getConvert(); locModel = new EarthModel(refModel, convert); locModel.interpolate(); if (TablesUtil.deBugLevel > 0) { // Print the shell summaries. locModel.printShells(); if (TablesUtil.deBugLevel > 2) { // Print out the radial version. locModel.printModel(false, false); } // Print out the Earth flattened version. locModel.printModel(true, true); // Critical points are model slownesses that need to be sampled exactly. locModel.printCritical(); } // Make the initial slowness sampling. sample = new SampleSlowness(locModel); sample.sample('P'); if (TablesUtil.deBugLevel > 0) { sample.printModel('P', "Tau"); } sample.sample('S'); if (TablesUtil.deBugLevel > 0) { sample.printModel('S', "Tau"); } // We need a merged set of slownesses for converted branches (e.g., ScP). sample.merge(); if (TablesUtil.deBugLevel > 0) { sample.printMerge(); } // Fiddle with the sampling so that low velocity zones are // better sampled. sample.depthModel('P'); if (TablesUtil.deBugLevel > 0) { sample.depModel.printDepShells('P'); sample.printModel('P', "Depth"); } sample.depthModel('S'); if (TablesUtil.deBugLevel > 0) { sample.depModel.printDepShells('S'); sample.printModel('S', "Depth"); } depModel = sample.getDepthModel(); if (TablesUtil.deBugLevel > 2) { depModel.printDepShells('P'); depModel.printDepShells('S'); } // Do the integrals. integrate = new Integrate(depModel); integrate.doTauIntegrals('P'); integrate.doTauIntegrals('S'); // The final model only includes depth samples that will be // of interest for earthquake location. finModel = integrate.getFinalModel(); if (TablesUtil.deBugLevel > 1) { finModel.printShellInts('P'); finModel.printShellInts('S'); } // Reorganize the integral data. finModel.makePieces(); if (TablesUtil.deBugLevel > 0) { // These final shells control making the branches. finModel.printShellSpec('P'); finModel.printShellSpec('S'); if (TablesUtil.deBugLevel > 2) { // Proxy depth sampling before decimation. finModel.printProxy(); } } // Decimate the default sampling for the up-going branches. decimate = new DecTTbranch(finModel, convert); decimate.upGoingDec('P'); decimate.upGoingDec('S'); if (TablesUtil.deBugLevel > 0) { if (TablesUtil.deBugLevel > 2) { finModel.pPieces.printDec(); finModel.sPieces.printDec(); } // Proxy depth sampling after decimation. finModel.printProxy(); } // Make the branches. if (TablesUtil.deBugLevel > 0) { finModel.printDepShells('P'); finModel.printDepShells('S'); } layout = new MakeBranches(finModel, decimate); layout.readPhases(phaseFile); // Read the desired phases from a file if (TablesUtil.deBugLevel > 0) { if (TablesUtil.deBugLevel > 1) { layout.printPhases(); } layout.printBranches(false, true); } brnData = layout.getBranches(); // Do the final decimation. finModel.decimateP(); if (TablesUtil.deBugLevel > 0) { finModel.printP(); } finModel.decimateTauX('P'); finModel.decimateTauX('S'); // Print the final branches. if (TablesUtil.deBugLevel > 2) { layout.printBranches(true, true); } // Build the branch end ranges. finModel.setEnds(layout.getBranchEnds()); } else { System.out.println("failed to read model: " + status); } return status; } /** * Fill in all the reference data needed to calculate travel times from the table generation. * * @param serName Name of the model serialization file * @param auxTT Auxiliary travel-time data * @return The reference data for all branches * @throws IOException If serialization file write fails */ public AllBrnRef fillAllBrnRef(String serName, AuxTtRef auxTT) throws IOException { return new AllBrnRef(serName, finModel, brnData, auxTT); } }
31.941799
97
0.632765
dc3abbec3c29965eb4d94699a8308fa96ba09219
5,186
/******************************************************************************* * Copyright (c) 2017 IBM Corp. * * 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.acmeair.mongo.services; import static com.mongodb.client.model.Filters.eq; import com.acmeair.mongo.ConnectionManager; import com.acmeair.mongo.MongoConstants; import com.acmeair.service.BookingService; import com.acmeair.service.KeyGenerator; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.bson.Document; import org.eclipse.microprofile.opentracing.Traced; import io.opentracing.Span; import io.opentracing.Tracer; public class BookingServiceImpl implements BookingService, MongoConstants { private static final Logger logger = Logger.getLogger(BookingService.class.getName()); private MongoCollection<Document> booking; @Inject Tracer configuredTracer; @Inject KeyGenerator keyGenerator; @Inject ConnectionManager connectionManager; @PostConstruct public void initialization() { MongoDatabase database = connectionManager.getDb(); booking = database.getCollection("booking"); } /** * Book Flight. */ @Traced public String bookFlight(String customerId, String flightId) { try { String bookingId = keyGenerator.generate().toString(); Document bookingDoc = new Document("_id", bookingId) .append("customerId", customerId) .append("flightId", flightId) .append("dateOfBooking", new Date()); booking.insertOne(bookingDoc); return bookingId; } catch (Exception e) { throw new RuntimeException(e); } } @Override public String bookFlight(String customerId, String flightSegmentId, String flightId) { if (flightSegmentId == null) { return bookFlight(customerId, flightId); } else { try { String bookingId = keyGenerator.generate().toString(); Document bookingDoc = new Document("_id", bookingId).append("customerId", customerId) .append("flightId", flightId).append("dateOfBooking", new Date()) .append("flightSegmentId", flightSegmentId); Span activeSpan = configuredTracer.activeSpan(); Tracer.SpanBuilder spanBuilder = configuredTracer.buildSpan("Created bookFlight Span"); if (activeSpan != null) { spanBuilder.asChildOf(activeSpan.context()); } Span childSpan = spanBuilder.startManual(); childSpan.setTag("Created", true); booking.insertOne(bookingDoc); childSpan.finish(); return bookingId; } catch (Exception e) { throw new RuntimeException(e); } } } @Override public String getBooking(String user, String bookingId) { try { return booking.find(eq("_id", bookingId)).first().toJson(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<String> getBookingsByUser(String user) { List<String> bookings = new ArrayList<String>(); if (logger.isLoggable(Level.FINE)) { logger.fine("getBookingsByUser : " + user); } try (MongoCursor<Document> cursor = booking.find(eq("customerId", user)).iterator()) { while (cursor.hasNext()) { Document tempBookings = cursor.next(); Date dateOfBooking = (Date) tempBookings.get("dateOfBooking"); tempBookings.remove("dateOfBooking"); tempBookings.append("dateOfBooking", dateOfBooking.toString()); if (logger.isLoggable(Level.FINE)) { logger.fine("getBookingsByUser cursor data : " + tempBookings.toJson()); } bookings.add(tempBookings.toJson()); } } catch (Exception e) { throw new RuntimeException(e); } return bookings; } @Override @Traced public void cancelBooking(String user, String bookingId) { if (logger.isLoggable(Level.FINE)) { logger.fine("cancelBooking _id : " + bookingId); } try { booking.deleteMany(eq("_id", bookingId)); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Long count() { return booking.count(); } @Override public void dropBookings() { booking.deleteMany(new Document()); } @Override public String getServiceType() { return "mongo"; } }
28.032432
95
0.662553
920986abc2ca03e953859f19d99818b1704f737d
3,211
/* * Licensed by the author of Time4J-project. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. The copyright owner * 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 net.time4j.engine; /** * <p>Type-safe query for format attributes which control the formatting * process. </p> * * @author Meno Hochschild * @see ChronoMerger#createFrom(ChronoEntity, AttributeQuery, boolean, boolean) */ /*[deutsch] * <p>Typsichere Abfrage von Formatattributen zur Steuerung eines * Formatier- oder Parse-Vorgangs. </p> * * @author Meno Hochschild * @see ChronoMerger#createFrom(ChronoEntity, AttributeQuery, boolean, boolean) */ public interface AttributeQuery { //~ Methoden ---------------------------------------------------------- /** * <p>Queries if a format attribute exists for given key. </p> * * @param key attribute key * @return {@code true} if attribute exists else {@code false} */ /*[deutsch] * <p>Ermittelt, ob ein Formatattribut zum angegebenen Schl&uuml;ssel * existiert. </p> * * @param key attribute key * @return {@code true} if attribute exists else {@code false} */ boolean contains(AttributeKey<?> key); /** * <p>Yields a format attribute for given key. </p> * * @param <A> generic type of attribute value * @param key attribute key * @return attribute value * @throws java.util.NoSuchElementException if attribute does not exist */ /*[deutsch] * <p>Ermittelt ein Formatattribut zum angegebenen Schl&uuml;ssel. </p> * * @param <A> generic type of attribute value * @param key attribute key * @return attribute value * @throws java.util.NoSuchElementException if attribute does not exist */ <A> A get(AttributeKey<A> key); /** * <p>Yields a format attribute for given key. </p> * * @param <A> generic type of attribute value * @param key attribute key * @param defaultValue replacement value to be used if attribute does * not exist * @return attribute value */ /*[deutsch] * <p>Ermittelt ein Formatattribut zum angegebenen Schl&uuml;ssel. </p> * * @param <A> generic type of attribute value * @param key attribute key * @param defaultValue replacement value to be used if attribute does * not exist * @return attribute value */ <A> A get( AttributeKey<A> key, A defaultValue ); }
32.765306
83
0.626596
594dce5ac6b20181b386b12a4da7cde6c2210416
5,782
package com.bzh.floodserver.service.serviceImpl; import com.bzh.floodserver.mapper.RiverMapper; import com.bzh.floodserver.model.mapper.*; import com.bzh.floodserver.service.RiverService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; @Service public class RiverServiceImpl implements RiverService { @Autowired private RiverMapper riverMapper; @Override public River riverSelect(String ymdhmA, String ymdhmB, String stcd) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date timestart = null; Date timeend = null; try { timestart = sdf.parse(ymdhmA); timeend = sdf.parse(ymdhmB); } catch (ParseException e) { e.printStackTrace(); } St_rvfcch_b jingJieShuiWei = riverMapper.selectSt_rvfcch_bWrz(stcd); River rivers = riverMapper.riverselect(timestart, timeend, stcd); double chaochu = 0; if (rivers != null && jingJieShuiWei != null) { if (jingJieShuiWei.getWrz() < rivers.getZ()) { chaochu = rivers.getZ() - jingJieShuiWei.getWrz(); rivers.setChaochu(chaochu); } } return rivers; } @Override public Reservoir reservoirService(String stcd, String ymdhmA, String ymdhmB) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date timeA = null; Date timeB = null; try { timeA = sdf.parse(ymdhmA); timeB = sdf.parse(ymdhmB); } catch (ParseException e) { e.printStackTrace(); } return riverMapper.reservoirservice(stcd, timeA, timeB); } @Override public List<Rflow> rflowSelect(Date tmstart, Date tmend) { return riverMapper.rflowselect(tmstart, tmend); } @Override public List<Rlibrary> rlibrarySelect(Date tmstart, Date tmend) { return riverMapper.rlibraryselect(tmstart, tmend); } @Override public List<Ravenue> ravenueSelect(Date tmstart, Date tmend) { return riverMapper.ravenueselect(tmstart, tmend); } @Override public List<Rainfall> rainfallselect(String stcd, String tmstart, String tmend) throws ParseException { //创建一个雨量表的集合 List<Rainfall> list = riverMapper.rainfallselect(stcd, tmstart, tmend); //创建一个遍历时间的对象 Calendar now = Calendar.getInstance(); //创建时间格式 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateFormat.parse(tmstart)); now.setTime(dateFormat.parse(tmend)); //获取时间 Date endTime = now.getTime(); //获取时 int endHour = now.get(Calendar.HOUR_OF_DAY); //获取日 int endDate = now.get(Calendar.DATE); now.add(Calendar.DATE, 1); now.set(Calendar.HOUR_OF_DAY, 7); Rainfall mRainfall = null; List<Rainfall> rainfalls = new ArrayList<>(); calendar.setTime(dateFormat.parse(tmstart)); calendar.add(Calendar.HOUR_OF_DAY, -1); calendar.set(Calendar.MINUTE, 0); int cha = daysBetween(dateFormat.parse(tmstart), now.getTime()) + 1; for (int i = 0; i < cha; i++) { calendar.add(Calendar.HOUR_OF_DAY, 1); mRainfall = new Rainfall(calendar.getTime(), "0.0"); for (int j = 0; j < list.size(); j++) { if (list.get(j).getTm().getTime() == calendar.getTime().getTime()) { if (list.get(j).getDrp() == null) { mRainfall = new Rainfall(calendar.getTime(), "0.0"); } else { mRainfall = list.get(j); } list.remove(j); continue; } } if (calendar.getTime().getTime() > endTime.getTime()) { mRainfall = new Rainfall(calendar.getTime(), "--"); } rainfalls.add(mRainfall); } return rainfalls; } /** * 计算两个日期之间相差的小时差 * * @param smdate 较小的时间 * @param bdate 较大的时间 * @return 相差天数 * @throws ParseException calendar 对日期进行时间操作 * getTimeInMillis() 获取日期的毫秒显示形式 */ public int daysBetween(Date smdate, Date bdate) { Calendar cal = Calendar.getInstance(); cal.setTime(smdate); long time1 = cal.getTimeInMillis(); cal.setTime(bdate); long time2 = cal.getTimeInMillis(); long between_days = (time2 - time1) / (1000 * 3600); return Integer.parseInt(String.valueOf(between_days)); } @Override public List<Rivertime> selectRivertime(String stcd, String ymdhmstart, String ymdhmend) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date timestart = null; Date timeend = null; try { timestart = sdf.parse(ymdhmstart); timeend = sdf.parse(ymdhmend); } catch (ParseException e) { e.printStackTrace(); } List<Rivertime> list = riverMapper.selectRivertime(stcd, timestart, timeend); List<Rivertime> newlist = new ArrayList<>(); Rivertime rivertime; Rivertime newRivertime = null; for (int i = 0; i < list.size(); i++) { if (newRivertime != null) { rivertime = newRivertime; } else { rivertime = list.get(i); } if (i != list.size() - 1) { if (rivertime.getYmdhm().getTime() != list.get(i + 1).getYmdhm().getTime()) { newlist.add(rivertime); newRivertime = null; } else if (rivertime.getZr() != 0.0) { newRivertime = rivertime; continue; } else { newRivertime = null; continue; } } else { if (i != 0) { newlist.add(list.get(i)); } } } for (Rivertime r : newlist) { System.out.println(r); } return newlist; } @Override public List<Reservoirtime> selectReservoirtime(String stcd, String tmstart, String tmend) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date timestart = null; Date timeend = null; try { timestart = sdf.parse(tmstart); timeend = sdf.parse(tmend); } catch (ParseException e) { e.printStackTrace(); } return riverMapper.selectReservoirtime(stcd, timestart, timeend); } }
28.482759
104
0.687997
9bc148fe5d9e067cf77305283c95f94e0682799e
5,853
package GUI; import SmartGraph.Edge; import SmartGraph.Model; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.swing.JFrame; //The 'main' class so to speak public class RPICampousPathsMain extends JFrame{ //Representation private static Model m = null; private static GUI TheInterface = null; private static boolean IgnoreComboBoxListener = false; //A small function which returns a map of buildings and their coordinates public static HashMap<Integer, Pair<Integer>> getButtonCoordinates() { return m.getLocations(); } //A function used to find the shortest path between two buildings public static void findShortestPath(String node1Name, String node2Name) { //Since only an ID or a Name is given for a node, find the other //Therefore, if a name is given, find the ID. And visa versa Edge tempEdge = m.Clarify_IDs_and_Names(Integer.MIN_VALUE, Integer.MIN_VALUE, node1Name, node2Name); //Try to find the shortest path between two locations, if this fails then //catch the Runtime Exception, and set SpecialCase equal to the message try {tempEdge = m.findPath(tempEdge.StartID, tempEdge.EndID, node1Name, node2Name, "");} catch (RuntimeException UnexpectedOutput) { TheInterface.loadPath(null, null); return; } //Put the path in an ArrayList so that the GUI can interpret and //display it. If SpecialCase is not "" then no path was found: skip this ArrayList<SimpleEdge> ThePathIDs = new ArrayList<SimpleEdge>(); ArrayList<Pair<Pair<Integer>>> ThePath = new ArrayList<Pair<Pair<Integer>>>(); //Repeat for each edge //Note, the reason this function is written with a break is because //a path of length 0 is input as the same size as a path of length 1. //This function covers that corner case without any extra code or ifs while(true) { //Add the next edge to ThePathIDs ThePathIDs.add(new SimpleEdge(new Pair<Integer>(tempEdge.StartID, tempEdge.EndID), new Pair<String>(m.getName(tempEdge.StartID), m.getName( tempEdge.EndID)), m.getDirection(tempEdge.StartID, tempEdge.EndID))); //Add the coordinates of the ends of the lines ot be drawn to ThePath ThePath.add(new Pair<Pair<Integer>> (m.getCoordinates(tempEdge.EndID), m.getCoordinates(tempEdge.StartID))); //If (tempEdge.Path == tempEdge) then tempEdge.Start is the first building //in the path, therefore ThePath has been successfully constructed if (tempEdge.Path == tempEdge) break; tempEdge = tempEdge.Path; } //Correct the order Collections.reverse(ThePathIDs); //Present the user with the results. TheInterface.loadPath(ThePath, ThePathIDs); } //A function the Mouse_Listener will //call if the mouse is hovering over a button public static void locationHovered(int InputID) { //If the mouse is hovering over nothing, say so if (InputID == -1) TheInterface.locationHovered(""); //If the mouse is hovering over an intersection, say so else if (m.getName(InputID).length() == 0) TheInterface.locationHovered("Intersection "+InputID); //If the mouse is hovering over a building, say so else TheInterface.locationHovered(m.getName(InputID)); } //A function called by a listener if a location was selected public static void locationSelected(int InputID, String InputBuilding, int Which) { //If this function was called due //to setting a JComboBox, do nothing //Then prevent this function from being called recursively if (IgnoreComboBoxListener) return; IgnoreComboBoxListener = true; //If this function was called via a button listener if (InputID != 0) { //If a button represents an intersection, do nothing if (m.getName(InputID).length() == 0) { //Allow this function to be called again before exiting it IgnoreComboBoxListener = false; return; } //If the button represents a building, set InputBuilding to its name InputBuilding = m.getName(InputID); } //If the building entered does not exist, do nothing else if (!m.buildingExists(InputBuilding)) { //Allow this function to be called again before exiting it IgnoreComboBoxListener = false; return; } //Tell the GUI a location was selected TheInterface.locationSelected(InputBuilding, Which); //If the GUI has two buildings loaded, find the shortest path if (TheInterface.pathReady()) findShortestPath(TheInterface.getStart(), TheInterface.getEnd()); //Allow this function to be called again IgnoreComboBoxListener = false; } //Reset function public static void reset() { TheInterface.reset(); } //Main function public static void main(String args[]) { //Create the model m = new Model(); //A list of building names to be built below ArrayList<String> Buildings = new ArrayList<String>(); //First load the nodes into the graph try {m.readNodes("MapInfo/RPI_map_data_Nodes.csv");} catch (IOException e) {e.printStackTrace();} //Then load the edges into the graph try {m.readEdges("MapInfo/RPI_map_data_Edges.csv");} catch (IOException e) {e.printStackTrace();} //Note: the first call of output buildings builds //essential data structures in Model to be used later one. //Then, generate a list of building names to send to the GUI constructor Iterator<Map.Entry<Integer, String>> i = m.OutputBuildings().entrySet().iterator(); while(i.hasNext()) Buildings.add(i.next().getValue()); //Run the GUI try {TheInterface = new GUI("MapInfo/RPI_campus_map_2010_extra_nodes_edges.png", Buildings);} catch (IOException e) {e.printStackTrace();} //Make m observable m.addObserver(TheInterface); } //To satisfy the compiler private static final long serialVersionUID = 1L; }
34.22807
105
0.729028
3bb14a1c6be799c782005f9a7a49fe7a73179bac
3,588
package vn.fintechviet.content.model; import java.util.Date; import javax.persistence.*; /** * Created by tungn on 9/12/2017. */ @Entity @Table(name = "news") public class News { private long id; private String title; private String shortDescription; private String link; private String imageLink; private NewsCategory newsCategory; private Integer noOfLike; private String status = "ACTIVE"; private Date createdDate; @Id @Column(name = "id") @GeneratedValue(strategy = GenerationType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; } @Basic @Column(name = "title") public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Basic @Column(name = "shortDescription") public String getShortDescription() { return shortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } @Basic @Column(name = "link") public String getLink() { return link; } public void setLink(String link) { this.link = link; } @Basic @Column(name = "imageLink") public String getImageLink() { return imageLink; } public void setImageLink(String imageLink) { this.imageLink = imageLink; } @ManyToOne @JoinColumn(name = "newsCategoryId") public NewsCategory getNewsCategory() { return newsCategory; } public void setNewsCategory(NewsCategory newsCategory) { this.newsCategory = newsCategory; } @Basic @Column(name = "noOfLike") public Integer getNoOfLike() { return noOfLike; } public void setNoOfLike(Integer noOfLike) { this.noOfLike = noOfLike; } @Basic @Column(name = "status") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Column(name = "createdDate") @Temporal(TemporalType.TIMESTAMP) public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; News news = (News) o; if (id != news.id) return false; if (title != null ? !title.equals(news.title) : news.title != null) return false; if (shortDescription != null ? !shortDescription.equals(news.shortDescription) : news.shortDescription != null) return false; if (link != null ? !link.equals(news.link) : news.link != null) return false; if (noOfLike != null ? !noOfLike.equals(news.noOfLike) : news.noOfLike != null) return false; if (status != null ? !status.equals(news.status) : news.status != null) return false; return true; } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (shortDescription != null ? shortDescription.hashCode() : 0); result = 31 * result + (link != null ? link.hashCode() : 0); result = 31 * result + (noOfLike != null ? noOfLike.hashCode() : 0); result = 31 * result + (status != null ? status.hashCode() : 0); return result; } }
24.916667
119
0.606466
6c47b5d480a55eac4f313a3e3331a781eccbc827
2,669
/* * Copyright 2020 ART-Framework Contributors (https://github.com/Silthus/art-framework) * * 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.artframework; import io.artframework.conf.ContextConfig; /** * The {@link Factory} is used to create new instances of {@link ArtObject}s which * are wrapped inside an {@link ArtObjectContext}. * The created context and art object is initialized with its configuration and properties. * <p> * Every {@link ArtObject} must have exactly one {@link ArtObjectContext} and an {@link Factory} * that knows how to create the context, a new instance of the art object and how to load the configuration * of the art object. * * @param <TContext> the type of the context that is created for the art object by the factory * @param <TArtObject> the art object type that is created by the factory, e.g. {@link Action} */ public interface Factory<TContext extends ArtObjectContext<TArtObject>, TArtObject extends ArtObject> extends Scoped { /** * @return the meta information of the art object created by this factory */ ArtObjectMeta<TArtObject> meta(); /** * Creates a new ArtObject instance provided by this factory with the given configuration. * <p>The created object will have its field injected that are defined in the provided {@link ConfigMap}. * <p>The object will be created automtically by the {@link ArtObjectContext} that is created * with the {@link #createContext(ContextConfig)} method. * * @param configMap the config map that holds the config information of the object * @return a new art object instance for the type of this factory */ TArtObject create(ConfigMap configMap); /** * Creates a new ArtObjectContext that controls the execution flow of the ArtObject. * <p>The context will dynamically create new instances of the {@link ArtObject} using {@link #create(ConfigMap)}. * * @param config the configuration maps of the context * @return a new instance of the art object context defined as the context type of this factory */ TContext createContext(ContextConfig config); }
44.483333
118
0.730611
edfcd651c996abd480ee0ed6b07c7b53fdf23581
11,784
package org.apache.bookkeeper.bookie; /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ import java.io.File; import java.io.FileOutputStream; import java.nio.channels.FileChannel; import java.util.Enumeration; import org.apache.bookkeeper.bookie.CheckpointSource.Checkpoint; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.LedgerEntry; import org.apache.bookkeeper.client.LedgerHandle; import org.apache.bookkeeper.client.BookKeeper.DigestType; import org.apache.bookkeeper.proto.BookieServer; import org.apache.bookkeeper.test.BookKeeperClusterTestCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.junit.Assert; import org.junit.Test; import static com.google.common.base.Charsets.UTF_8; /** * This class tests that index corruption cases */ public class IndexCorruptionTest extends BookKeeperClusterTestCase { static Logger LOG = LoggerFactory.getLogger(IndexCorruptionTest.class); DigestType digestType; int pageSize = 1024; public IndexCorruptionTest() { super(1); this.digestType = DigestType.CRC32; baseConf.setPageSize(pageSize); } @Test(timeout=60000) public void testNoSuchLedger() throws Exception { LOG.debug("Testing NoSuchLedger"); SyncThread syncThread = bs.get(0).getBookie().syncThread; syncThread.suspendSync(); // Create a ledger LedgerHandle lh = bkc.createLedger(1, 1, digestType, "".getBytes()); // Close the ledger which cause a readEntry(0) call LedgerHandle newLh = bkc.openLedger(lh.getId(), digestType, "".getBytes()); // Create a new ledger to write entries String dummyMsg = "NoSuchLedger"; int numMsgs = 3; LedgerHandle wlh = bkc.createLedger(1, 1, digestType, "".getBytes()); for (int i=0; i<numMsgs; i++) { wlh.addEntry(dummyMsg.getBytes()); } syncThread.resumeSync(); // trigger sync syncThread.requestFlush().get(); // restart bookies restartBookies(); Enumeration<LedgerEntry> seq = wlh.readEntries(0, numMsgs - 1); assertTrue("Enumeration of ledger entries has no element", seq.hasMoreElements() == true); int entryId = 0; while (seq.hasMoreElements()) { LedgerEntry e = seq.nextElement(); assertEquals(entryId, e.getEntryId()); Assert.assertArrayEquals(dummyMsg.getBytes(), e.getEntry()); ++entryId; } assertEquals(entryId, numMsgs); } @Test(timeout = 60000) public void testEmptyIndexPage() throws Exception { LOG.debug("Testing EmptyIndexPage"); SyncThread syncThread = bs.get(0).getBookie().syncThread; assertNotNull("Not found SyncThread.", syncThread); syncThread.suspendSync(); // Create a ledger LedgerHandle lh1 = bkc.createLedger(1, 1, digestType, "".getBytes()); String dummyMsg = "NoSuchLedger"; // write two page entries to ledger 2 int numMsgs = 2 * pageSize / 8; LedgerHandle lh2 = bkc.createLedger(1, 1, digestType, "".getBytes()); for (int i=0; i<numMsgs; i++) { lh2.addEntry(dummyMsg.getBytes()); } syncThread.resumeSync(); // trigger sync syncThread.requestFlush().get(); syncThread.suspendSync(); // Close ledger 1 which cause a readEntry(0) call LedgerHandle newLh1 = bkc.openLedger(lh1.getId(), digestType, "".getBytes()); // write another 3 entries to ledger 2 for (int i=0; i<3; i++) { lh2.addEntry(dummyMsg.getBytes()); } syncThread.resumeSync(); // wait for sync again syncThread.requestFlush().get(); // restart bookies restartBookies(); numMsgs += 3; Enumeration<LedgerEntry> seq = lh2.readEntries(0, numMsgs - 1); assertTrue("Enumeration of ledger entries has no element", seq.hasMoreElements() == true); int entryId = 0; while (seq.hasMoreElements()) { LedgerEntry e = seq.nextElement(); assertEquals(entryId, e.getEntryId()); Assert.assertArrayEquals(dummyMsg.getBytes(), e.getEntry()); ++entryId; } assertEquals(entryId, numMsgs); } @Test(timeout = 60000) public void testPartialFlushedIndexPageAlignedWithIndexEntrySize() throws Exception { testPartialFlushedIndexPage(pageSize / 2); } @Test(timeout = 60000) public void testPartialFlushedIndexPageWithPartialIndexEntry() throws Exception { testPartialFlushedIndexPage(pageSize / 2 - 3); } void testPartialFlushedIndexPage(int sizeToTruncate) throws Exception { SyncThread syncThread = bs.get(0).getBookie().getSyncThread(); assertNotNull("Not found SyncThread.", syncThread); // suspend sync thread syncThread.suspendSync(); // Create a ledger and write entries LedgerHandle lh = bkc.createLedger(1, 1, digestType, "".getBytes()); String dummyMsg = "PartialFlushedIndexPage"; // write two page entries to ledger int numMsgs = 2 * pageSize / 8; for (int i = 0; i < numMsgs; i++) { lh.addEntry(dummyMsg.getBytes(UTF_8)); } // simulate partial flushed index page during shutdown // 0. flush the ledger storage Bookie bookie = bs.get(0).getBookie(); bookie.ledgerStorage.flush(); // 1. truncate the ledger index file to simulate partial flushed index page LedgerCacheImpl ledgerCache = (LedgerCacheImpl) ((InterleavedLedgerStorage) bookie.ledgerStorage).ledgerCache; File lf = ledgerCache.indexPersistenceManager.findIndexFile(lh.getId()); FileChannel fc = new FileOutputStream(lf, true).getChannel(); fc.truncate(fc.size() - sizeToTruncate); fc.close(); syncThread.disableCheckpoint(); syncThread.resumeSync(); // restart bookies // 1. bookies should restart successfully without hitting ShortReadException // 2. since SyncThread was suspended, bookie would still replay journals. so all entries should not be lost. restartBookies(); // Open the ledger LedgerHandle readLh = bkc.openLedger(lh.getId(), digestType, "".getBytes()); Enumeration<LedgerEntry> seq = readLh.readEntries(0, numMsgs - 1); assertTrue("Enumeration of ledger entries has no element", seq.hasMoreElements()); int entryId = 0; while (seq.hasMoreElements()) { LedgerEntry e = seq.nextElement(); assertEquals(entryId, e.getEntryId()); Assert.assertArrayEquals(dummyMsg.getBytes(), e.getEntry()); ++entryId; } assertEquals(entryId, numMsgs); } @Test(timeout = 60000) public void testMissingEntriesWithoutPartialIndexEntry() throws Exception { long availableStartEntryId = 0L; long availableEndEntryId = (pageSize + pageSize / 2) / 8 - 1; long missingStartEntryId = availableEndEntryId + 1; long missingEndEntryId = (2 * pageSize) / 8 - 1; testPartialIndexPage(false, pageSize / 2, availableStartEntryId, availableEndEntryId, missingStartEntryId, missingEndEntryId); } @Test(timeout = 60000) public void testMissingEntriesWithPartialIndexEntry() throws Exception { long availableStartEntryId = 0L; long availableEndEntryId = (pageSize + pageSize / 2 - 3) / 8 - 1; long missingStartEntryId = availableEndEntryId + 1; long missingEndEntryId = (2 * pageSize) / 8 - 1; testPartialIndexPage(false, pageSize / 2 + 3, availableStartEntryId, availableEndEntryId, missingStartEntryId, missingEndEntryId); } @Test(timeout = 60000) public void testNoPartialIndexEntry() throws Exception { long availableStartEntryId = 0L; long availableEndEntryId = (pageSize + pageSize / 2) / 8 - 1; testPartialIndexPage(true, pageSize / 2, availableStartEntryId, availableEndEntryId, 0, -1); } @Test(timeout = 60000) public void testPartialIndexEntry() throws Exception { long availableStartEntryId = 0L; long availableEndEntryId = (pageSize + pageSize / 2 - 3) / 8 - 1; testPartialIndexPage(true, pageSize / 2 + 3, availableStartEntryId, availableEndEntryId, 0, -1); } void testPartialIndexPage(boolean startNewBookie, int sizeToTruncate, long availableStartEntryId, long avaialbleEndEntryId, long missingStartEntryId, long missingEndEntryId) throws Exception { int ensembleSize = 1; if (startNewBookie) { int newBookiePort = this.startNewBookie(); LOG.info("Started new bookie @ port {}", newBookiePort); ++ensembleSize; } // Create a ledger and write entries LedgerHandle lh = bkc.createLedger(ensembleSize, ensembleSize, digestType, "".getBytes()); String dummyMsg = "PartialIndexPage"; int numMsgs = 2 * pageSize / 8; for (int i = 0; i < numMsgs; i++) { lh.addEntry(dummyMsg.getBytes(UTF_8)); } for (BookieServer bookieServer : bs) { bookieServer.getBookie().getSyncThread().requestFlush().get(); } lh.close(); // cause partial index page Bookie bookie = bs.get(0).getBookie(); LedgerCacheImpl ledgerCache = (LedgerCacheImpl) ((InterleavedLedgerStorage) bookie.ledgerStorage).ledgerCache; File lf = ledgerCache.indexPersistenceManager.findIndexFile(lh.getId()); FileChannel fc = new FileOutputStream(lf, true).getChannel(); fc.truncate(fc.size() - sizeToTruncate); fc.close(); // restart bookies restartBookies(); // Open the ledger LedgerHandle readLh = bkc.openLedger(lh.getId(), digestType, "".getBytes()); Enumeration<LedgerEntry> seq = readLh.readEntries(availableStartEntryId, avaialbleEndEntryId); assertTrue("Enumeration of ledger entries has no element", seq.hasMoreElements()); long entryId = availableStartEntryId; while (seq.hasMoreElements()) { LedgerEntry e = seq.nextElement(); assertEquals(entryId, e.getEntryId()); Assert.assertArrayEquals(dummyMsg.getBytes(), e.getEntry()); ++entryId; } assertEquals(entryId, avaialbleEndEntryId + 1); // missing entries for (entryId = missingStartEntryId; entryId <= missingEndEntryId; ++entryId) { try { readLh.readEntries(entryId, entryId); fail("Should fail on reading missing entry " + entryId); } catch (BKException.BKNoSuchEntryException bnsee) { // expected } } } }
37.291139
118
0.646979
572229d96ec3e54cfd285d98a1cd36cd7f59399c
273
package com.sh.vhr.mapper; import com.sh.vhr.model.Role; import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper public interface RoleMapper{ List<Role> getAllRoles(); Integer addRole(Role role); Integer deleteRoleById(Integer roleId); }
19.5
44
0.754579
0e473c9f9867e7c9b1f9189da228c9dc527f88d7
116,120
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.app; import com.android.internal.policy.PolicyManager; import com.android.internal.util.XmlUtils; import com.google.android.collect.Maps; import org.xmlpull.v1.XmlPullParserException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.ContextWrapper; import android.content.IContentProvider; import android.content.Intent; import android.content.IntentFilter; import android.content.IIntentReceiver; import android.content.IntentSender; import android.content.ReceiverCallNotAllowedException; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.ComponentInfo; import android.content.pm.FeatureInfo; import android.content.pm.IPackageDataObserver; import android.content.pm.IPackageDeleteObserver; import android.content.pm.IPackageInstallObserver; import android.content.pm.IPackageMoveObserver; import android.content.pm.IPackageManager; import android.content.pm.IPackageStatsObserver; import android.content.pm.InstrumentationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PermissionGroupInfo; import android.content.pm.PermissionInfo; import android.content.pm.ProviderInfo; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.content.res.AssetManager; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.hardware.SensorManager; import android.hardware.usb.IUsbManager; import android.hardware.usb.UsbManager; import android.location.ILocationManager; import android.location.LocationManager; import android.media.AudioManager; import android.net.ConnectivityManager; import android.net.IConnectivityManager; import android.net.ThrottleManager; import android.net.IThrottleManager; import android.net.Uri; import android.net.wifi.IWifiManager; import android.net.wifi.WifiManager; import android.nfc.NfcManager; import android.os.Binder; import android.os.Bundle; import android.os.DropBoxManager; import android.os.Environment; import android.os.FileUtils; import android.os.Handler; import android.os.IBinder; import android.os.IPowerManager; import android.os.Looper; import android.os.PowerManager; import android.os.Process; import android.os.RemoteException; import android.os.ServiceManager; import android.os.Vibrator; import android.os.FileUtils.FileStatus; import android.os.storage.StorageManager; import android.telephony.TelephonyManager; import android.text.ClipboardManager; import android.util.AndroidRuntimeException; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.WindowManagerImpl; import android.view.accessibility.AccessibilityManager; import android.view.inputmethod.InputMethodManager; import android.accounts.AccountManager; import android.accounts.IAccountManager; import android.app.admin.DevicePolicyManager; import com.android.internal.os.IDropBoxManagerService; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; class ReceiverRestrictedContext extends ContextWrapper { ReceiverRestrictedContext(Context base) { super(base); } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { return registerReceiver(receiver, filter, null, null); } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { throw new ReceiverCallNotAllowedException( "IntentReceiver components are not allowed to register to receive intents"); //ex.fillInStackTrace(); //Log.e("IntentReceiver", ex.getMessage(), ex); //return mContext.registerReceiver(receiver, filter, broadcastPermission, // scheduler); } @Override public boolean bindService(Intent service, ServiceConnection conn, int flags) { throw new ReceiverCallNotAllowedException( "IntentReceiver components are not allowed to bind to services"); //ex.fillInStackTrace(); //Log.e("IntentReceiver", ex.getMessage(), ex); //return mContext.bindService(service, interfaceName, conn, flags); } } /** * Common implementation of Context API, which provides the base * context object for Activity and other application components. */ class ContextImpl extends Context { private final static String TAG = "ApplicationContext"; private final static boolean DEBUG = false; private final static boolean DEBUG_ICONS = false; private static final Object sSync = new Object(); private static AlarmManager sAlarmManager; private static PowerManager sPowerManager; private static ConnectivityManager sConnectivityManager; private static ThrottleManager sThrottleManager; private static WifiManager sWifiManager; private static LocationManager sLocationManager; private static final HashMap<String, SharedPreferencesImpl> sSharedPrefs = new HashMap<String, SharedPreferencesImpl>(); private AudioManager mAudioManager; /*package*/ LoadedApk mPackageInfo; private Resources mResources; /*package*/ ActivityThread mMainThread; private Context mOuterContext; private IBinder mActivityToken = null; private ApplicationContentResolver mContentResolver; private int mThemeResource = 0; private Resources.Theme mTheme = null; private PackageManager mPackageManager; private NotificationManager mNotificationManager = null; private ActivityManager mActivityManager = null; private WallpaperManager mWallpaperManager = null; private Context mReceiverRestrictedContext = null; private SearchManager mSearchManager = null; private SensorManager mSensorManager = null; private StorageManager mStorageManager = null; private UsbManager mUsbManager = null; private Vibrator mVibrator = null; private LayoutInflater mLayoutInflater = null; private StatusBarManager mStatusBarManager = null; private TelephonyManager mTelephonyManager = null; private ClipboardManager mClipboardManager = null; private boolean mRestricted; private AccountManager mAccountManager; // protected by mSync private DropBoxManager mDropBoxManager = null; private DevicePolicyManager mDevicePolicyManager = null; private UiModeManager mUiModeManager = null; private DownloadManager mDownloadManager = null; private NfcManager mNfcManager = null; private final Object mSync = new Object(); private File mDatabasesDir; private File mPreferencesDir; private File mFilesDir; private File mCacheDir; private File mExternalFilesDir; private File mExternalCacheDir; private static long sInstanceCount = 0; private static final String[] EMPTY_FILE_LIST = {}; // For debug only /* @Override protected void finalize() throws Throwable { super.finalize(); --sInstanceCount; } */ public static long getInstanceCount() { return sInstanceCount; } @Override public AssetManager getAssets() { return mResources.getAssets(); } @Override public Resources getResources() { return mResources; } @Override public PackageManager getPackageManager() { if (mPackageManager != null) { return mPackageManager; } IPackageManager pm = ActivityThread.getPackageManager(); if (pm != null) { // Doesn't matter if we make more than one instance. return (mPackageManager = new ApplicationPackageManager(this, pm)); } return null; } @Override public ContentResolver getContentResolver() { return mContentResolver; } @Override public Looper getMainLooper() { return mMainThread.getLooper(); } @Override public Context getApplicationContext() { return (mPackageInfo != null) ? mPackageInfo.getApplication() : mMainThread.getApplication(); } @Override public void setTheme(int resid) { mThemeResource = resid; } @Override public Resources.Theme getTheme() { if (mTheme == null) { if (mThemeResource == 0) { mThemeResource = com.android.internal.R.style.Theme; } mTheme = mResources.newTheme(); mTheme.applyStyle(mThemeResource, true); } return mTheme; } @Override public ClassLoader getClassLoader() { return mPackageInfo != null ? mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader(); } @Override public String getPackageName() { if (mPackageInfo != null) { return mPackageInfo.getPackageName(); } throw new RuntimeException("Not supported in system context"); } @Override public ApplicationInfo getApplicationInfo() { if (mPackageInfo != null) { return mPackageInfo.getApplicationInfo(); } throw new RuntimeException("Not supported in system context"); } @Override public String getPackageResourcePath() { if (mPackageInfo != null) { return mPackageInfo.getResDir(); } throw new RuntimeException("Not supported in system context"); } @Override public String getPackageCodePath() { if (mPackageInfo != null) { return mPackageInfo.getAppDir(); } throw new RuntimeException("Not supported in system context"); } private static File makeBackupFile(File prefsFile) { return new File(prefsFile.getPath() + ".bak"); } public File getSharedPrefsFile(String name) { return makeFilename(getPreferencesDir(), name + ".xml"); } @Override public SharedPreferences getSharedPreferences(String name, int mode) { SharedPreferencesImpl sp; File prefsFile; boolean needInitialLoad = false; synchronized (sSharedPrefs) { sp = sSharedPrefs.get(name); if (sp != null && !sp.hasFileChangedUnexpectedly()) { return sp; } prefsFile = getSharedPrefsFile(name); if (sp == null) { sp = new SharedPreferencesImpl(prefsFile, mode, null); sSharedPrefs.put(name, sp); needInitialLoad = true; } } synchronized (sp) { if (needInitialLoad && sp.isLoaded()) { // lost the race to load; another thread handled it return sp; } File backup = makeBackupFile(prefsFile); if (backup.exists()) { prefsFile.delete(); backup.renameTo(prefsFile); } // Debugging if (prefsFile.exists() && !prefsFile.canRead()) { Log.w(TAG, "Attempt to read preferences file " + prefsFile + " without permission"); } Map map = null; FileStatus stat = new FileStatus(); if (FileUtils.getFileStatus(prefsFile.getPath(), stat) && prefsFile.canRead()) { try { FileInputStream str = new FileInputStream(prefsFile); map = XmlUtils.readMapXml(str); str.close(); } catch (org.xmlpull.v1.XmlPullParserException e) { Log.w(TAG, "getSharedPreferences", e); } catch (FileNotFoundException e) { Log.w(TAG, "getSharedPreferences", e); } catch (IOException e) { Log.w(TAG, "getSharedPreferences", e); } } sp.replace(map, stat); } return sp; } private File getPreferencesDir() { synchronized (mSync) { if (mPreferencesDir == null) { mPreferencesDir = new File(getDataDirFile(), "shared_prefs"); } return mPreferencesDir; } } @Override public FileInputStream openFileInput(String name) throws FileNotFoundException { File f = makeFilename(getFilesDir(), name); return new FileInputStream(f); } @Override public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException { final boolean append = (mode&MODE_APPEND) != 0; File f = makeFilename(getFilesDir(), name); try { FileOutputStream fos = new FileOutputStream(f, append); setFilePermissionsFromMode(f.getPath(), mode, 0); return fos; } catch (FileNotFoundException e) { } File parent = f.getParentFile(); parent.mkdir(); FileUtils.setPermissions( parent.getPath(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, -1, -1); FileOutputStream fos = new FileOutputStream(f, append); setFilePermissionsFromMode(f.getPath(), mode, 0); return fos; } @Override public boolean deleteFile(String name) { File f = makeFilename(getFilesDir(), name); return f.delete(); } @Override public File getFilesDir() { synchronized (mSync) { if (mFilesDir == null) { mFilesDir = new File(getDataDirFile(), "files"); } if (!mFilesDir.exists()) { if(!mFilesDir.mkdirs()) { Log.w(TAG, "Unable to create files directory " + mFilesDir.getPath()); return null; } FileUtils.setPermissions( mFilesDir.getPath(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, -1, -1); } return mFilesDir; } } @Override public File getExternalFilesDir(String type) { synchronized (mSync) { if (mExternalFilesDir == null) { mExternalFilesDir = Environment.getExternalStorageAppFilesDirectory( getPackageName()); } if (!mExternalFilesDir.exists()) { try { (new File(Environment.getExternalStorageAndroidDataDir(), ".nomedia")).createNewFile(); } catch (IOException e) { } if (!mExternalFilesDir.mkdirs()) { Log.w(TAG, "Unable to create external files directory"); return null; } } if (type == null) { return mExternalFilesDir; } File dir = new File(mExternalFilesDir, type); if (!dir.exists()) { if (!dir.mkdirs()) { Log.w(TAG, "Unable to create external media directory " + dir); return null; } } return dir; } } @Override public File getCacheDir() { synchronized (mSync) { if (mCacheDir == null) { mCacheDir = new File(getDataDirFile(), "cache"); } if (!mCacheDir.exists()) { if(!mCacheDir.mkdirs()) { Log.w(TAG, "Unable to create cache directory"); return null; } FileUtils.setPermissions( mCacheDir.getPath(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, -1, -1); } } return mCacheDir; } @Override public File getExternalCacheDir() { synchronized (mSync) { if (mExternalCacheDir == null) { mExternalCacheDir = Environment.getExternalStorageAppCacheDirectory( getPackageName()); } if (!mExternalCacheDir.exists()) { try { (new File(Environment.getExternalStorageAndroidDataDir(), ".nomedia")).createNewFile(); } catch (IOException e) { } if (!mExternalCacheDir.mkdirs()) { Log.w(TAG, "Unable to create external cache directory"); return null; } } return mExternalCacheDir; } } @Override public File getFileStreamPath(String name) { return makeFilename(getFilesDir(), name); } @Override public String[] fileList() { final String[] list = getFilesDir().list(); return (list != null) ? list : EMPTY_FILE_LIST; } @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { File f = validateFilePath(name, true); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(f, factory); setFilePermissionsFromMode(f.getPath(), mode, 0); return db; } @Override public boolean deleteDatabase(String name) { try { File f = validateFilePath(name, false); return f.delete(); } catch (Exception e) { } return false; } @Override public File getDatabasePath(String name) { return validateFilePath(name, false); } @Override public String[] databaseList() { final String[] list = getDatabasesDir().list(); return (list != null) ? list : EMPTY_FILE_LIST; } private File getDatabasesDir() { synchronized (mSync) { if (mDatabasesDir == null) { mDatabasesDir = new File(getDataDirFile(), "databases"); } if (mDatabasesDir.getPath().equals("databases")) { mDatabasesDir = new File("/data/system"); } return mDatabasesDir; } } @Override public Drawable getWallpaper() { return getWallpaperManager().getDrawable(); } @Override public Drawable peekWallpaper() { return getWallpaperManager().peekDrawable(); } @Override public int getWallpaperDesiredMinimumWidth() { return getWallpaperManager().getDesiredMinimumWidth(); } @Override public int getWallpaperDesiredMinimumHeight() { return getWallpaperManager().getDesiredMinimumHeight(); } @Override public void setWallpaper(Bitmap bitmap) throws IOException { getWallpaperManager().setBitmap(bitmap); } @Override public void setWallpaper(InputStream data) throws IOException { getWallpaperManager().setStream(data); } @Override public void clearWallpaper() throws IOException { getWallpaperManager().clear(); } @Override public void startActivity(Intent intent) { if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { throw new AndroidRuntimeException( "Calling startActivity() from outside of an Activity " + " context requires the FLAG_ACTIVITY_NEW_TASK flag." + " Is this really what you want?"); } mMainThread.getInstrumentation().execStartActivity( getOuterContext(), mMainThread.getApplicationThread(), null, null, intent, -1); } @Override public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException { try { String resolvedType = null; if (fillInIntent != null) { resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver()); } int result = ActivityManagerNative.getDefault() .startActivityIntentSender(mMainThread.getApplicationThread(), intent, fillInIntent, resolvedType, null, null, 0, flagsMask, flagsValues); if (result == IActivityManager.START_CANCELED) { throw new IntentSender.SendIntentException(); } Instrumentation.checkStartActivityResult(result, null); } catch (RemoteException e) { } } @Override public void sendBroadcast(Intent intent) { String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, null, Activity.RESULT_OK, null, null, null, false, false); } catch (RemoteException e) { } } @Override public void sendBroadcast(Intent intent, String receiverPermission) { String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, null, Activity.RESULT_OK, null, null, receiverPermission, false, false); } catch (RemoteException e) { } } @Override public void sendOrderedBroadcast(Intent intent, String receiverPermission) { String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, null, Activity.RESULT_OK, null, null, receiverPermission, true, false); } catch (RemoteException e) { } } @Override public void sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { IIntentReceiver rd = null; if (resultReceiver != null) { if (mPackageInfo != null) { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = mPackageInfo.getReceiverDispatcher( resultReceiver, getOuterContext(), scheduler, mMainThread.getInstrumentation(), false); } else { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = new LoadedApk.ReceiverDispatcher( resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); } } String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, rd, initialCode, initialData, initialExtras, receiverPermission, true, false); } catch (RemoteException e) { } } @Override public void sendStickyBroadcast(Intent intent) { String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, null, Activity.RESULT_OK, null, null, null, false, true); } catch (RemoteException e) { } } @Override public void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { IIntentReceiver rd = null; if (resultReceiver != null) { if (mPackageInfo != null) { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = mPackageInfo.getReceiverDispatcher( resultReceiver, getOuterContext(), scheduler, mMainThread.getInstrumentation(), false); } else { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = new LoadedApk.ReceiverDispatcher( resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); } } String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, rd, initialCode, initialData, initialExtras, null, true, true); } catch (RemoteException e) { } } @Override public void removeStickyBroadcast(Intent intent) { String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); if (resolvedType != null) { intent = new Intent(intent); intent.setDataAndType(intent.getData(), resolvedType); } try { ActivityManagerNative.getDefault().unbroadcastIntent( mMainThread.getApplicationThread(), intent); } catch (RemoteException e) { } } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { return registerReceiver(receiver, filter, null, null); } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { return registerReceiverInternal(receiver, filter, broadcastPermission, scheduler, getOuterContext()); } private Intent registerReceiverInternal(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, Context context) { IIntentReceiver rd = null; if (receiver != null) { if (mPackageInfo != null && context != null) { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = mPackageInfo.getReceiverDispatcher( receiver, context, scheduler, mMainThread.getInstrumentation(), true); } else { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = new LoadedApk.ReceiverDispatcher( receiver, context, scheduler, null, true).getIIntentReceiver(); } } try { return ActivityManagerNative.getDefault().registerReceiver( mMainThread.getApplicationThread(), rd, filter, broadcastPermission); } catch (RemoteException e) { return null; } } @Override public void unregisterReceiver(BroadcastReceiver receiver) { if (mPackageInfo != null) { IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher( getOuterContext(), receiver); try { ActivityManagerNative.getDefault().unregisterReceiver(rd); } catch (RemoteException e) { } } else { throw new RuntimeException("Not supported in system context"); } } @Override public ComponentName startService(Intent service) { try { ComponentName cn = ActivityManagerNative.getDefault().startService( mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(getContentResolver())); if (cn != null && cn.getPackageName().equals("!")) { throw new SecurityException( "Not allowed to start service " + service + " without permission " + cn.getClassName()); } return cn; } catch (RemoteException e) { return null; } } @Override public boolean stopService(Intent service) { try { int res = ActivityManagerNative.getDefault().stopService( mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(getContentResolver())); if (res < 0) { throw new SecurityException( "Not allowed to stop service " + service); } return res != 0; } catch (RemoteException e) { return false; } } @Override public boolean bindService(Intent service, ServiceConnection conn, int flags) { IServiceConnection sd; if (mPackageInfo != null) { sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), mMainThread.getHandler(), flags); } else { throw new RuntimeException("Not supported in system context"); } try { int res = ActivityManagerNative.getDefault().bindService( mMainThread.getApplicationThread(), getActivityToken(), service, service.resolveTypeIfNeeded(getContentResolver()), sd, flags); if (res < 0) { throw new SecurityException( "Not allowed to bind to service " + service); } return res != 0; } catch (RemoteException e) { return false; } } @Override public void unbindService(ServiceConnection conn) { if (mPackageInfo != null) { IServiceConnection sd = mPackageInfo.forgetServiceDispatcher( getOuterContext(), conn); try { ActivityManagerNative.getDefault().unbindService(sd); } catch (RemoteException e) { } } else { throw new RuntimeException("Not supported in system context"); } } @Override public boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments) { try { return ActivityManagerNative.getDefault().startInstrumentation( className, profileFile, 0, arguments, null); } catch (RemoteException e) { // System has crashed, nothing we can do. } return false; } @Override public Object getSystemService(String name) { if (WINDOW_SERVICE.equals(name)) { return WindowManagerImpl.getDefault(); } else if (LAYOUT_INFLATER_SERVICE.equals(name)) { synchronized (mSync) { LayoutInflater inflater = mLayoutInflater; if (inflater != null) { return inflater; } mLayoutInflater = inflater = PolicyManager.makeNewLayoutInflater(getOuterContext()); return inflater; } } else if (ACTIVITY_SERVICE.equals(name)) { return getActivityManager(); } else if (INPUT_METHOD_SERVICE.equals(name)) { return InputMethodManager.getInstance(this); } else if (ALARM_SERVICE.equals(name)) { return getAlarmManager(); } else if (ACCOUNT_SERVICE.equals(name)) { return getAccountManager(); } else if (POWER_SERVICE.equals(name)) { return getPowerManager(); } else if (CONNECTIVITY_SERVICE.equals(name)) { return getConnectivityManager(); } else if (THROTTLE_SERVICE.equals(name)) { return getThrottleManager(); } else if (WIFI_SERVICE.equals(name)) { return getWifiManager(); } else if (NOTIFICATION_SERVICE.equals(name)) { return getNotificationManager(); } else if (KEYGUARD_SERVICE.equals(name)) { return new KeyguardManager(); } else if (ACCESSIBILITY_SERVICE.equals(name)) { return AccessibilityManager.getInstance(this); } else if (LOCATION_SERVICE.equals(name)) { return getLocationManager(); } else if (SEARCH_SERVICE.equals(name)) { return getSearchManager(); } else if (SENSOR_SERVICE.equals(name)) { return getSensorManager(); } else if (STORAGE_SERVICE.equals(name)) { return getStorageManager(); } else if (USB_SERVICE.equals(name)) { return getUsbManager(); } else if (VIBRATOR_SERVICE.equals(name)) { return getVibrator(); } else if (STATUS_BAR_SERVICE.equals(name)) { synchronized (mSync) { if (mStatusBarManager == null) { mStatusBarManager = new StatusBarManager(getOuterContext()); } return mStatusBarManager; } } else if (AUDIO_SERVICE.equals(name)) { return getAudioManager(); } else if (TELEPHONY_SERVICE.equals(name)) { return getTelephonyManager(); } else if (CLIPBOARD_SERVICE.equals(name)) { return getClipboardManager(); } else if (WALLPAPER_SERVICE.equals(name)) { return getWallpaperManager(); } else if (DROPBOX_SERVICE.equals(name)) { return getDropBoxManager(); } else if (DEVICE_POLICY_SERVICE.equals(name)) { return getDevicePolicyManager(); } else if (UI_MODE_SERVICE.equals(name)) { return getUiModeManager(); } else if (DOWNLOAD_SERVICE.equals(name)) { return getDownloadManager(); } else if (NFC_SERVICE.equals(name)) { return getNfcManager(); } return null; } private AccountManager getAccountManager() { synchronized (mSync) { if (mAccountManager == null) { IBinder b = ServiceManager.getService(ACCOUNT_SERVICE); IAccountManager service = IAccountManager.Stub.asInterface(b); mAccountManager = new AccountManager(this, service); } return mAccountManager; } } private ActivityManager getActivityManager() { synchronized (mSync) { if (mActivityManager == null) { mActivityManager = new ActivityManager(getOuterContext(), mMainThread.getHandler()); } } return mActivityManager; } private AlarmManager getAlarmManager() { synchronized (sSync) { if (sAlarmManager == null) { IBinder b = ServiceManager.getService(ALARM_SERVICE); IAlarmManager service = IAlarmManager.Stub.asInterface(b); sAlarmManager = new AlarmManager(service); } } return sAlarmManager; } private PowerManager getPowerManager() { synchronized (sSync) { if (sPowerManager == null) { IBinder b = ServiceManager.getService(POWER_SERVICE); IPowerManager service = IPowerManager.Stub.asInterface(b); sPowerManager = new PowerManager(service, mMainThread.getHandler()); } } return sPowerManager; } private ConnectivityManager getConnectivityManager() { synchronized (sSync) { if (sConnectivityManager == null) { IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE); IConnectivityManager service = IConnectivityManager.Stub.asInterface(b); sConnectivityManager = new ConnectivityManager(service); } } return sConnectivityManager; } private ThrottleManager getThrottleManager() { synchronized (sSync) { if (sThrottleManager == null) { IBinder b = ServiceManager.getService(THROTTLE_SERVICE); IThrottleManager service = IThrottleManager.Stub.asInterface(b); sThrottleManager = new ThrottleManager(service); } } return sThrottleManager; } private WifiManager getWifiManager() { synchronized (sSync) { if (sWifiManager == null) { IBinder b = ServiceManager.getService(WIFI_SERVICE); IWifiManager service = IWifiManager.Stub.asInterface(b); sWifiManager = new WifiManager(service, mMainThread.getHandler()); } } return sWifiManager; } private NotificationManager getNotificationManager() { synchronized (mSync) { if (mNotificationManager == null) { mNotificationManager = new NotificationManager( new ContextThemeWrapper(getOuterContext(), com.android.internal.R.style.Theme_Dialog), mMainThread.getHandler()); } } return mNotificationManager; } private WallpaperManager getWallpaperManager() { synchronized (mSync) { if (mWallpaperManager == null) { mWallpaperManager = new WallpaperManager(getOuterContext(), mMainThread.getHandler()); } } return mWallpaperManager; } private TelephonyManager getTelephonyManager() { synchronized (mSync) { if (mTelephonyManager == null) { mTelephonyManager = new TelephonyManager(getOuterContext()); } } return mTelephonyManager; } private ClipboardManager getClipboardManager() { synchronized (mSync) { if (mClipboardManager == null) { mClipboardManager = new ClipboardManager(getOuterContext(), mMainThread.getHandler()); } } return mClipboardManager; } private LocationManager getLocationManager() { synchronized (sSync) { if (sLocationManager == null) { IBinder b = ServiceManager.getService(LOCATION_SERVICE); ILocationManager service = ILocationManager.Stub.asInterface(b); sLocationManager = new LocationManager(service); } } return sLocationManager; } private SearchManager getSearchManager() { synchronized (mSync) { if (mSearchManager == null) { mSearchManager = new SearchManager(getOuterContext(), mMainThread.getHandler()); } } return mSearchManager; } private SensorManager getSensorManager() { synchronized (mSync) { if (mSensorManager == null) { mSensorManager = new SensorManager(mMainThread.getHandler().getLooper()); } } return mSensorManager; } private StorageManager getStorageManager() { synchronized (mSync) { if (mStorageManager == null) { try { mStorageManager = new StorageManager(mMainThread.getHandler().getLooper()); } catch (RemoteException rex) { Log.e(TAG, "Failed to create StorageManager", rex); mStorageManager = null; } } } return mStorageManager; } private UsbManager getUsbManager() { synchronized (mSync) { if (mUsbManager == null) { IBinder b = ServiceManager.getService(USB_SERVICE); IUsbManager service = IUsbManager.Stub.asInterface(b); mUsbManager = new UsbManager(this, service); } } return mUsbManager; } private Vibrator getVibrator() { synchronized (mSync) { if (mVibrator == null) { mVibrator = new Vibrator(); } } return mVibrator; } private AudioManager getAudioManager() { if (mAudioManager == null) { mAudioManager = new AudioManager(this); } return mAudioManager; } /* package */ static DropBoxManager createDropBoxManager() { IBinder b = ServiceManager.getService(DROPBOX_SERVICE); IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b); return new DropBoxManager(service); } private DropBoxManager getDropBoxManager() { synchronized (mSync) { if (mDropBoxManager == null) { mDropBoxManager = createDropBoxManager(); } } return mDropBoxManager; } private DevicePolicyManager getDevicePolicyManager() { synchronized (mSync) { if (mDevicePolicyManager == null) { mDevicePolicyManager = DevicePolicyManager.create(this, mMainThread.getHandler()); } } return mDevicePolicyManager; } private UiModeManager getUiModeManager() { synchronized (mSync) { if (mUiModeManager == null) { mUiModeManager = new UiModeManager(); } } return mUiModeManager; } private DownloadManager getDownloadManager() { synchronized (mSync) { if (mDownloadManager == null) { mDownloadManager = new DownloadManager(getContentResolver(), getPackageName()); } } return mDownloadManager; } private NfcManager getNfcManager() { synchronized (mSync) { if (mNfcManager == null) { mNfcManager = new NfcManager(this); } } return mNfcManager; } @Override public int checkPermission(String permission, int pid, int uid) { if (permission == null) { throw new IllegalArgumentException("permission is null"); } if (!Process.supportsProcesses()) { return PackageManager.PERMISSION_GRANTED; } try { return ActivityManagerNative.getDefault().checkPermission( permission, pid, uid); } catch (RemoteException e) { return PackageManager.PERMISSION_DENIED; } } @Override public int checkCallingPermission(String permission) { if (permission == null) { throw new IllegalArgumentException("permission is null"); } if (!Process.supportsProcesses()) { return PackageManager.PERMISSION_GRANTED; } int pid = Binder.getCallingPid(); if (pid != Process.myPid()) { return checkPermission(permission, pid, Binder.getCallingUid()); } return PackageManager.PERMISSION_DENIED; } @Override public int checkCallingOrSelfPermission(String permission) { if (permission == null) { throw new IllegalArgumentException("permission is null"); } return checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid()); } private void enforce( String permission, int resultOfCheck, boolean selfToo, int uid, String message) { if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { throw new SecurityException( (message != null ? (message + ": ") : "") + (selfToo ? "Neither user " + uid + " nor current process has " : "User " + uid + " does not have ") + permission + "."); } } public void enforcePermission( String permission, int pid, int uid, String message) { enforce(permission, checkPermission(permission, pid, uid), false, uid, message); } public void enforceCallingPermission(String permission, String message) { enforce(permission, checkCallingPermission(permission), false, Binder.getCallingUid(), message); } public void enforceCallingOrSelfPermission( String permission, String message) { enforce(permission, checkCallingOrSelfPermission(permission), true, Binder.getCallingUid(), message); } @Override public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { try { ActivityManagerNative.getDefault().grantUriPermission( mMainThread.getApplicationThread(), toPackage, uri, modeFlags); } catch (RemoteException e) { } } @Override public void revokeUriPermission(Uri uri, int modeFlags) { try { ActivityManagerNative.getDefault().revokeUriPermission( mMainThread.getApplicationThread(), uri, modeFlags); } catch (RemoteException e) { } } @Override public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { if (!Process.supportsProcesses()) { return PackageManager.PERMISSION_GRANTED; } try { return ActivityManagerNative.getDefault().checkUriPermission( uri, pid, uid, modeFlags); } catch (RemoteException e) { return PackageManager.PERMISSION_DENIED; } } @Override public int checkCallingUriPermission(Uri uri, int modeFlags) { if (!Process.supportsProcesses()) { return PackageManager.PERMISSION_GRANTED; } int pid = Binder.getCallingPid(); if (pid != Process.myPid()) { return checkUriPermission(uri, pid, Binder.getCallingUid(), modeFlags); } return PackageManager.PERMISSION_DENIED; } @Override public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { return checkUriPermission(uri, Binder.getCallingPid(), Binder.getCallingUid(), modeFlags); } @Override public int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags) { if (DEBUG) { Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission=" + readPermission + " writePermission=" + writePermission + " pid=" + pid + " uid=" + uid + " mode" + modeFlags); } if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { if (readPermission == null || checkPermission(readPermission, pid, uid) == PackageManager.PERMISSION_GRANTED) { return PackageManager.PERMISSION_GRANTED; } } if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { if (writePermission == null || checkPermission(writePermission, pid, uid) == PackageManager.PERMISSION_GRANTED) { return PackageManager.PERMISSION_GRANTED; } } return uri != null ? checkUriPermission(uri, pid, uid, modeFlags) : PackageManager.PERMISSION_DENIED; } private String uriModeFlagToString(int uriModeFlags) { switch (uriModeFlags) { case Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION: return "read and write"; case Intent.FLAG_GRANT_READ_URI_PERMISSION: return "read"; case Intent.FLAG_GRANT_WRITE_URI_PERMISSION: return "write"; } throw new IllegalArgumentException( "Unknown permission mode flags: " + uriModeFlags); } private void enforceForUri( int modeFlags, int resultOfCheck, boolean selfToo, int uid, Uri uri, String message) { if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { throw new SecurityException( (message != null ? (message + ": ") : "") + (selfToo ? "Neither user " + uid + " nor current process has " : "User " + uid + " does not have ") + uriModeFlagToString(modeFlags) + " permission on " + uri + "."); } } public void enforceUriPermission( Uri uri, int pid, int uid, int modeFlags, String message) { enforceForUri( modeFlags, checkUriPermission(uri, pid, uid, modeFlags), false, uid, uri, message); } public void enforceCallingUriPermission( Uri uri, int modeFlags, String message) { enforceForUri( modeFlags, checkCallingUriPermission(uri, modeFlags), false, Binder.getCallingUid(), uri, message); } public void enforceCallingOrSelfUriPermission( Uri uri, int modeFlags, String message) { enforceForUri( modeFlags, checkCallingOrSelfUriPermission(uri, modeFlags), true, Binder.getCallingUid(), uri, message); } public void enforceUriPermission( Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message) { enforceForUri(modeFlags, checkUriPermission( uri, readPermission, writePermission, pid, uid, modeFlags), false, uid, uri, message); } @Override public Context createPackageContext(String packageName, int flags) throws PackageManager.NameNotFoundException { if (packageName.equals("system") || packageName.equals("android")) { return new ContextImpl(mMainThread.getSystemContext()); } LoadedApk pi = mMainThread.getPackageInfo(packageName, flags); if (pi != null) { ContextImpl c = new ContextImpl(); c.mRestricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED; c.init(pi, null, mMainThread, mResources); if (c.mResources != null) { return c; } } // Should be a better exception. throw new PackageManager.NameNotFoundException( "Application package " + packageName + " not found"); } @Override public boolean isRestricted() { return mRestricted; } private File getDataDirFile() { if (mPackageInfo != null) { return mPackageInfo.getDataDirFile(); } throw new RuntimeException("Not supported in system context"); } @Override public File getDir(String name, int mode) { name = "app_" + name; File file = makeFilename(getDataDirFile(), name); if (!file.exists()) { file.mkdir(); setFilePermissionsFromMode(file.getPath(), mode, FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH); } return file; } static ContextImpl createSystemContext(ActivityThread mainThread) { ContextImpl context = new ContextImpl(); context.init(Resources.getSystem(), mainThread); return context; } ContextImpl() { // For debug only //++sInstanceCount; mOuterContext = this; } /** * Create a new ApplicationContext from an existing one. The new one * works and operates the same as the one it is copying. * * @param context Existing application context. */ public ContextImpl(ContextImpl context) { ++sInstanceCount; mPackageInfo = context.mPackageInfo; mResources = context.mResources; mMainThread = context.mMainThread; mContentResolver = context.mContentResolver; mOuterContext = this; } final void init(LoadedApk packageInfo, IBinder activityToken, ActivityThread mainThread) { init(packageInfo, activityToken, mainThread, null); } final void init(LoadedApk packageInfo, IBinder activityToken, ActivityThread mainThread, Resources container) { mPackageInfo = packageInfo; mResources = mPackageInfo.getResources(mainThread); if (mResources != null && container != null && container.getCompatibilityInfo().applicationScale != mResources.getCompatibilityInfo().applicationScale) { if (DEBUG) { Log.d(TAG, "loaded context has different scaling. Using container's" + " compatiblity info:" + container.getDisplayMetrics()); } mResources = mainThread.getTopLevelResources( mPackageInfo.getResDir(), container.getCompatibilityInfo().copy()); } mMainThread = mainThread; mContentResolver = new ApplicationContentResolver(this, mainThread); setActivityToken(activityToken); } final void init(Resources resources, ActivityThread mainThread) { mPackageInfo = null; mResources = resources; mMainThread = mainThread; mContentResolver = new ApplicationContentResolver(this, mainThread); } final void scheduleFinalCleanup(String who, String what) { mMainThread.scheduleContextCleanup(this, who, what); } final void performFinalCleanup(String who, String what) { //Log.i(TAG, "Cleanup up context: " + this); mPackageInfo.removeContextRegistrations(getOuterContext(), who, what); } final Context getReceiverRestrictedContext() { if (mReceiverRestrictedContext != null) { return mReceiverRestrictedContext; } return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext()); } final void setActivityToken(IBinder token) { mActivityToken = token; } final void setOuterContext(Context context) { mOuterContext = context; } final Context getOuterContext() { return mOuterContext; } final IBinder getActivityToken() { return mActivityToken; } private static void setFilePermissionsFromMode(String name, int mode, int extraPermissions) { int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR |FileUtils.S_IRGRP|FileUtils.S_IWGRP |extraPermissions; if ((mode&MODE_WORLD_READABLE) != 0) { perms |= FileUtils.S_IROTH; } if ((mode&MODE_WORLD_WRITEABLE) != 0) { perms |= FileUtils.S_IWOTH; } if (DEBUG) { Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode) + ", perms=0x" + Integer.toHexString(perms)); } FileUtils.setPermissions(name, perms, -1, -1); } private File validateFilePath(String name, boolean createDirectory) { File dir; File f; if (name.charAt(0) == File.separatorChar) { String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar)); dir = new File(dirPath); name = name.substring(name.lastIndexOf(File.separatorChar)); f = new File(dir, name); } else { dir = getDatabasesDir(); f = makeFilename(dir, name); } if (createDirectory && !dir.isDirectory() && dir.mkdir()) { FileUtils.setPermissions(dir.getPath(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, -1, -1); } return f; } private File makeFilename(File base, String name) { if (name.indexOf(File.separatorChar) < 0) { return new File(base, name); } throw new IllegalArgumentException( "File " + name + " contains a path separator"); } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- private static final class ApplicationContentResolver extends ContentResolver { public ApplicationContentResolver(Context context, ActivityThread mainThread) { super(context); mMainThread = mainThread; } @Override protected IContentProvider acquireProvider(Context context, String name) { return mMainThread.acquireProvider(context, name); } @Override protected IContentProvider acquireExistingProvider(Context context, String name) { return mMainThread.acquireExistingProvider(context, name); } @Override public boolean releaseProvider(IContentProvider provider) { return mMainThread.releaseProvider(provider); } private final ActivityThread mMainThread; } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /*package*/ static final class ApplicationPackageManager extends PackageManager { @Override public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException { try { PackageInfo pi = mPM.getPackageInfo(packageName, flags); if (pi != null) { return pi; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(packageName); } @Override public String[] currentToCanonicalPackageNames(String[] names) { try { return mPM.currentToCanonicalPackageNames(names); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public String[] canonicalToCurrentPackageNames(String[] names) { try { return mPM.canonicalToCurrentPackageNames(names); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public Intent getLaunchIntentForPackage(String packageName) { // First see if the package has an INFO activity; the existence of // such an activity is implied to be the desired front-door for the // overall package (such as if it has multiple launcher entries). Intent intentToResolve = new Intent(Intent.ACTION_MAIN); intentToResolve.addCategory(Intent.CATEGORY_INFO); intentToResolve.setPackage(packageName); ResolveInfo resolveInfo = resolveActivity(intentToResolve, 0); // Otherwise, try to find a main launcher activity. if (resolveInfo == null) { // reuse the intent instance intentToResolve.removeCategory(Intent.CATEGORY_INFO); intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER); intentToResolve.setPackage(packageName); resolveInfo = resolveActivity(intentToResolve, 0); } if (resolveInfo == null) { return null; } Intent intent = new Intent(intentToResolve); intent.setClassName(resolveInfo.activityInfo.applicationInfo.packageName, resolveInfo.activityInfo.name); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } @Override public int[] getPackageGids(String packageName) throws NameNotFoundException { try { int[] gids = mPM.getPackageGids(packageName); if (gids == null || gids.length > 0) { return gids; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(packageName); } @Override public PermissionInfo getPermissionInfo(String name, int flags) throws NameNotFoundException { try { PermissionInfo pi = mPM.getPermissionInfo(name, flags); if (pi != null) { return pi; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(name); } @Override public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) throws NameNotFoundException { try { List<PermissionInfo> pi = mPM.queryPermissionsByGroup(group, flags); if (pi != null) { return pi; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(group); } @Override public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) throws NameNotFoundException { try { PermissionGroupInfo pgi = mPM.getPermissionGroupInfo(name, flags); if (pgi != null) { return pgi; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(name); } @Override public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { try { return mPM.getAllPermissionGroups(flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException { try { ApplicationInfo ai = mPM.getApplicationInfo(packageName, flags); if (ai != null) { return ai; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(packageName); } @Override public ActivityInfo getActivityInfo(ComponentName className, int flags) throws NameNotFoundException { try { ActivityInfo ai = mPM.getActivityInfo(className, flags); if (ai != null) { return ai; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(className.toString()); } @Override public ActivityInfo getReceiverInfo(ComponentName className, int flags) throws NameNotFoundException { try { ActivityInfo ai = mPM.getReceiverInfo(className, flags); if (ai != null) { return ai; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(className.toString()); } @Override public ServiceInfo getServiceInfo(ComponentName className, int flags) throws NameNotFoundException { try { ServiceInfo si = mPM.getServiceInfo(className, flags); if (si != null) { return si; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(className.toString()); } @Override public ProviderInfo getProviderInfo(ComponentName className, int flags) throws NameNotFoundException { try { ProviderInfo pi = mPM.getProviderInfo(className, flags); if (pi != null) { return pi; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(className.toString()); } @Override public String[] getSystemSharedLibraryNames() { try { return mPM.getSystemSharedLibraryNames(); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public FeatureInfo[] getSystemAvailableFeatures() { try { return mPM.getSystemAvailableFeatures(); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public boolean hasSystemFeature(String name) { try { return mPM.hasSystemFeature(name); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public int checkPermission(String permName, String pkgName) { try { return mPM.checkPermission(permName, pkgName); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public boolean addPermission(PermissionInfo info) { try { return mPM.addPermission(info); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public boolean addPermissionAsync(PermissionInfo info) { try { return mPM.addPermissionAsync(info); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public void removePermission(String name) { try { mPM.removePermission(name); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public int checkSignatures(String pkg1, String pkg2) { try { return mPM.checkSignatures(pkg1, pkg2); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public int checkSignatures(int uid1, int uid2) { try { return mPM.checkUidSignatures(uid1, uid2); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public String[] getPackagesForUid(int uid) { try { return mPM.getPackagesForUid(uid); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public String getNameForUid(int uid) { try { return mPM.getNameForUid(uid); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public int getUidForSharedUser(String sharedUserName) throws NameNotFoundException { try { int uid = mPM.getUidForSharedUser(sharedUserName); if(uid != -1) { return uid; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException("No shared userid for user:"+sharedUserName); } @Override public List<PackageInfo> getInstalledPackages(int flags) { try { return mPM.getInstalledPackages(flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List<ApplicationInfo> getInstalledApplications(int flags) { try { return mPM.getInstalledApplications(flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public ResolveInfo resolveActivity(Intent intent, int flags) { try { return mPM.resolveIntent( intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) { try { return mPM.queryIntentActivities( intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List<ResolveInfo> queryIntentActivityOptions( ComponentName caller, Intent[] specifics, Intent intent, int flags) { final ContentResolver resolver = mContext.getContentResolver(); String[] specificTypes = null; if (specifics != null) { final int N = specifics.length; for (int i=0; i<N; i++) { Intent sp = specifics[i]; if (sp != null) { String t = sp.resolveTypeIfNeeded(resolver); if (t != null) { if (specificTypes == null) { specificTypes = new String[N]; } specificTypes[i] = t; } } } } try { return mPM.queryIntentActivityOptions(caller, specifics, specificTypes, intent, intent.resolveTypeIfNeeded(resolver), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) { try { return mPM.queryIntentReceivers( intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public ResolveInfo resolveService(Intent intent, int flags) { try { return mPM.resolveService( intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List<ResolveInfo> queryIntentServices(Intent intent, int flags) { try { return mPM.queryIntentServices( intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public ProviderInfo resolveContentProvider(String name, int flags) { try { return mPM.resolveContentProvider(name, flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List<ProviderInfo> queryContentProviders(String processName, int uid, int flags) { try { return mPM.queryContentProviders(processName, uid, flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public InstrumentationInfo getInstrumentationInfo( ComponentName className, int flags) throws NameNotFoundException { try { InstrumentationInfo ii = mPM.getInstrumentationInfo( className, flags); if (ii != null) { return ii; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(className.toString()); } @Override public List<InstrumentationInfo> queryInstrumentation( String targetPackage, int flags) { try { return mPM.queryInstrumentation(targetPackage, flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public Drawable getDrawable(String packageName, int resid, ApplicationInfo appInfo) { ResourceName name = new ResourceName(packageName, resid); Drawable dr = getCachedIcon(name); if (dr != null) { return dr; } if (appInfo == null) { try { appInfo = getApplicationInfo(packageName, 0); } catch (NameNotFoundException e) { return null; } } try { Resources r = getResourcesForApplication(appInfo); dr = r.getDrawable(resid); if (false) { RuntimeException e = new RuntimeException("here"); e.fillInStackTrace(); Log.w(TAG, "Getting drawable 0x" + Integer.toHexString(resid) + " from package " + packageName + ": app scale=" + r.getCompatibilityInfo().applicationScale + ", caller scale=" + mContext.getResources().getCompatibilityInfo().applicationScale, e); } if (DEBUG_ICONS) Log.v(TAG, "Getting drawable 0x" + Integer.toHexString(resid) + " from " + r + ": " + dr); putCachedIcon(name, dr); return dr; } catch (NameNotFoundException e) { Log.w("PackageManager", "Failure retrieving resources for" + appInfo.packageName); } catch (RuntimeException e) { // If an exception was thrown, fall through to return // default icon. Log.w("PackageManager", "Failure retrieving icon 0x" + Integer.toHexString(resid) + " in package " + packageName, e); } return null; } @Override public Drawable getActivityIcon(ComponentName activityName) throws NameNotFoundException { return getActivityInfo(activityName, 0).loadIcon(this); } @Override public Drawable getActivityIcon(Intent intent) throws NameNotFoundException { if (intent.getComponent() != null) { return getActivityIcon(intent.getComponent()); } ResolveInfo info = resolveActivity( intent, PackageManager.MATCH_DEFAULT_ONLY); if (info != null) { return info.activityInfo.loadIcon(this); } throw new NameNotFoundException(intent.toURI()); } @Override public Drawable getDefaultActivityIcon() { return Resources.getSystem().getDrawable( com.android.internal.R.drawable.sym_def_app_icon); } @Override public Drawable getApplicationIcon(ApplicationInfo info) { return info.loadIcon(this); } @Override public Drawable getApplicationIcon(String packageName) throws NameNotFoundException { return getApplicationIcon(getApplicationInfo(packageName, 0)); } @Override public Drawable getActivityLogo(ComponentName activityName) throws NameNotFoundException { return getActivityInfo(activityName, 0).loadLogo(this); } @Override public Drawable getActivityLogo(Intent intent) throws NameNotFoundException { if (intent.getComponent() != null) { return getActivityLogo(intent.getComponent()); } ResolveInfo info = resolveActivity( intent, PackageManager.MATCH_DEFAULT_ONLY); if (info != null) { return info.activityInfo.loadLogo(this); } throw new NameNotFoundException(intent.toUri(0)); } @Override public Drawable getApplicationLogo(ApplicationInfo info) { return info.loadLogo(this); } @Override public Drawable getApplicationLogo(String packageName) throws NameNotFoundException { return getApplicationLogo(getApplicationInfo(packageName, 0)); } @Override public Resources getResourcesForActivity( ComponentName activityName) throws NameNotFoundException { return getResourcesForApplication( getActivityInfo(activityName, 0).applicationInfo); } @Override public Resources getResourcesForApplication( ApplicationInfo app) throws NameNotFoundException { if (app.packageName.equals("system")) { return mContext.mMainThread.getSystemContext().getResources(); } Resources r = mContext.mMainThread.getTopLevelResources( app.uid == Process.myUid() ? app.sourceDir : app.publicSourceDir, mContext.mPackageInfo); if (r != null) { return r; } throw new NameNotFoundException("Unable to open " + app.publicSourceDir); } @Override public Resources getResourcesForApplication( String appPackageName) throws NameNotFoundException { return getResourcesForApplication( getApplicationInfo(appPackageName, 0)); } int mCachedSafeMode = -1; @Override public boolean isSafeMode() { try { if (mCachedSafeMode < 0) { mCachedSafeMode = mPM.isSafeMode() ? 1 : 0; } return mCachedSafeMode != 0; } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } static void configurationChanged() { synchronized (sSync) { sIconCache.clear(); sStringCache.clear(); } } ApplicationPackageManager(ContextImpl context, IPackageManager pm) { mContext = context; mPM = pm; } private Drawable getCachedIcon(ResourceName name) { synchronized (sSync) { WeakReference<Drawable> wr = sIconCache.get(name); if (DEBUG_ICONS) Log.v(TAG, "Get cached weak drawable ref for " + name + ": " + wr); if (wr != null) { // we have the activity Drawable dr = wr.get(); if (dr != null) { if (DEBUG_ICONS) Log.v(TAG, "Get cached drawable for " + name + ": " + dr); return dr; } // our entry has been purged sIconCache.remove(name); } } return null; } private void putCachedIcon(ResourceName name, Drawable dr) { synchronized (sSync) { sIconCache.put(name, new WeakReference<Drawable>(dr)); if (DEBUG_ICONS) Log.v(TAG, "Added cached drawable for " + name + ": " + dr); } } static final void handlePackageBroadcast(int cmd, String[] pkgList, boolean hasPkgInfo) { boolean immediateGc = false; if (cmd == IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE) { immediateGc = true; } if (pkgList != null && (pkgList.length > 0)) { boolean needCleanup = false; for (String ssp : pkgList) { synchronized (sSync) { if (sIconCache.size() > 0) { Iterator<ResourceName> it = sIconCache.keySet().iterator(); while (it.hasNext()) { ResourceName nm = it.next(); if (nm.packageName.equals(ssp)) { //Log.i(TAG, "Removing cached drawable for " + nm); it.remove(); needCleanup = true; } } } if (sStringCache.size() > 0) { Iterator<ResourceName> it = sStringCache.keySet().iterator(); while (it.hasNext()) { ResourceName nm = it.next(); if (nm.packageName.equals(ssp)) { //Log.i(TAG, "Removing cached string for " + nm); it.remove(); needCleanup = true; } } } } } if (needCleanup || hasPkgInfo) { if (immediateGc) { // Schedule an immediate gc. Runtime.getRuntime().gc(); } else { ActivityThread.currentActivityThread().scheduleGcIdler(); } } } } private static final class ResourceName { final String packageName; final int iconId; ResourceName(String _packageName, int _iconId) { packageName = _packageName; iconId = _iconId; } ResourceName(ApplicationInfo aInfo, int _iconId) { this(aInfo.packageName, _iconId); } ResourceName(ComponentInfo cInfo, int _iconId) { this(cInfo.applicationInfo.packageName, _iconId); } ResourceName(ResolveInfo rInfo, int _iconId) { this(rInfo.activityInfo.applicationInfo.packageName, _iconId); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceName that = (ResourceName) o; if (iconId != that.iconId) return false; return !(packageName != null ? !packageName.equals(that.packageName) : that.packageName != null); } @Override public int hashCode() { int result; result = packageName.hashCode(); result = 31 * result + iconId; return result; } @Override public String toString() { return "{ResourceName " + packageName + " / " + iconId + "}"; } } private CharSequence getCachedString(ResourceName name) { synchronized (sSync) { WeakReference<CharSequence> wr = sStringCache.get(name); if (wr != null) { // we have the activity CharSequence cs = wr.get(); if (cs != null) { return cs; } // our entry has been purged sStringCache.remove(name); } } return null; } private void putCachedString(ResourceName name, CharSequence cs) { synchronized (sSync) { sStringCache.put(name, new WeakReference<CharSequence>(cs)); } } @Override public CharSequence getText(String packageName, int resid, ApplicationInfo appInfo) { ResourceName name = new ResourceName(packageName, resid); CharSequence text = getCachedString(name); if (text != null) { return text; } if (appInfo == null) { try { appInfo = getApplicationInfo(packageName, 0); } catch (NameNotFoundException e) { return null; } } try { Resources r = getResourcesForApplication(appInfo); text = r.getText(resid); putCachedString(name, text); return text; } catch (NameNotFoundException e) { Log.w("PackageManager", "Failure retrieving resources for" + appInfo.packageName); } catch (RuntimeException e) { // If an exception was thrown, fall through to return // default icon. Log.w("PackageManager", "Failure retrieving text 0x" + Integer.toHexString(resid) + " in package " + packageName, e); } return null; } @Override public XmlResourceParser getXml(String packageName, int resid, ApplicationInfo appInfo) { if (appInfo == null) { try { appInfo = getApplicationInfo(packageName, 0); } catch (NameNotFoundException e) { return null; } } try { Resources r = getResourcesForApplication(appInfo); return r.getXml(resid); } catch (RuntimeException e) { // If an exception was thrown, fall through to return // default icon. Log.w("PackageManager", "Failure retrieving xml 0x" + Integer.toHexString(resid) + " in package " + packageName, e); } catch (NameNotFoundException e) { Log.w("PackageManager", "Failure retrieving resources for" + appInfo.packageName); } return null; } @Override public CharSequence getApplicationLabel(ApplicationInfo info) { return info.loadLabel(this); } @Override public void installPackage(Uri packageURI, IPackageInstallObserver observer, int flags, String installerPackageName) { try { mPM.installPackage(packageURI, observer, flags, installerPackageName); } catch (RemoteException e) { // Should never happen! } } @Override public void movePackage(String packageName, IPackageMoveObserver observer, int flags) { try { mPM.movePackage(packageName, observer, flags); } catch (RemoteException e) { // Should never happen! } } @Override public String getInstallerPackageName(String packageName) { try { return mPM.getInstallerPackageName(packageName); } catch (RemoteException e) { // Should never happen! } return null; } @Override public void deletePackage(String packageName, IPackageDeleteObserver observer, int flags) { try { mPM.deletePackage(packageName, observer, flags); } catch (RemoteException e) { // Should never happen! } } @Override public void clearApplicationUserData(String packageName, IPackageDataObserver observer) { try { mPM.clearApplicationUserData(packageName, observer); } catch (RemoteException e) { // Should never happen! } } @Override public void deleteApplicationCacheFiles(String packageName, IPackageDataObserver observer) { try { mPM.deleteApplicationCacheFiles(packageName, observer); } catch (RemoteException e) { // Should never happen! } } @Override public void freeStorageAndNotify(long idealStorageSize, IPackageDataObserver observer) { try { mPM.freeStorageAndNotify(idealStorageSize, observer); } catch (RemoteException e) { // Should never happen! } } @Override public void freeStorage(long freeStorageSize, IntentSender pi) { try { mPM.freeStorage(freeStorageSize, pi); } catch (RemoteException e) { // Should never happen! } } @Override public void getPackageSizeInfo(String packageName, IPackageStatsObserver observer) { try { mPM.getPackageSizeInfo(packageName, observer); } catch (RemoteException e) { // Should never happen! } } @Override public void addPackageToPreferred(String packageName) { try { mPM.addPackageToPreferred(packageName); } catch (RemoteException e) { // Should never happen! } } @Override public void removePackageFromPreferred(String packageName) { try { mPM.removePackageFromPreferred(packageName); } catch (RemoteException e) { // Should never happen! } } @Override public List<PackageInfo> getPreferredPackages(int flags) { try { return mPM.getPreferredPackages(flags); } catch (RemoteException e) { // Should never happen! } return new ArrayList<PackageInfo>(); } @Override public void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) { try { mPM.addPreferredActivity(filter, match, set, activity); } catch (RemoteException e) { // Should never happen! } } @Override public void replacePreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) { try { mPM.replacePreferredActivity(filter, match, set, activity); } catch (RemoteException e) { // Should never happen! } } @Override public void clearPackagePreferredActivities(String packageName) { try { mPM.clearPackagePreferredActivities(packageName); } catch (RemoteException e) { // Should never happen! } } @Override public int getPreferredActivities(List<IntentFilter> outFilters, List<ComponentName> outActivities, String packageName) { try { return mPM.getPreferredActivities(outFilters, outActivities, packageName); } catch (RemoteException e) { // Should never happen! } return 0; } @Override public void setComponentEnabledSetting(ComponentName componentName, int newState, int flags) { try { mPM.setComponentEnabledSetting(componentName, newState, flags); } catch (RemoteException e) { // Should never happen! } } @Override public int getComponentEnabledSetting(ComponentName componentName) { try { return mPM.getComponentEnabledSetting(componentName); } catch (RemoteException e) { // Should never happen! } return PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; } @Override public void setApplicationEnabledSetting(String packageName, int newState, int flags) { try { mPM.setApplicationEnabledSetting(packageName, newState, flags); } catch (RemoteException e) { // Should never happen! } } @Override public int getApplicationEnabledSetting(String packageName) { try { return mPM.getApplicationEnabledSetting(packageName); } catch (RemoteException e) { // Should never happen! } return PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; } private final ContextImpl mContext; private final IPackageManager mPM; private static final Object sSync = new Object(); private static HashMap<ResourceName, WeakReference<Drawable> > sIconCache = new HashMap<ResourceName, WeakReference<Drawable> >(); private static HashMap<ResourceName, WeakReference<CharSequence> > sStringCache = new HashMap<ResourceName, WeakReference<CharSequence> >(); } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- private static final class SharedPreferencesImpl implements SharedPreferences { // Lock ordering rules: // - acquire SharedPreferencesImpl.this before EditorImpl.this // - acquire mWritingToDiskLock before EditorImpl.this private final File mFile; private final File mBackupFile; private final int mMode; private Map<String, Object> mMap; // guarded by 'this' private int mDiskWritesInFlight = 0; // guarded by 'this' private boolean mLoaded = false; // guarded by 'this' private long mStatTimestamp; // guarded by 'this' private long mStatSize; // guarded by 'this' private final Object mWritingToDiskLock = new Object(); private static final Object mContent = new Object(); private final WeakHashMap<OnSharedPreferenceChangeListener, Object> mListeners; SharedPreferencesImpl( File file, int mode, Map initialContents) { mFile = file; mBackupFile = makeBackupFile(file); mMode = mode; mLoaded = initialContents != null; mMap = initialContents != null ? initialContents : new HashMap<String, Object>(); FileStatus stat = new FileStatus(); if (FileUtils.getFileStatus(file.getPath(), stat)) { mStatTimestamp = stat.mtime; } mListeners = new WeakHashMap<OnSharedPreferenceChangeListener, Object>(); } // Has this SharedPreferences ever had values assigned to it? boolean isLoaded() { synchronized (this) { return mLoaded; } } // Has the file changed out from under us? i.e. writes that // we didn't instigate. public boolean hasFileChangedUnexpectedly() { synchronized (this) { if (mDiskWritesInFlight > 0) { // If we know we caused it, it's not unexpected. if (DEBUG) Log.d(TAG, "disk write in flight, not unexpected."); return false; } } FileStatus stat = new FileStatus(); if (!FileUtils.getFileStatus(mFile.getPath(), stat)) { return true; } synchronized (this) { return mStatTimestamp != stat.mtime || mStatSize != stat.size; } } /* package */ void replace(Map newContents, FileStatus stat) { synchronized (this) { mLoaded = true; if (newContents != null) { mMap = newContents; } if (stat != null) { mStatTimestamp = stat.mtime; mStatSize = stat.size; } } } public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { synchronized(this) { mListeners.put(listener, mContent); } } public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { synchronized(this) { mListeners.remove(listener); } } public Map<String, ?> getAll() { synchronized(this) { //noinspection unchecked return new HashMap<String, Object>(mMap); } } public String getString(String key, String defValue) { synchronized (this) { String v = (String)mMap.get(key); return v != null ? v : defValue; } } public int getInt(String key, int defValue) { synchronized (this) { Integer v = (Integer)mMap.get(key); return v != null ? v : defValue; } } public long getLong(String key, long defValue) { synchronized (this) { Long v = (Long)mMap.get(key); return v != null ? v : defValue; } } public float getFloat(String key, float defValue) { synchronized (this) { Float v = (Float)mMap.get(key); return v != null ? v : defValue; } } public boolean getBoolean(String key, boolean defValue) { synchronized (this) { Boolean v = (Boolean)mMap.get(key); return v != null ? v : defValue; } } public boolean contains(String key) { synchronized (this) { return mMap.containsKey(key); } } public Editor edit() { return new EditorImpl(); } // Return value from EditorImpl#commitToMemory() private static class MemoryCommitResult { public boolean changesMade; // any keys different? public List<String> keysModified; // may be null public Set<OnSharedPreferenceChangeListener> listeners; // may be null public Map<?, ?> mapToWriteToDisk; public final CountDownLatch writtenToDiskLatch = new CountDownLatch(1); public volatile boolean writeToDiskResult = false; public void setDiskWriteResult(boolean result) { writeToDiskResult = result; writtenToDiskLatch.countDown(); } } public final class EditorImpl implements Editor { private final Map<String, Object> mModified = Maps.newHashMap(); private boolean mClear = false; public Editor putString(String key, String value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor putInt(String key, int value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor putLong(String key, long value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor putFloat(String key, float value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor putBoolean(String key, boolean value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor remove(String key) { synchronized (this) { mModified.put(key, this); return this; } } public Editor clear() { synchronized (this) { mClear = true; return this; } } public void apply() { final MemoryCommitResult mcr = commitToMemory(); final Runnable awaitCommit = new Runnable() { public void run() { try { mcr.writtenToDiskLatch.await(); } catch (InterruptedException ignored) { } } }; QueuedWork.add(awaitCommit); Runnable postWriteRunnable = new Runnable() { public void run() { awaitCommit.run(); QueuedWork.remove(awaitCommit); } }; SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable); // Okay to notify the listeners before it's hit disk // because the listeners should always get the same // SharedPreferences instance back, which has the // changes reflected in memory. notifyListeners(mcr); } // Returns true if any changes were made private MemoryCommitResult commitToMemory() { MemoryCommitResult mcr = new MemoryCommitResult(); synchronized (SharedPreferencesImpl.this) { // We optimistically don't make a deep copy until // a memory commit comes in when we're already // writing to disk. if (mDiskWritesInFlight > 0) { // We can't modify our mMap as a currently // in-flight write owns it. Clone it before // modifying it. // noinspection unchecked mMap = new HashMap<String, Object>(mMap); } mcr.mapToWriteToDisk = mMap; mDiskWritesInFlight++; boolean hasListeners = mListeners.size() > 0; if (hasListeners) { mcr.keysModified = new ArrayList<String>(); mcr.listeners = new HashSet<OnSharedPreferenceChangeListener>(mListeners.keySet()); } synchronized (this) { if (mClear) { if (!mMap.isEmpty()) { mcr.changesMade = true; mMap.clear(); } mClear = false; } for (Entry<String, Object> e : mModified.entrySet()) { String k = e.getKey(); Object v = e.getValue(); if (v == this) { // magic value for a removal mutation if (!mMap.containsKey(k)) { continue; } mMap.remove(k); } else { boolean isSame = false; if (mMap.containsKey(k)) { Object existingValue = mMap.get(k); if (existingValue != null && existingValue.equals(v)) { continue; } } mMap.put(k, v); } mcr.changesMade = true; if (hasListeners) { mcr.keysModified.add(k); } } mModified.clear(); } } return mcr; } public boolean commit() { MemoryCommitResult mcr = commitToMemory(); SharedPreferencesImpl.this.enqueueDiskWrite( mcr, null /* sync write on this thread okay */); try { mcr.writtenToDiskLatch.await(); } catch (InterruptedException e) { return false; } notifyListeners(mcr); return mcr.writeToDiskResult; } private void notifyListeners(final MemoryCommitResult mcr) { if (mcr.listeners == null || mcr.keysModified == null || mcr.keysModified.size() == 0) { return; } if (Looper.myLooper() == Looper.getMainLooper()) { for (int i = mcr.keysModified.size() - 1; i >= 0; i--) { final String key = mcr.keysModified.get(i); for (OnSharedPreferenceChangeListener listener : mcr.listeners) { if (listener != null) { listener.onSharedPreferenceChanged(SharedPreferencesImpl.this, key); } } } } else { // Run this function on the main thread. ActivityThread.sMainThreadHandler.post(new Runnable() { public void run() { notifyListeners(mcr); } }); } } } /** * Enqueue an already-committed-to-memory result to be written * to disk. * * They will be written to disk one-at-a-time in the order * that they're enqueued. * * @param postWriteRunnable if non-null, we're being called * from apply() and this is the runnable to run after * the write proceeds. if null (from a regular commit()), * then we're allowed to do this disk write on the main * thread (which in addition to reducing allocations and * creating a background thread, this has the advantage that * we catch them in userdebug StrictMode reports to convert * them where possible to apply() ...) */ private void enqueueDiskWrite(final MemoryCommitResult mcr, final Runnable postWriteRunnable) { final Runnable writeToDiskRunnable = new Runnable() { public void run() { synchronized (mWritingToDiskLock) { writeToFile(mcr); } synchronized (SharedPreferencesImpl.this) { mDiskWritesInFlight--; } if (postWriteRunnable != null) { postWriteRunnable.run(); } } }; final boolean isFromSyncCommit = (postWriteRunnable == null); // Typical #commit() path with fewer allocations, doing a write on // the current thread. if (isFromSyncCommit) { boolean wasEmpty = false; synchronized (SharedPreferencesImpl.this) { wasEmpty = mDiskWritesInFlight == 1; } if (wasEmpty) { writeToDiskRunnable.run(); return; } } QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable); } private static FileOutputStream createFileOutputStream(File file) { FileOutputStream str = null; try { str = new FileOutputStream(file); } catch (FileNotFoundException e) { File parent = file.getParentFile(); if (!parent.mkdir()) { Log.e(TAG, "Couldn't create directory for SharedPreferences file " + file); return null; } FileUtils.setPermissions( parent.getPath(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, -1, -1); try { str = new FileOutputStream(file); } catch (FileNotFoundException e2) { Log.e(TAG, "Couldn't create SharedPreferences file " + file, e2); } } return str; } // Note: must hold mWritingToDiskLock private void writeToFile(MemoryCommitResult mcr) { // Rename the current file so it may be used as a backup during the next read if (mFile.exists()) { if (!mcr.changesMade) { // If the file already exists, but no changes were // made to the underlying map, it's wasteful to // re-write the file. Return as if we wrote it // out. mcr.setDiskWriteResult(true); return; } if (!mBackupFile.exists()) { if (!mFile.renameTo(mBackupFile)) { Log.e(TAG, "Couldn't rename file " + mFile + " to backup file " + mBackupFile); mcr.setDiskWriteResult(false); return; } } else { mFile.delete(); } } // Attempt to write the file, delete the backup and return true as atomically as // possible. If any exception occurs, delete the new file; next time we will restore // from the backup. try { FileOutputStream str = createFileOutputStream(mFile); if (str == null) { mcr.setDiskWriteResult(false); return; } XmlUtils.writeMapXml(mcr.mapToWriteToDisk, str); FileUtils.sync(str); str.close(); setFilePermissionsFromMode(mFile.getPath(), mMode, 0); FileStatus stat = new FileStatus(); if (FileUtils.getFileStatus(mFile.getPath(), stat)) { synchronized (this) { mStatTimestamp = stat.mtime; mStatSize = stat.size; } } // Writing was successful, delete the backup file if there is one. mBackupFile.delete(); mcr.setDiskWriteResult(true); return; } catch (XmlPullParserException e) { Log.w(TAG, "writeToFile: Got exception:", e); } catch (IOException e) { Log.w(TAG, "writeToFile: Got exception:", e); } // Clean up an unsuccessfully written file if (mFile.exists()) { if (!mFile.delete()) { Log.e(TAG, "Couldn't clean up partially-written file " + mFile); } } mcr.setDiskWriteResult(false); } } }
36.344288
114
0.546693
b4cca5fbdff4137f1f5c653a6afc6b07879aa810
1,369
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]>, all rights reserved. * * This code is private property of the copyright holder and cannot be used without * having obtained a license or prior written permission of the copyright holder. * * 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.vladsch.md.nav.testUtil.cases; import com.vladsch.flexmark.util.data.DataHolder; import com.vladsch.plugin.test.util.cases.LightFixtureLineMarkerSpecTest; import java.util.HashMap; import java.util.Map; public interface MdLightFixtureLineMarkerSpecTest extends MdCodeInsightFixtureSpecTestCase, LightFixtureLineMarkerSpecTest { Map<String, DataHolder> optionsMap = new HashMap<>(); static Map<String, DataHolder> getOptionsMap() { synchronized (optionsMap) { if (optionsMap.isEmpty()) { optionsMap.putAll(MdCodeInsightFixtureSpecTestCase.getOptionsMap()); optionsMap.putAll(LightFixtureLineMarkerSpecTest.getOptionsMap()); } return optionsMap; } } }
37
124
0.739226
0aaa684b0534025d3400dcdd0bf0d424590bbdf3
1,747
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.errorTreeView; import com.intellij.icons.AllIcons; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.CustomizeColoredTreeCellRenderer; import com.intellij.ui.SimpleColoredComponent; import com.intellij.ui.SimpleTextAttributes; import javax.swing.*; public class FixedHotfixGroupElement extends GroupingElement { private final CustomizeColoredTreeCellRenderer myCustomizeColoredTreeCellRenderer; public FixedHotfixGroupElement(String name, Object data, VirtualFile file) { super(name, data, file); myCustomizeColoredTreeCellRenderer = new CustomizeColoredTreeCellRenderer() { @Override public void customizeCellRenderer(SimpleColoredComponent renderer, JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { renderer.setIcon(AllIcons.General.Information); renderer.append("Fixed: ", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); final String[] text = getText(); final String checkedText = ((text != null) && (text.length > 0)) ? text[0] : ""; renderer.append(checkedText, SimpleTextAttributes.REGULAR_ATTRIBUTES); } }; } @Override public CustomizeColoredTreeCellRenderer getLeftSelfRenderer() { return myCustomizeColoredTreeCellRenderer; } }
42.609756
140
0.647396
bc7241f597ddd6a965661f86924ccd992440c6ed
9,056
/*************************************************************************** * JVerbnet v1.2.0 * Copyright (c) 2012 Massachusetts Institute of Technology * * JVerbnet is distributed under the terms of the Creative Commons * Attribution 3.0 Unported License, which means it may be freely used for * all purposes, as long as proper acknowledgment is made. See the license * file included with this distribution for more details. ****************************************************************************/ package edu.mit.jverbnet.data.syntax; import static edu.mit.jverbnet.util.Checks.NotNull; import edu.mit.jverbnet.data.selection.IRestrType; import edu.mit.jverbnet.data.selection.ISelRestrictions; import edu.mit.jverbnet.data.selection.SelRestrictions; import edu.mit.jverbnet.data.syntax.SyntaxArgType.VALUE_RULE; import edu.mit.jverbnet.util.Checks; /** * Default implementation of {@link ISyntaxArgDesc}. * * @author Mark A. Finlayson * @version 1.2.0 * @since JVerbnet 1.0.0 */ public class SyntaxArgDesc implements ISyntaxArgDesc { // unchanging fields private final ISyntaxDesc parent; private final SyntaxArgType type; private final String value; private final INounPhraseType npType; private final ISelRestrictions<? extends IRestrType> selRestrs; /** * Creates a new syntax argument description with the specified parameters. * May be used to create all syntax arguments other than those of the * {@link SyntaxArgType#NP} type. * * @param parent the syntax descriptor parent of this argument; may not be <code>null</code> * @param type * the type; may not be <code>null</code> or * {@link SyntaxArgType#NP} * @param value * the value; must meet the restrictions of the type or an * exception is thrown; see * {@link VALUE_RULE#checkValue(String)}. * @param selRestrs * the selectional restrictions for this argument; may be * <code>null</code> * @since JVerbnet 1.2.0 */ public SyntaxArgDesc(ISyntaxDesc parent, SyntaxArgType type, String value, ISelRestrictions<? extends IRestrType> selRestrs){ this(parent, type, value, null, selRestrs); } /** * Creates a new syntax argument description of the {@link SyntaxArgType#NP} * type with the specified parameters. * * @param parent * the syntax descriptor parent of this argument; may not be * <code>null</code> * @param type * the noun phrase type * @param value * the value; must meet the restrictions of the type or an * exception is thrown; see {@link VALUE_RULE#checkValue(String)} * . * @param selRestrs * the selectional restrictions for this argument; may be * <code>null</code> * @since JVerbnet 1.2.0 */ public SyntaxArgDesc(ISyntaxDesc parent, INounPhraseType type, String value, ISelRestrictions<? extends IRestrType> selRestrs){ this(parent, SyntaxArgType.NP, value, type, selRestrs); } /** * Creates a new syntax argument description with full control. * * @param parent * the syntax descriptor parent of this argument; may not be * <code>null</code> * @param type * the type; may not be <code>null</code> * @param value * the value; must meet the restrictions of the type or an * exception is thrown; see {@link VALUE_RULE#checkValue(String)} * @param npType * must be non-<code>null</code> if the type is * {@link SyntaxArgType#NP}; otherwise must be <code>null</code> * @param selRestrs * the selectional restrictions for this argument; may be * <code>null</code> * @throws NullPointerException * if type is <code>null</code>; or if the type requires the * value not to be <code>null</code> and the value is * <code>null</code> * @since JVerbnet 1.2.0 */ public SyntaxArgDesc(ISyntaxDesc parent, SyntaxArgType type, String value, INounPhraseType npType, ISelRestrictions<? extends IRestrType> selRestrs){ // check arguments NotNull.check("parent", parent); NotNull.check("type", type); value = type.getValueRule().checkValue(value); if(selRestrs == null) selRestrs = SelRestrictions.emptyRestrictions(); // check type/npType compatibility if(type == SyntaxArgType.NP && npType == null) throw new IllegalArgumentException("Must specific npType if argument type is NP"); if(type != SyntaxArgType.NP && npType != null) throw new IllegalArgumentException("May not specific npType if argument type is not NP"); // assign fields this.parent = parent; this.type = type; this.value = value; this.npType = npType; this.selRestrs = selRestrs; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc#getParent() */ public ISyntaxDesc getParent() { return parent; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc#getType() */ public SyntaxArgType getType() { return type; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc#getValue() */ public String getValue() { return value; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc#getNounPhraseType() */ public INounPhraseType getNounPhraseType() { return npType; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc#getSelRestrictions() */ public ISelRestrictions<? extends IRestrType> getSelRestrictions() { return selRestrs; } /** * Default implementation of syntax arg descriptor builder interface. * * @author Mark A. Finlayson * @version 1.2.0 * @since JVerbnet 1.2.0 */ public static class SyntaxArgDescBuilder implements ISyntaxArgDescBuilder { private SyntaxArgType type; private String value; private INounPhraseType npType; private ISelRestrictions<? extends IRestrType> selRestrs; /** * Creates a new builder with the specified values. Any value may be set * to <code>null</code> on construction. * * @since JVerbnet 1.2.0 */ public SyntaxArgDescBuilder(SyntaxArgType type, String value, INounPhraseType npType, ISelRestrictions<? extends IRestrType> selRestrs) { this.type = type; this.value = value; this.npType = npType; this.selRestrs = selRestrs; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc#getParent() */ public ISyntaxDesc getParent() { return Checks.thisMethodShouldNeverBeCalled(); } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc#getType() */ public SyntaxArgType getType() { return type; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc#getValue() */ public String getValue() { return value; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc#getNounPhraseType() */ public INounPhraseType getNounPhraseType() { return npType; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc#getSelRestrictions() */ public ISelRestrictions<? extends IRestrType> getSelRestrictions() { return selRestrs; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc.ISyntaxArgDescBuilder#setType(edu.mit.jverbnet.data.syntax.SyntaxArgType) */ public void setType(SyntaxArgType type) { this.type = type; if(type != SyntaxArgType.NP) this.npType = null; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc.ISyntaxArgDescBuilder#setValue(java.lang.String) */ public void setValue(String value) { this.value = value; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc.ISyntaxArgDescBuilder#setNounPhrasetype(edu.mit.jverbnet.data.syntax.INounPhraseType) */ public void setNounPhrasetype(INounPhraseType npType) { if(npType == null) return; this.type = SyntaxArgType.NP; this.npType = npType; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc.ISyntaxArgDescBuilder#setSelRestrictions(edu.mit.jverbnet.data.selection.ISelRestrictions) */ public void setSelRestrictions(ISelRestrictions<? extends IRestrType> restrs) { this.selRestrs = restrs; } /* * (non-Javadoc) * * @see edu.mit.jverbnet.data.syntax.ISyntaxArgDesc.ISyntaxArgDescBuilder#create(edu.mit.jverbnet.data.syntax.ISyntaxDesc) */ public ISyntaxArgDesc create(ISyntaxDesc parent) { return new SyntaxArgDesc(parent, type, value, npType, selRestrs); } } }
30.594595
151
0.64587
53cd6de2e41f02161d15c7a21377b494837e0b29
388
/** * */ package io.sipstack.transaction; /** * Represents all the states a transaction may be in, Invite and Non-Invite transactions * alike. Of course, a Non-Invite transaction has less states that an Invite transaction. * * @author [email protected] */ public enum TransactionState { INIT, CALLING, TRYING, PROCEEDING, ACCEPTED, COMPLETED, CONFIRMED, TERMINATED; }
25.866667
89
0.737113
29affd2071dbe9b1993be872dc15429c6fb1e225
2,142
package com.yt.comment.util; import java.io.File; import java.io.FileInputStream; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; /** * Description:MD5加密工具类 * * @author:Tong */ public class MD5Util { private static final char DIGITS[] = {'0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f'}; /** * 获取文件的MD5码 * @param absPath 文件路径 * @return 文件的Md5码 */ public final static String getFileMD5(String absPath) { try { File file = new File(absPath); MessageDigest mdTemp = MessageDigest.getInstance("MD5"); FileInputStream fis = new FileInputStream(file); FileChannel fileChannel = fis.getChannel(); MappedByteBuffer mbb = fileChannel .map(FileChannel.MapMode.READ_ONLY,0,file.length()); mdTemp.update(mbb); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0 ; i < j ; i ++) { byte byte0 = md[i]; str[k++] = DIGITS[byte0 >>> 4 & 0xf]; str[k++] = DIGITS[byte0 & 0xf]; } fis.close(); return new String(str); } catch (Exception e) { return ""; } } public final static String getMD5(String s) { char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; try { byte[] strTemp = s.getBytes(); MessageDigest mdTemp = MessageDigest.getInstance("MD5"); mdTemp.update(strTemp); byte[] md = mdTemp.digest(); int j = md.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0 ; i < j ; i ++) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { return null; } } }
31.043478
93
0.48366