blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2 values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 9.45M | extension stringclasses 28 values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
30d1ca5eb28a079e4306819bf06d6c46199bf7b0 | c1cab1be130a55207c2708eb6baa03e186fd8c1c | /src/com/zz/cms/tarticle/dao/impl/TarticleDao.java | eefcef33343b6923b7c5b3c6453f74e4c172fd93 | [] | no_license | sunrongx/zzjyCMS | 9f237152c6ad9876e7e5c09e95ea06efafe1c302 | bae9ca8f82a3a62195f72b0a6c2d2a3e5a0dd111 | refs/heads/master | 2020-06-13T01:47:45.708841 | 2019-07-27T13:26:07 | 2019-07-27T13:26:07 | 194,492,667 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,436 | java | package com.zz.cms.tarticle.dao.impl;
import java.util.List;
import com.zz.cms.exception.SysException;
import com.zz.cms.tarticle.bean.TarticleBean;
import com.zz.cms.tchannel.bean.TchannelBean;
import com.zz.cms.user.bean.UserBean;
public interface TarticleDao {
//一个map集合对应一个Tarticlebean
public List<TarticleBean> title(TarticleBean user) throws SysException ;
//根据条件查询,参数为查询条件,返回的是所有文章的集合
public List<TarticleBean> queryByTiaoJian(String TiaoJian,Object [ ] obj);
//查询所有文章信息的方法
public List<TarticleBean> queryAll();
//文章新增的判断方法
public int insertTart(TarticleBean tart);
//根据文章名查询文章信息
public TarticleBean queryBytitle(String title);
//根据作者查询文章信息
public List<TarticleBean> queryByAuther(String auther ) throws SysException;
//根据文章ID查询文章信息
public List<TarticleBean> queryTartById(int id) throws SysException;
//修改文章的方法
public int updateTart(TarticleBean tart) throws SysException;
//删除文章的方法
public int deleteTart(int id) throws SysException;
//获取所属栏目的栏目信息
public List<TchannelBean> queryChan();
//分页查询所有文章的方法
public List<TarticleBean> queryByPage(String name, int start, int size);
//查询总页数
public int queryPageCounts();
}
| [
"sunrongx@126.com"
] | sunrongx@126.com |
8edb465300510de64a838641b88374138dc82afe | 4cc4d9d488939dde56fda368faf58d8564047673 | /external/vogar/src/vogar/target/MainRunnerFactory.java | 6412b26908620247270a34410b8e8da3463786be | [] | no_license | Tosotada/android-8.0.0_r4 | 24b3e4590c9c0b6c19f06127a61320061e527685 | 7b2a348b53815c068a960fe7243b9dc9ba144fa6 | refs/heads/master | 2020-04-01T11:39:03.926512 | 2017-08-28T16:26:25 | 2017-08-28T16:26:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,449 | java | /*
* Copyright (C) 2015 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 vogar.target;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import vogar.ClassAnalyzer;
import vogar.monitor.TargetMonitor;
/**
* Supports running a class with a {@code static void main(String[] args)} entry point.
*/
public class MainRunnerFactory implements RunnerFactory {
@Override @Nullable
public TargetRunner newRunner(TargetMonitor monitor, String qualification,
Class<?> klass, AtomicReference<String> skipPastReference,
TestEnvironment testEnvironment, int timeoutSeconds, boolean profile,
String[] args) {
if (new ClassAnalyzer(klass).hasMethod(true, void.class, "main", String[].class)) {
return new MainTargetRunner(monitor, klass, args);
} else {
return null;
}
}
}
| [
"xdtianyu@gmail.com"
] | xdtianyu@gmail.com |
6e67fe1986564d867bf923df90fae8099c945258 | 0ce6fd8861b6daadb8a80e2eabb999ad19cc8149 | /src/main/java/com/coinbase/exchange/api/payments/PaymentService.java | f4f28f4a7ad85577c46c2e5adfc1538a398c87fd | [] | no_license | markd315/CryptoPayroll-API | c5431baebc6dc4df2c878bafd4851b90caa840ad | 24d99946cc181f31c8b9da2897fd46c79e38e50c | refs/heads/master | 2020-03-20T20:36:20.506387 | 2018-07-06T17:47:35 | 2018-07-06T17:47:35 | 137,696,390 | 0 | 0 | null | 2018-07-06T17:47:36 | 2018-06-18T00:21:55 | Java | UTF-8 | Java | false | false | 1,037 | java | package com.coinbase.exchange.api.payments;
import com.coinbase.exchange.api.exchange.GdaxExchange;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/**
* Created by robevansuk on 16/02/2017.
*/
@Component
@Service
public class PaymentService {
private static final String PAYMENT_METHODS_ENDPOINT = "/payment-methods";
private static final String COINBASE_ACCOUNTS_ENDPOINT = "/coinbase-accounts";
@Autowired
GdaxExchange gdaxExchange;
public List<PaymentType> getPaymentTypes() {
System.out.println(gdaxExchange);
return gdaxExchange.getAsList(PAYMENT_METHODS_ENDPOINT, new ParameterizedTypeReference<PaymentType[]>() {
});
}
public List<CoinbaseAccount> getCoinbaseAccounts() {
return gdaxExchange.getAsList(COINBASE_ACCOUNTS_ENDPOINT, new ParameterizedTypeReference<CoinbaseAccount[]>() {
});
}
} | [
"mark_davis@ultimatesoftware.com"
] | mark_davis@ultimatesoftware.com |
6fcd621d8e1711017e5ab390f9e41a93cb8faa8f | 4e81ceedae1eabc491a9ae876998776cbde49e63 | /src/main/java/com/luizmario/brewer/controller/UsuariosController.java | 5a9efd7699d62646c7ff9063aaf9925103874645 | [] | no_license | luizmdeveloper/brewer | e93634ddc3f2e98314d69782d68f7557b4f37dfa | e0a32b1195055bceecf4ee08d2149589b723e202 | refs/heads/master | 2018-09-06T05:38:37.952929 | 2018-07-10T02:04:35 | 2018-07-10T02:04:35 | 103,947,333 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,130 | java | package com.luizmario.brewer.controller;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.luizmario.brewer.controller.page.PageWrapper;
import com.luizmario.brewer.model.Usuario;
import com.luizmario.brewer.respository.GrupoRepository;
import com.luizmario.brewer.respository.UsuarioRepository;
import com.luizmario.brewer.respository.filter.UsuarioFilter;
import com.luizmario.brewer.service.StatusUsuario;
import com.luizmario.brewer.service.UsuarioService;
import com.luizmario.brewer.service.execption.EmailUsuarioJaCadastradoException;
import com.luizmario.brewer.service.execption.SenhaUsuarioNaoPreenchidaException;
import com.luizmario.brewer.service.execption.UsuarioComVendaCadastradaException;
@Controller
@RequestMapping("/usuario")
public class UsuariosController {
@Autowired
private UsuarioService usuarioService;
@Autowired
private GrupoRepository grupoRepository;
@Autowired
private UsuarioRepository usuarioRepository;
@RequestMapping("/novo")
public ModelAndView novo(Usuario usuario){
ModelAndView mv = new ModelAndView("usuario/cadastro-usuario");
mv.addObject("grupos", grupoRepository.findAll());
return mv;
}
@PostMapping(value = {"/novo", "{\\d+}"})
public ModelAndView salvar(@Valid Usuario usuario, BindingResult result, RedirectAttributes attributes) {
if (result.hasErrors()) {
return novo(usuario);
}
try {
usuarioService.salvar(usuario);
}catch (EmailUsuarioJaCadastradoException e) {
result.rejectValue("email", e.getMessage(), e.getMessage());
return novo(usuario);
}catch(SenhaUsuarioNaoPreenchidaException e) {
result.rejectValue("senha", e.getMessage(), e.getMessage());
return novo(usuario);
}
attributes.addFlashAttribute("mensagem", "Usuário salvo com sucesso!");
return new ModelAndView("redirect:/usuario/novo");
}
@GetMapping
public ModelAndView buscar(UsuarioFilter usuarioFilter, @PageableDefault(size = 5) Pageable page, HttpServletRequest httpServletRequest) {
ModelAndView mv = new ModelAndView("usuario/pesquisar-usuario");
mv.addObject("grupos", grupoRepository.findAll());
PageWrapper<Usuario> pagina = new PageWrapper<>(usuarioRepository.filtar(usuarioFilter, page), httpServletRequest);
mv.addObject("pagina", pagina);
return mv;
}
@DeleteMapping("{codigo}")
public @ResponseBody ResponseEntity<?> apagar(@PathVariable("codigo") Usuario usuario){
try {
usuarioService.apagar(usuario);
} catch (UsuarioComVendaCadastradaException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
return ResponseEntity.ok().build();
}
@PutMapping("/status")
@ResponseStatus(HttpStatus.OK)
public void altetarStatus(@RequestParam("codigos[]") Long codigos[], @RequestParam("status") StatusUsuario status) {
usuarioService.alterarStauts(codigos, status);
}
@GetMapping("/{codigo}")
public ModelAndView editar(@PathVariable Long codigo) {
Usuario usuario = usuarioRepository.buscarPor(codigo);
ModelAndView mv = novo(usuario);
mv.addObject(usuario);
return mv;
}
}
| [
"luizmariodev@gmail.com"
] | luizmariodev@gmail.com |
e3db6e7fb53766a5262b7c92dcd61f15d8fdb5ed | e2a13e10e04b2af42af2003315bf984aa1c597f2 | /newworkspace/yanbin/src/main/java/servlet/ReadFile.java | a1ff01b70401df80db085f61c9796d14ed1bdc2a | [] | no_license | yanbin93/sysuDemo | c5d59e89e6843333c05c021aa697849f1ad212e5 | 82acf2dc65c1c1b528c3b602175fbd1752537796 | refs/heads/master | 2021-01-17T11:18:13.438411 | 2017-03-23T02:48:30 | 2017-03-23T02:48:30 | 84,029,259 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,578 | java | package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.showFile;
/**
* Servlet implementation class ReadFile
*/
public class ReadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ReadFile() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
showFile showfile=new showFile();
String s_filename=request.getParameter("filename");
String content =null;
String filename=null;
if(s_filename!=null){
//接收到了pageNow
filename=s_filename;
}
if (filename!=null){
try {
content = showfile.showFile(filename);
} catch (Exception e) {
e.printStackTrace();
}
}
out.println(content);
request.setAttribute("content", content);
request.getRequestDispatcher("ReadFile.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
| [
"1010652868@qq.com"
] | 1010652868@qq.com |
f0c069e33d1b9de1b26635fdc2aa684e915c07e5 | 42d29caa568a1f02397e3aa45174377a85f28b6d | /old-lint/src/main/java/com/dedao/lints/AutoPointRegisteredCustomViewDetector.java | 54b2dffcc1b261f7f811bb9f8441ef8af9e056c4 | [
"MIT"
] | permissive | leobert-lan/-Deprecated-CustomLintRules | 5a31b5d0b03c67072e0e5eb242eeca8f1d230a44 | 10c8f4bd87db67b11529aee0d06454b61ebd7910 | refs/heads/master | 2023-06-11T17:18:32.577031 | 2021-07-01T07:36:00 | 2021-07-01T07:36:00 | 112,932,069 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,192 | java | package com.dedao.lints;
import com.android.SdkConstants;
import com.android.tools.lint.detector.api.Category;
import com.android.tools.lint.detector.api.Context;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Implementation;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.JavaContext;
import com.android.tools.lint.detector.api.Location;
import com.android.tools.lint.detector.api.Scope;
import com.android.tools.lint.detector.api.Severity;
import com.intellij.psi.PsiClass;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* user liushuo
* date 2017/4/27
* 扫描系统中所有自定义XXXView,如果该View未在
* file.properties 文件中注册,提示错误
* file.properties 文件中注册的View,会配置到
* WindowCallbackWrapper 的策略映射表中
*/
public class AutoPointRegisteredCustomViewDetector extends Detector implements Detector.JavaPsiScanner {
private static final String CLASS_RECYCLER_VIEW = "android.support.v7.widget.RecyclerView";
private static final String CLASS_GRID_VIEW = "android.widget.GridView";
private static final String CLASS_LIST_VIEW = "android.widget.ListView";
private static final String CLASS_EXPANDABLE_LIST_VIEW = "android.widget.ExpandableListView";
private static final String CLASS_VIEW_PAGER = "android.support.v4.view.ViewPager";
public static final Issue ISSUE_NO_FILE = Issue.create(
"NoFile",
"no file",
"no file",
Category.CORRECTNESS,
10,
Severity.FATAL,
new Implementation(
AutoPointRegisteredCustomViewDetector.class,
Scope.JAVA_FILE_SCOPE));
public static final Issue ISSUE_UN_REGISTER_VIEW = Issue.create(
"UnRegisterView",
"unregister view",
"unregister view",
Category.CORRECTNESS,
10,
Severity.FATAL,
new Implementation(
AutoPointRegisteredCustomViewDetector.class,
Scope.JAVA_FILE_SCOPE));
private Set<String> mSet = new HashSet<>();
@Override
public List<String> applicableSuperClasses() {
return Arrays.asList(CLASS_RECYCLER_VIEW,
CLASS_EXPANDABLE_LIST_VIEW,
CLASS_GRID_VIEW,
CLASS_VIEW_PAGER,
CLASS_LIST_VIEW);
}
@Override
public void checkClass(JavaContext context, PsiClass node) {
super.checkClass(context, node);
String name = node.getName();
mSet.add(name);
}
@Override
public void afterCheckProject(Context context) {
super.afterCheckProject(context);
File dir = context.getMainProject().getDir();
File parentDir = dir.getParentFile();
boolean gradleExists = new File(parentDir, SdkConstants.FN_BUILD_GRADLE).exists();
if (!gradleExists) {
return;
}
File file = new File(parentDir, "file.properties");
if (!file.exists()) {
context.report(ISSUE_NO_FILE, Location.create(context.file),
"no file in project reference dir '" + parentDir.getAbsolutePath() + "'");
return;
}
try {
FileInputStream fis = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fis);
Iterator<String> itr = mSet.iterator();
while (itr.hasNext()) {
String key = itr.next();
String value = properties.getProperty(key);
if (value == null || value.isEmpty()) {
context.report(ISSUE_UN_REGISTER_VIEW, Location.create(context.file),
"unregister view(" + key + ") at project " + context.getProject().getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"mrshuo@sina.cn"
] | mrshuo@sina.cn |
8ac2c013bdaa5c4b237b9a29a9409347c9ce651a | 1d02959a6cae05956a29ae4b8f4026e1a6390061 | /src/test/org/net9/group/service/GroupTopicServiceTest.java | 5b7b49380533778e37f06525dc77cfc2109b48b7 | [] | no_license | FreeDao/ctba.cn | d43326e82ad465fca3ded538d1d5e00103070ac2 | 9fe70e2c3138d6d96a5acca0e7c2892a2d61a751 | refs/heads/master | 2021-01-22T14:15:57.401667 | 2013-02-24T11:45:39 | 2013-02-24T11:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,833 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.net9.group.service;
import org.junit.Test;
import org.net9.test.TestBase;
/**
*
* @author ChenChangRen
*/
public class GroupTopicServiceTest extends TestBase {
/**
* Test of delTopic method, of class GroupTopicService.
*/
@Test
public void testDelTopic() {
}
/**
* Test of findNewTopicsForUser method, of class GroupTopicService.
*/
@Test
public void testFindNewTopicsForUser() {
}
/**
* Test of findTopics method, of class GroupTopicService.
*/
@Test
public void testFindTopics() {
}
/**
* Test of findTopicsByGroupIds method, of class GroupTopicService.
*/
@Test
public void testFindTopicsByGroupIds() {
}
/**
* Test of findTopicsByParent method, of class GroupTopicService.
*/
@Test
public void testFindTopicsByParent() {
}
/**
* Test of findTopicsByUser method, of class GroupTopicService.
*/
@Test
public void testFindTopicsByUser() {
}
/**
* Test of getGroupTopicsCnt method, of class GroupTopicService.
*/
@Test
public void testGetGroupTopicsCnt() {
}
/**
* Test of getGroupTopicsCntByParent method, of class GroupTopicService.
*/
@Test
public void testGetGroupTopicsCntByParent() {
}
/**
* Test of getNewestGroupTopic method, of class GroupTopicService.
*/
@Test
public void testGetNewestGroupTopic() {
}
/**
* Test of getTopic method, of class GroupTopicService.
*/
@Test
public void testGetTopic() {
}
/**
* Test of saveTopic method, of class GroupTopicService.
*/
@Test
public void testSaveTopic() {
}
} | [
"mockee@douban.com"
] | mockee@douban.com |
a3d2d7b76300b15a2169b371feac34ccb7ccfc2b | 1bcd0f33a48a7561048f2d31e9b354c5fabf7d85 | /app/src/main/java/com/drivequeen/driver/Activity/ActivityEmail.java | 82a28869a11bfb5617d46217790829e23df65598 | [] | no_license | AceOfLife/Bluecab | 5f407fe1cb8fe82fab0cdb2ec11ea7c1bf7e582d | c0ef10d6dd2be5422b48dafd07d1486b6ac20b38 | refs/heads/master | 2020-05-19T06:51:47.705002 | 2019-05-05T09:57:46 | 2019-05-05T09:57:46 | 184,884,987 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,438 | java | package com.drivequeen.driver.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.drivequeen.driver.Helper.SharedHelper;
import com.drivequeen.driver.R;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ActivityEmail extends AppCompatActivity {
ImageView backArrow;
FloatingActionButton nextICON;
EditText email;
TextView register, forgetPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email);
if (Build.VERSION.SDK_INT > 15) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
email = (EditText) findViewById(R.id.email);
nextICON = (FloatingActionButton) findViewById(R.id.nextIcon);
backArrow = (ImageView) findViewById(R.id.backArrow);
register = (TextView) findViewById(R.id.register);
forgetPassword = (TextView) findViewById(R.id.forgetPassword);
nextICON.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (email.getText().toString().equals("")) {
displayMessage(getString(R.string.email_validation));
} else {
SharedHelper.putKey(ActivityEmail.this, "email", email.getText().toString());
Intent mainIntent = new Intent(ActivityEmail.this, ActivityPassword.class);
startActivity(mainIntent);
finish();
}
}
});
backArrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedHelper.putKey(ActivityEmail.this, "email", "");
Intent mainIntent = new Intent(ActivityEmail.this, BeginScreen.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
ActivityEmail.this.finish();
}
});
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedHelper.putKey(ActivityEmail.this, "password", "");
Intent mainIntent = new Intent(ActivityEmail.this, RegisterActivity.class);
mainIntent.putExtra("isFromMailActivity", true);
startActivity(mainIntent);
}
});
forgetPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedHelper.putKey(ActivityEmail.this, "password", "");
Intent mainIntent = new Intent(ActivityEmail.this, ForgetPassword.class);
mainIntent.putExtra("isFromMailActivity", true);
startActivity(mainIntent);
}
});
}
public void displayMessage(String toastString) {
try {
Snackbar.make(getCurrentFocus(), toastString, Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, toastString, Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
public void onBackPressed() {
SharedHelper.putKey(ActivityEmail.this, "email", "");
Intent mainIntent = new Intent(ActivityEmail.this, BeginScreen.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainIntent);
ActivityEmail.this.finish();
}
} | [
"teddyogbonnaya@yahoo.com"
] | teddyogbonnaya@yahoo.com |
0ab7eb16ee706f6389caa1ee44918b973606d33b | 7fd4119937bc97c9185a3f894f208178e0e00642 | /common/src/main/java/dk/frv/enav/common/xml/metoc/MetocForecastTriplet.java | c93acb1657372bd616d6aea12b0de73e308ce68c | [] | no_license | dma-graveyard/EnavShore | 15847d7aec278ceaad9928a2582e2a59a3822691 | 01f5f6c8c554988bdf991b8b9528fd9c4f14d168 | refs/heads/master | 2021-01-23T07:08:53.051185 | 2014-12-03T14:18:39 | 2014-12-03T14:18:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,141 | java | package dk.frv.enav.common.xml.metoc;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "metocForecastTriplet", propOrder = {})
public class MetocForecastTriplet implements Serializable {
private static final long serialVersionUID = 1L;
private Double forecast;
private Double min;
private Double max;
public MetocForecastTriplet() {
}
public MetocForecastTriplet(Double forecast, Double min, Double max) {
this.forecast = forecast;
this.min = min;
this.max = max;
}
public MetocForecastTriplet(Double forecast) {
this(forecast, null, null);
}
public Double getForecast() {
return forecast;
}
public void setForecast(Double forecast) {
this.forecast = forecast;
}
public Double getMin() {
return min;
}
public void setMin(Double min) {
this.min = min;
}
public Double getMax() {
return max;
}
public void setMax(Double max) {
this.max = max;
}
}
| [
"RCH@PC5467.fomfrv.dk"
] | RCH@PC5467.fomfrv.dk |
50d5a49c073e340b553bc8fcc2728703534b7232 | 9feb2d5919c61ac4dcac42ade4c86d3a33cfe21c | /common-library/src/main/java/com/dysen/common_library/tools/chart/DynamicLineChartManager.java | b765c1881fc6cce99c477530ec920d98cd6caf70 | [] | no_license | dysen2014/CommonTest | a48858eb1c3c058e1f1d421d6faf954979e637e6 | e2d414ff777de0891e21e3827208961422ecc65c | refs/heads/master | 2020-03-24T16:25:36.384207 | 2018-12-29T09:35:33 | 2018-12-29T09:35:33 | 142,824,228 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,306 | java | package com.dysen.common_library.tools.chart;
import com.dysen.common_library.R;
import com.dysen.common_library.utils.Tools;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* @package com.vip.zb.tool
* @email dy.sen@qq.com
* created by dysen on 2018/9/10 - 下午2:45
* @info
*/
public class DynamicLineChartManager {
private LineChart lineChart;
private YAxis leftAxis;
private YAxis rightAxis;
private XAxis xAxis;
private LineData lineData;
private LineDataSet lineDataSet;
private List<ILineDataSet> lineDataSets = new ArrayList<>();
private SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
private List<String> timeList = new ArrayList<>(); //存储x轴的时间
public void setTimeList(List<String> timeList) {
this.timeList = timeList;
}
//一条曲线
public DynamicLineChartManager(LineChart mLineChart, String name, int color) {
this.lineChart = mLineChart;
leftAxis = lineChart.getAxisLeft();
rightAxis = lineChart.getAxisRight();
xAxis = lineChart.getXAxis();
initLineChart();
initLineDataSet(name, color);
}
//多条曲线
public DynamicLineChartManager(LineChart mLineChart, List<String> names, List<Integer> colors) {
this.lineChart = mLineChart;
leftAxis = lineChart.getAxisLeft();
rightAxis = lineChart.getAxisRight();
xAxis = lineChart.getXAxis();
initLineChart();
initLineDataSet(names, colors);
}
/**
* 初始化LineChar
*/
private void initLineChart() {
lineChart.setDrawGridBackground(false);
//显示边界
lineChart.setDrawBorders(false);
lineChart.setBorderColor(Tools.getColor(R.color.white));
//折线图例 标签 设置
Legend legend = lineChart.getLegend();
legend.setForm(Legend.LegendForm.LINE);
legend.setTextSize(11f);
//显示位置
legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
legend.setDrawInside(false);
legend.setEnabled(false);// 不显示图例
//X轴设置显示位置在底部
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
xAxis.setGranularity(1f);
xAxis.setLabelCount(5);
xAxis.setTextColor(Tools.getColor(R.color.white));
xAxis.setGridColor(Tools.getColor(R.color.transparent));
xAxis.setYOffset(20f);
xAxis.setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return timeList.get((int) value % timeList.size());
}
});
//保证Y轴从0开始,不然会上移一点
leftAxis.setAxisMinimum(0f);
rightAxis.setAxisMinimum(0f);
}
/**
* 初始化折线(一条线)
*
* @param name
* @param color
*/
private void initLineDataSet(String name, int color) {
lineDataSet = new LineDataSet(null, name);
lineDataSet.setLabel("");
lineDataSet.setLineWidth(1.2f);
lineDataSet.setCircleRadius(1.5f);
lineDataSet.setColor(color);
lineDataSet.setCircleColor(color);
lineDataSet.setHighLightColor(color);
//设置曲线填充
lineDataSet.setDrawFilled(false);
lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
lineDataSet.setValueTextSize(10f);
// 设置平滑曲线
lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
// 不显示坐标点的小圆点
lineDataSet.setDrawCircles(false);
// 不显示坐标点的数据
lineDataSet.setDrawValues(false);
// 不显示定位线
lineDataSet.setHighlightEnabled(false);
//添加一个空的 LineData
lineData = new LineData();
lineChart.setData(lineData);
lineChart.invalidate();
// 不从y轴发出横向直线
leftAxis.setDrawGridLines(true);
xAxis.setDrawAxisLine(false);
// 设置y轴数据偏移量
rightAxis.setAxisLineColor(Tools.getColor(R.color.transparent));
rightAxis.setYOffset(-3);
xAxis.setAxisLineColor(Tools.getColor(R.color.transparent));
}
/**
* 初始化折线(多条线)
*
* @param names
* @param colors
*/
private void initLineDataSet(List<String> names, List<Integer> colors) {
for (int i = 0; i < names.size(); i++) {
lineDataSet = new LineDataSet(null, names.get(i));
lineDataSet.setColor(colors.get(i));
lineDataSet.setLineWidth(1.5f);
lineDataSet.setCircleRadius(1.5f);
lineDataSet.setColor(colors.get(i));
lineDataSet.setDrawFilled(true);
lineDataSet.setCircleColor(colors.get(i));
lineDataSet.setHighLightColor(colors.get(i));
lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
lineDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
lineDataSet.setValueTextSize(10f);
lineDataSets.add(lineDataSet);
}
//添加一个空的 LineData
lineData = new LineData();
lineChart.setData(lineData);
lineChart.invalidate();
}
/**
* 动态添加数据(一条折线图)
*
* @param number
*/
public void addEntry(float number) {
//最开始的时候才添加 lineDataSet(一个lineDataSet 代表一条线)
if (lineDataSet.getEntryCount() == 0) {
lineData.addDataSet(lineDataSet);
}
lineChart.setData(lineData);
//避免集合数据过多,及时清空(做这样的处理,并不知道有没有用,但还是这样做了)
if (timeList.size() > 11) {
timeList.clear();
}
timeList.add(df.format(System.currentTimeMillis()));
Entry entry = new Entry(lineDataSet.getEntryCount(), number);
lineData.addEntry(entry, 0);
//通知数据已经改变
lineData.notifyDataChanged();
lineChart.notifyDataSetChanged();
lineData.setDrawValues(false);
//设置在曲线图中显示的最大数量
lineChart.setVisibleXRangeMaximum(5);
//移到某个位置
lineChart.moveViewToX(lineData.getEntryCount() - 5);
// 不显示x, y轴
leftAxis.setDrawAxisLine(false);
rightAxis.setDrawAxisLine(false);
}
/**
* 动态添加数据(多条折线图)
*
* @param numbers
*/
public void addEntry(List<Float> numbers) {
if (lineDataSets.get(0).getEntryCount() == 0) {
lineData = new LineData(lineDataSets);
lineChart.setData(lineData);
}
if (timeList.size() > 11) {
timeList.clear();
}
timeList.add(df.format(System.currentTimeMillis()));
for (int i = 0; i < numbers.size(); i++) {
Entry entry = new Entry(lineDataSet.getEntryCount(), numbers.get(i));
lineData.addEntry(entry, i);
lineData.notifyDataChanged();
lineChart.notifyDataSetChanged();
lineChart.setVisibleXRangeMaximum(6);
lineChart.moveViewToX(lineData.getEntryCount() - 5);
}
}
/**
* 设置Y轴值
*
* @param max
* @param min
* @param labelCount
*/
public void setYAxis(float max, float min, int labelCount) {
if (max < min) {
return;
}
// leftAxis.setAxisMaximum(max);
// leftAxis.setAxisMinimum(min);
// leftAxis.setLabelCount(labelCount, false);
leftAxis.setEnabled(false);
rightAxis.setYOffset(8f);
rightAxis.setAxisMaximum(max);
rightAxis.setAxisMinimum(min);
rightAxis.setDrawAxisLine(false); //设置为true,绘制轴线
rightAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART); //y轴的数值显示在内侧
rightAxis.setTextColor(Tools.getColor(R.color.white));
rightAxis.setLabelCount(labelCount, false);
lineChart.invalidate();
}
/**
* 设置高限制线
*
* @param high
* @param name
*/
public void setHightLimitLine(float high, String name, int color) {
if (name == null) {
name = "高限制线";
}
LimitLine hightLimit = new LimitLine(high, name);
hightLimit.setLineWidth(4f);
hightLimit.setTextSize(10f);
hightLimit.setLineColor(color);
hightLimit.setTextColor(color);
leftAxis.addLimitLine(hightLimit);
lineChart.invalidate();
}
/**
* 设置低限制线
*
* @param low
* @param name
*/
public void setLowLimitLine(int low, String name) {
if (name == null) {
name = "低限制线";
}
LimitLine hightLimit = new LimitLine(low, name);
hightLimit.setLineWidth(4f);
hightLimit.setTextSize(10f);
leftAxis.addLimitLine(hightLimit);
lineChart.invalidate();
}
/**
* 设置描述信息
*
* @param str
*/
public void setDescription(String str) {
Description description = new Description();
description.setText(str);
lineChart.setDescription(description);
lineChart.invalidate();
}
}
| [
"dysen@outlook.com"
] | dysen@outlook.com |
383dc3157cd34e6439ec6529678ff0f2aa8115a2 | c80c49976c783d6e593655519d8336cd74afab5a | /src/org/gulup/http/StringRequestHttp.java | a4476d37bb47548c688dd08ac4681ada1a06c796 | [] | no_license | gulup/gCore | 7ea2c5fd14b1ffdc2f6a43711a374f649fa51169 | 14de2e64df3ec1db6d01c0c83ab0b0a32d8a9356 | refs/heads/master | 2021-01-19T13:03:29.695897 | 2015-04-15T06:29:52 | 2015-04-15T06:29:52 | 24,041,833 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,968 | java | package org.gulup.http;
import java.util.Map;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
/**
* 運行一個StringRequest
* @author 李靜
* @version 2014-5-16
*/
public class StringRequestHttp {
/**
* 運行一個StringRequest
* @param queue 隊列
* @param url 地址
* @param listener 請求成功回調
* @param errorListener 請求錯誤回調
* @param header header參數
*/
public static void runStringRequest(RequestQueue queue,String url,Response.Listener<String> listener,
Response.ErrorListener errorListener ,final Map header){
StringRequest request = new StringRequest(url,listener,errorListener){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
// TODO Auto-generated method stub
return header == null ? super.getHeaders() : header;
}
};
queue.add(request);
}
/**
* 運行一個StringRequest
* @param queue 隊列、
* @param method 請求方式
* @param url 地址
* @param listener 請求成功回調
* @param errorListener 請求錯誤回調
* @param header header參數
*/
public static void runStringRequset(RequestQueue queue,String url,int method,
Response.Listener<String> listener,Response.ErrorListener errorListener,
final Map header,final Map body){
StringRequest request = new StringRequest(method,url,listener,errorListener){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
// TODO Auto-generated method stub
return header == null ? super.getHeaders() : header;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
// TODO Auto-generated method stub
return body == null ? super.getParams() : body;
}
};
queue.add(request);
}
}
| [
"460162314@qq.com"
] | 460162314@qq.com |
b78e062ebc21a57ee427b10b64bbfab2f7484091 | 76d298253f0c991a43b7d263fe4c6f3bca655a9f | /lang/java/reef-runtime-mock/src/main/java/org/apache/reef/mock/runtime/MockFailedEvaluator.java | d9c0c3c735c24019aad14ef998de3efc9ed6d8c4 | [
"Apache-2.0"
] | permissive | ryumbra/reef | fb8aa4f86113a121ff54314f2eca7fd5003e312e | b759764c7b67afd6cd37044029901ec8a9adba72 | refs/heads/master | 2021-05-14T09:00:26.725402 | 2018-01-26T00:46:08 | 2018-02-21T21:01:53 | 116,315,393 | 1 | 0 | null | 2018-03-26T22:10:52 | 2018-01-04T22:51:34 | Java | UTF-8 | Java | false | false | 2,342 | java | /*
* 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.reef.mock.runtime;
import org.apache.reef.annotations.Unstable;
import org.apache.reef.annotations.audience.Private;
import org.apache.reef.driver.context.FailedContext;
import org.apache.reef.driver.evaluator.FailedEvaluator;
import org.apache.reef.driver.task.FailedTask;
import org.apache.reef.exception.EvaluatorException;
import org.apache.reef.util.Optional;
import java.util.ArrayList;
import java.util.List;
/**
* mock failed evaluator.
*/
@Unstable
@Private
public final class MockFailedEvaluator implements FailedEvaluator {
private final String evaluatorID;
private final List<FailedContext> failedContextList;
private final Optional<FailedTask> failedTask;
public MockFailedEvaluator(
final String evaluatorID,
final List<FailedContext> failedContextList,
final Optional<FailedTask> failedTask) {
this.evaluatorID = evaluatorID;
this.failedContextList = failedContextList;
this.failedTask = failedTask;
}
public MockFailedEvaluator(final String evaluatorID) {
this.evaluatorID = evaluatorID;
this.failedContextList = new ArrayList<>();
this.failedTask = Optional.empty();
}
@Override
public EvaluatorException getEvaluatorException() {
return null;
}
@Override
public List<FailedContext> getFailedContextList() {
return this.failedContextList;
}
@Override
public Optional<FailedTask> getFailedTask() {
return this.failedTask;
}
@Override
public String getId() {
return this.evaluatorID;
}
}
| [
"weimer@apache.org"
] | weimer@apache.org |
253aaea8974df53b540a88130817630e3a34d4b5 | 2a0478eddd2dde1729642c65267e585396004770 | /src/main/java/ClassifiedObject.java | 13e6a4eca8d69a8b148ad755343d5fe0659d92b1 | [] | no_license | RabaDabaDoba/thesis | c74d4f6f37e34aa20d7064570d4067f10c5e6b5b | fd65ce5540419bff1add7b17660b0db6b4f71691 | refs/heads/master | 2020-05-19T15:20:00.913703 | 2019-05-05T22:07:50 | 2019-05-05T22:07:50 | 185,082,909 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,230 | java |
import java.util.Comparator;
/*
* 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.
*/
/**
*
* @author Robin
*/
public class ClassifiedObject {
String name;
double value;
public ClassifiedObject(String name, double value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
@Override
public String toString() {
return "ClassifiedObject{" + "name=" + name + ", value=" + value + '}';
}
}
class Sortbyvalue implements Comparator<ClassifiedObject>
{
// Used for sorting in ascending order of
// roll number
public int compare(ClassifiedObject a, ClassifiedObject b)
{
if (a.getValue() < b.getValue()) return -1;
if (a.getValue() > b.getValue()) return 1;
return 0;
}
}
| [
"robindah@kth.se"
] | robindah@kth.se |
5dd5a5f8bff5f945dd8712def42075a2f16fec16 | fe7dd864012b1551ad7f35696adb7962c79337ea | /src/buildcraft/api/transport/IStripesHandler.java | 311589eaa93f0c79baa9894e3a90854359ba045b | [] | no_license | P3pp3rF1y/MineFactoryReloaded | 45db3543b6e9bf72b0b528dc8faf102f6de7f16f | c33a33c97132ba51b0021688450809b82978c15b | refs/heads/1.10.x | 2020-06-13T05:21:43.880923 | 2018-02-04T20:17:55 | 2018-02-04T20:17:55 | 75,440,286 | 11 | 3 | null | 2023-06-28T14:58:26 | 2016-12-02T23:55:55 | Java | UTF-8 | Java | false | false | 864 | java | /** Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team http://www.mod-buildcraft.com
*
* The BuildCraft API is distributed under the terms of the MIT License. Please check the contents of the license, which
* should be located as "LICENSE.API" in the BuildCraft source code distribution. */
package buildcraft.api.transport;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public interface IStripesHandler {
enum StripesHandlerType {
ITEM_USE,
BLOCK_BREAK
}
StripesHandlerType getType();
boolean shouldHandle(ItemStack stack);
boolean handle(World world, BlockPos pos, EnumFacing direction, ItemStack stack, EntityPlayer player, IStripesActivator activator);
}
| [
"p3pp3rf1y@gmail.com"
] | p3pp3rf1y@gmail.com |
7733ed321eb8fc0cdbd7eb32c0490d21a63ff023 | 235fdb2dc7b13d35031b3b0ffa0916f397a4d3b8 | /connect-examples/v2/square-connect-sdk/java/src/main/java/com/squareup/connect/models/BalancePaymentDetails.java | 1b367c79328709fe5484bf42c99bffb414b1acd1 | [
"Apache-2.0"
] | permissive | fakeNetflix/square-repo-connect-api-examples | 0d63bef859917d48c9837fe97a3086c189e5e7f1 | c5db8e77988c3b47317a3588458604e785ddb23d | refs/heads/master | 2023-02-05T18:01:42.260483 | 2019-08-15T21:40:03 | 2019-08-15T21:40:03 | 203,054,353 | 0 | 0 | null | 2022-12-14T07:33:29 | 2019-08-18T20:40:30 | Java | UTF-8 | Java | false | false | 2,920 | java | /*
* Square Connect API
* Client library for accessing the Square Connect APIs
*
* OpenAPI spec version: 2.0
* Contact: developers@squareup.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.squareup.connect.models;
import java.util.Objects;
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;
/**
* Reflects the current status of a balance payment.
*/
@ApiModel(description = "Reflects the current status of a balance payment.")
public class BalancePaymentDetails {
@JsonProperty("account_id")
private String accountId = null;
@JsonProperty("status")
private String status = null;
public BalancePaymentDetails accountId(String accountId) {
this.accountId = accountId;
return this;
}
/**
* ID for the account used to fund the payment.
* @return accountId
**/
@ApiModelProperty(value = "ID for the account used to fund the payment.")
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public BalancePaymentDetails status(String status) {
this.status = status;
return this;
}
/**
* The balance payment’s current state. Can be `COMPLETED` or `FAILED`.
* @return status
**/
@ApiModelProperty(value = "The balance payment’s current state. Can be `COMPLETED` or `FAILED`.")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BalancePaymentDetails balancePaymentDetails = (BalancePaymentDetails) o;
return Objects.equals(this.accountId, balancePaymentDetails.accountId) &&
Objects.equals(this.status, balancePaymentDetails.status);
}
@Override
public int hashCode() {
return Objects.hash(accountId, status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class BalancePaymentDetails {\n");
sb.append(" accountId: ").append(toIndentedString(accountId)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).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 ");
}
}
| [
"xiao@squareup.com"
] | xiao@squareup.com |
41ea773d6762625962268c3a9a5efc57338203cd | 1067e2dea4a8b6d90fcc10cf474a47f36eecdd3b | /app/src/main/java/com/example/yangchaoming/bappdemo/demo1/widget/NineImageAdapter.java | 9956a38e3d97ff5e8ee90df56e32074f41d3d5be | [] | no_license | ThePrisonerNo25/BAppDemo | cb287197438a890bf263a298c620c849f5ef88af | 1d0e6dc411f1defc69fbc0d1ea46ede0f80ff4f8 | refs/heads/master | 2021-11-23T20:31:27.959896 | 2021-11-12T03:30:57 | 2021-11-12T03:30:57 | 231,756,054 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,715 | java | package com.example.yangchaoming.bappdemo.demo1.widget;
import android.content.Context;
import android.graphics.Color;
import androidx.core.content.ContextCompat;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.example.yangchaoming.bappdemo.R;
import java.util.List;
/**
* @author KCrason
* @date 2018/4/27
*/
public class NineImageAdapter implements NineGridView.NineGridAdapter<String> {
private List<String> mImageBeans;
private Context mContext;
private RequestOptions mRequestOptions;
private DrawableTransitionOptions mDrawableTransitionOptions;
public NineImageAdapter(Context context, RequestOptions requestOptions, DrawableTransitionOptions drawableTransitionOptions, List<String> imageBeans) {
this.mContext = context;
this.mDrawableTransitionOptions = drawableTransitionOptions;
this.mImageBeans = imageBeans;
int itemSize = (getScreenWidth() - 2 * dp2px(4) - dp2px(54)) / 3;
this.mRequestOptions = requestOptions.override(itemSize, itemSize);
}
@Override
public int getCount() {
return mImageBeans == null ? 0 : mImageBeans.size();
}
@Override
public String getItem(int position) {
return mImageBeans == null ? null :
position < mImageBeans.size() ? mImageBeans.get(position) : null;
}
@Override
public View getView(int position, View itemView) {
ImageView imageView;
if (itemView == null) {
imageView = new ImageView(mContext);
imageView.setBackgroundColor(Color.parseColor("#f2f2f2"));
imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
} else {
imageView = (ImageView) itemView;
}
// String url = mImageBeans.get(position);
// Glide.with(mContext).load(url).apply(mRequestOptions).transition(mDrawableTransitionOptions).into(imageView);
imageView.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.ic_launcher));
return imageView;
}
public int dp2px(float dpValue) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, mContext.getResources().getDisplayMetrics());
}
public int getScreenWidth() {
return mContext.getResources().getDisplayMetrics().widthPixels;
}
public int getScreenHeight(){
return mContext.getResources().getDisplayMetrics().heightPixels;
}
}
| [
"yangchaoming@ejoyst.com"
] | yangchaoming@ejoyst.com |
7c88e56024a81f49fb7ca4930e44f053bcdc5d74 | 2b555a33a5826dbd816951fa074b6294d638e078 | /src/test/java/org/suresh/vasu/couchbasequeueimpl/CouchbaseListOperationsTest.java | c6662604e9c6e826c0a40b320485ad2222cee152 | [] | no_license | sureshvasu/couchbase-queue-impl | 0305d0ea84082f1490ef0771da3f290186777b7e | 332bd07f69bd7adcb145808d8b0b47342f7ef6b1 | refs/heads/master | 2023-02-27T17:19:08.377548 | 2021-02-07T03:35:15 | 2021-02-07T03:35:15 | 335,192,773 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 359 | java | package org.suresh.vasu.couchbasequeueimpl;
import org.junit.jupiter.api.Test;
public class CouchbaseListOperationsTest extends BaseTest {
@Test
public void testListAdd(){
CouchbaseListOperations couchbaseListOperations = new CouchbaseListOperations(bucket.defaultCollection());
couchbaseListOperations.listAddOperation();
}
}
| [
"suresh.vasu@tesco.com"
] | suresh.vasu@tesco.com |
dc35072204416de38eb3b18009009c339749edf0 | 4d940ba36c20b6ce3cc631017ad4e4d7ef7532ae | /app/common/src/com/retrofitstudy/common/data/TokenManager.java | fe96b4e5d8a3401c1f32f2433c723d8b5d26f0f5 | [] | no_license | GilBert1987/RetrofitStudy | e349428e57a34eba95e55728f65bbac4f7c322fd | fedcc7036e53e3646309318d7c92606693ee8f50 | refs/heads/master | 2021-01-09T06:09:18.701656 | 2017-02-05T13:39:30 | 2017-02-05T13:45:32 | 80,926,403 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 267 | java | package com.retrofitstudy.common.data;
public class TokenManager {
private static String sToken;
public static synchronized void updateToken(String token) {
sToken = token;
}
public static String getToken() {
return sToken;
}
}
| [
"wang.chen.cse@gmail.com"
] | wang.chen.cse@gmail.com |
d5fe6ce65d0d41b15c5ef23c4e97bd12277d925a | 390cf3aa01d4be4e18fb72b0c40af5eac0c1e072 | /app/src/test/java/com/nellyville/shippingcalculator/ExampleUnitTest.java | 99719ca94b59dc58477d37cfd89bae568cc46c83 | [] | no_license | BritainS/Shipping_Calculator | 52d28b406e6bf06773380c77917f0390021f2981 | 5eb2bd4adaa7cb07ad6f051a0ea8664e330453b4 | refs/heads/master | 2022-12-18T17:25:13.839135 | 2020-09-19T19:37:59 | 2020-09-19T19:37:59 | 296,939,160 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 394 | java | package com.nellyville.shippingcalculator;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"Britainsizemore@gmail.com"
] | Britainsizemore@gmail.com |
608a7214a899c50791eb68a226091c735a9c9fad | 76c8a18d702c9b1ae1f5f583d516ebc04594f7cd | /GlobalPay/src/main/java/com/capgemini/dao/GlobalDao.java | f0d83e97c8f884ab7a02dce36fbb89427bbba7a4 | [] | no_license | MalarJothisivalingam/WebProject | 1c6b4d512d96bc62b8167cab7692be6c774f6f36 | b543be6568c2217070bd1c59275f22a6a139aeff | refs/heads/master | 2020-03-29T05:02:20.977800 | 2019-02-15T05:21:19 | 2019-02-15T05:21:19 | 149,562,917 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 84 | java | package com.capgemini.dao;
public interface GlobalDao {
void method();
}
| [
"masivali@DIN13002984.corp.capgemini.com"
] | masivali@DIN13002984.corp.capgemini.com |
6d5c9916dacc0c11955a0e1f4da0bfdcce4d9e2d | dd7571c5fdcdbd35a1eda71480b96ce6d6385955 | /Nicole_Sorial/HandIn/Discord/Feb7/File6Driver.java | 54939e48e4df151624a4a304ae519746062e9fcd | [] | no_license | FRCStudents/AP2017 | 231cc8ebd7f1313bc834cbb82dea502efaf31c53 | 7ef3f661dae397ae2e00c3fe880d0afcdf5688a8 | refs/heads/master | 2021-01-20T01:27:59.386535 | 2018-04-04T21:03:21 | 2018-04-04T21:03:21 | 89,280,515 | 6 | 3 | null | 2017-09-06T13:03:06 | 2017-04-24T19:44:05 | Java | UTF-8 | Java | false | false | 125 | java | public class File6Driver {
public static void main(String[] argv) {
File6 f = new File6();
System.out.println(f);
}
} | [
"grace.cola@gmail.com"
] | grace.cola@gmail.com |
9fb7c0899d4358f6e8b068bbdcb1a291d263d02f | d5786bf0335010f7de9bb2cea6bb0a9536ff73af | /aliyun-java-sdk-sofa/src/main/java/com/aliyuncs/sofa/model/v20190815/QueryLinkeBahamutIterationdetachreleaseRequest.java | b6f174fb5847a8e8488eead2d7e53e354636b526 | [
"Apache-2.0"
] | permissive | 1203802276/aliyun-openapi-java-sdk | 8066c546f0177cbbebb7b1178fe6ccaeb6f1da09 | e3f89f2ef8542055e3990401a94edccd1bbca410 | refs/heads/master | 2023-04-15T07:09:27.195262 | 2021-03-19T06:22:51 | 2021-03-19T06:22:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,436 | java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.sofa.model.v20190815;
import com.aliyuncs.RpcAcsRequest;
import java.util.List;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.sofa.Endpoint;
/**
* @author auto create
* @version
*/
public class QueryLinkeBahamutIterationdetachreleaseRequest extends RpcAcsRequest<QueryLinkeBahamutIterationdetachreleaseResponse> {
private String overdueReason;
private Boolean overdueFastDev;
private List<String> iterationIdsRepeatLists;
private String releaseId;
private String iterationId;
private String overdueMes;
public QueryLinkeBahamutIterationdetachreleaseRequest() {
super("SOFA", "2019-08-15", "QueryLinkeBahamutIterationdetachrelease", "sofacafedeps");
setMethod(MethodType.POST);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public String getOverdueReason() {
return this.overdueReason;
}
public void setOverdueReason(String overdueReason) {
this.overdueReason = overdueReason;
if(overdueReason != null){
putBodyParameter("OverdueReason", overdueReason);
}
}
public Boolean getOverdueFastDev() {
return this.overdueFastDev;
}
public void setOverdueFastDev(Boolean overdueFastDev) {
this.overdueFastDev = overdueFastDev;
if(overdueFastDev != null){
putBodyParameter("OverdueFastDev", overdueFastDev.toString());
}
}
public List<String> getIterationIdsRepeatLists() {
return this.iterationIdsRepeatLists;
}
public void setIterationIdsRepeatLists(List<String> iterationIdsRepeatLists) {
this.iterationIdsRepeatLists = iterationIdsRepeatLists;
if (iterationIdsRepeatLists != null) {
for (int i = 0; i < iterationIdsRepeatLists.size(); i++) {
putBodyParameter("IterationIdsRepeatList." + (i + 1) , iterationIdsRepeatLists.get(i));
}
}
}
public String getReleaseId() {
return this.releaseId;
}
public void setReleaseId(String releaseId) {
this.releaseId = releaseId;
if(releaseId != null){
putBodyParameter("ReleaseId", releaseId);
}
}
public String getIterationId() {
return this.iterationId;
}
public void setIterationId(String iterationId) {
this.iterationId = iterationId;
if(iterationId != null){
putBodyParameter("IterationId", iterationId);
}
}
public String getOverdueMes() {
return this.overdueMes;
}
public void setOverdueMes(String overdueMes) {
this.overdueMes = overdueMes;
if(overdueMes != null){
putBodyParameter("OverdueMes", overdueMes);
}
}
@Override
public Class<QueryLinkeBahamutIterationdetachreleaseResponse> getResponseClass() {
return QueryLinkeBahamutIterationdetachreleaseResponse.class;
}
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
169832701b31aac0e90999c6beb31f8310445e91 | ece3113f0cbdd16d6b2180b52f2279080ff2783b | /services/java/com/android/server/ConnectivityService.java | 73bc6c912150cf2a86796c2d55ebdc2b8b7d8aef | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | GAXUSXX/android_frameworks_base | f521d1428e3162685caa6efc7ac274d26e760eef | cc3a12d7b3e47ee7ec036226438d4d5709c13623 | refs/heads/master | 2020-04-01T18:55:50.467339 | 2014-01-21T18:58:09 | 2014-01-21T18:58:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 203,669 | java | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server;
import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
import static android.net.ConnectivityManager.TYPE_DUMMY;
import static android.net.ConnectivityManager.TYPE_ETHERNET;
import static android.net.ConnectivityManager.TYPE_MOBILE;
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.net.ConnectivityManager.TYPE_WIMAX;
import static android.net.ConnectivityManager.getNetworkTypeName;
import static android.net.ConnectivityManager.isNetworkTypeValid;
import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothTetheringDataTracker;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.net.CaptivePortalTracker;
import android.net.ConnectivityManager;
import android.net.DummyDataStateTracker;
import android.net.EthernetDataTracker;
import android.net.IConnectivityManager;
import android.net.INetworkManagementEventObserver;
import android.net.INetworkPolicyListener;
import android.net.INetworkPolicyManager;
import android.net.INetworkStatsService;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.LinkProperties.CompareResult;
import android.net.LinkQualityInfo;
import android.net.MobileDataStateTracker;
import android.net.NetworkConfig;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.NetworkQuotaInfo;
import android.net.NetworkState;
import android.net.NetworkStateTracker;
import android.net.NetworkUtils;
import android.net.Proxy;
import android.net.ProxyProperties;
import android.net.RouteInfo;
import android.net.SamplingDataTracker;
import android.net.Uri;
import android.net.wifi.WifiStateTracker;
import android.net.wimax.WimaxHelper;
import android.net.wimax.WimaxManagerConstants;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.FileUtils;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.INetworkManagementService;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.ParcelFileDescriptor;
import android.os.PowerManager;
import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.provider.Settings;
import android.security.Credentials;
import android.security.KeyStore;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Slog;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.util.Xml;
import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.net.LegacyVpnInfo;
import com.android.internal.net.VpnConfig;
import com.android.internal.net.VpnProfile;
import com.android.internal.telephony.DctConstants;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.XmlUtils;
import com.android.server.am.BatteryStatsService;
import com.android.server.connectivity.DataConnectionStats;
import com.android.server.connectivity.Nat464Xlat;
import com.android.server.connectivity.PacManager;
import com.android.server.connectivity.Tethering;
import com.android.server.connectivity.Vpn;
import com.android.server.net.BaseNetworkObserver;
import com.android.server.net.LockdownVpnTracker;
import com.google.android.collect.Lists;
import com.google.android.collect.Sets;
import dalvik.system.DexClassLoader;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
/**
* @hide
*/
public class ConnectivityService extends IConnectivityManager.Stub {
private static final String TAG = "ConnectivityService";
private static final boolean DBG = true;
private static final boolean VDBG = false;
private static final boolean LOGD_RULES = false;
// TODO: create better separation between radio types and network types
// how long to wait before switching back to a radio's default network
private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
// system property that can override the above value
private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
"android.telephony.apn-restore";
// Default value if FAIL_FAST_TIME_MS is not set
private static final int DEFAULT_FAIL_FAST_TIME_MS = 1 * 60 * 1000;
// system property that can override DEFAULT_FAIL_FAST_TIME_MS
private static final String FAIL_FAST_TIME_MS =
"persist.radio.fail_fast_time_ms";
private static final String ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED =
"android.net.ConnectivityService.action.PKT_CNT_SAMPLE_INTERVAL_ELAPSED";
private static final int SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE = 0;
private PendingIntent mSampleIntervalElapsedIntent;
// Set network sampling interval at 12 minutes, this way, even if the timers get
// aggregated, it will fire at around 15 minutes, which should allow us to
// aggregate this timer with other timers (specially the socket keep alive timers)
private static final int DEFAULT_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 12 * 60);
// start network sampling a minute after booting ...
private static final int DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS = (VDBG ? 30 : 60);
AlarmManager mAlarmManager;
// used in recursive route setting to add gateways for the host for which
// a host route was requested.
private static final int MAX_HOSTROUTE_CYCLE_COUNT = 10;
private Tethering mTethering;
private KeyStore mKeyStore;
@GuardedBy("mVpns")
private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
private VpnCallback mVpnCallback = new VpnCallback();
private boolean mLockdownEnabled;
private LockdownVpnTracker mLockdownTracker;
private Nat464Xlat mClat;
/** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
private Object mRulesLock = new Object();
/** Currently active network rules by UID. */
private SparseIntArray mUidRules = new SparseIntArray();
/** Set of ifaces that are costly. */
private HashSet<String> mMeteredIfaces = Sets.newHashSet();
/**
* Sometimes we want to refer to the individual network state
* trackers separately, and sometimes we just want to treat them
* abstractly.
*/
private NetworkStateTracker mNetTrackers[];
/* Handles captive portal check on a network */
private CaptivePortalTracker mCaptivePortalTracker;
/**
* The link properties that define the current links
*/
private LinkProperties mCurrentLinkProperties[];
/**
* A per Net list of the PID's that requested access to the net
* used both as a refcount and for per-PID DNS selection
*/
private List<Integer> mNetRequestersPids[];
// priority order of the nettrackers
// (excluding dynamically set mNetworkPreference)
// TODO - move mNetworkTypePreference into this
private int[] mPriorityList;
private Context mContext;
private int mNetworkPreference;
private int mActiveDefaultNetwork = -1;
// 0 is full bad, 100 is full good
private int mDefaultInetCondition = 0;
private int mDefaultInetConditionPublished = 0;
private boolean mInetConditionChangeInFlight = false;
private int mDefaultConnectionSequence = 0;
private Object mDnsLock = new Object();
private int mNumDnsEntries;
private boolean mTestMode;
private static ConnectivityService sServiceInstance;
private INetworkManagementService mNetd;
private INetworkPolicyManager mPolicyManager;
private static final int ENABLED = 1;
private static final int DISABLED = 0;
private static final boolean ADD = true;
private static final boolean REMOVE = false;
private static final boolean TO_DEFAULT_TABLE = true;
private static final boolean TO_SECONDARY_TABLE = false;
private static final boolean EXEMPT = true;
private static final boolean UNEXEMPT = false;
/**
* used internally as a delayed event to make us switch back to the
* default network
*/
private static final int EVENT_RESTORE_DEFAULT_NETWORK = 1;
/**
* used internally to change our mobile data enabled flag
*/
private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
/**
* used internally to change our network preference setting
* arg1 = networkType to prefer
*/
private static final int EVENT_SET_NETWORK_PREFERENCE = 3;
/**
* used internally to synchronize inet condition reports
* arg1 = networkType
* arg2 = condition (0 bad, 100 good)
*/
private static final int EVENT_INET_CONDITION_CHANGE = 4;
/**
* used internally to mark the end of inet condition hold periods
* arg1 = networkType
*/
private static final int EVENT_INET_CONDITION_HOLD_END = 5;
/**
* used internally to set enable/disable cellular data
* arg1 = ENBALED or DISABLED
*/
private static final int EVENT_SET_MOBILE_DATA = 7;
/**
* used internally to clear a wakelock when transitioning
* from one net to another
*/
private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
/**
* used internally to reload global proxy settings
*/
private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
/**
* used internally to set external dependency met/unmet
* arg1 = ENABLED (met) or DISABLED (unmet)
* arg2 = NetworkType
*/
private static final int EVENT_SET_DEPENDENCY_MET = 10;
/**
* used internally to send a sticky broadcast delayed.
*/
private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
/**
* Used internally to
* {@link NetworkStateTracker#setPolicyDataEnable(boolean)}.
*/
private static final int EVENT_SET_POLICY_DATA_ENABLE = 12;
private static final int EVENT_VPN_STATE_CHANGED = 13;
/**
* Used internally to disable fail fast of mobile data
*/
private static final int EVENT_ENABLE_FAIL_FAST_MOBILE_DATA = 14;
/**
* user internally to indicate that data sampling interval is up
*/
private static final int EVENT_SAMPLE_INTERVAL_ELAPSED = 15;
/**
* PAC manager has received new port.
*/
private static final int EVENT_PROXY_HAS_CHANGED = 16;
/** Handler used for internal events. */
private InternalHandler mHandler;
/** Handler used for incoming {@link NetworkStateTracker} events. */
private NetworkStateTrackerHandler mTrackerHandler;
// list of DeathRecipients used to make sure features are turned off when
// a process dies
private List<FeatureUser> mFeatureUsers;
private boolean mSystemReady;
private Intent mInitialBroadcast;
private PowerManager.WakeLock mNetTransitionWakeLock;
private String mNetTransitionWakeLockCausedBy = "";
private int mNetTransitionWakeLockSerialNumber;
private int mNetTransitionWakeLockTimeout;
private InetAddress mDefaultDns;
// Lock for protecting access to mAddedRoutes and mExemptAddresses
private final Object mRoutesLock = new Object();
// this collection is used to refcount the added routes - if there are none left
// it's time to remove the route from the route table
@GuardedBy("mRoutesLock")
private Collection<RouteInfo> mAddedRoutes = new ArrayList<RouteInfo>();
// this collection corresponds to the entries of mAddedRoutes that have routing exemptions
// used to handle cleanup of exempt rules
@GuardedBy("mRoutesLock")
private Collection<LinkAddress> mExemptAddresses = new ArrayList<LinkAddress>();
// used in DBG mode to track inet condition reports
private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
private ArrayList mInetLog;
// track the current default http proxy - tell the world if we get a new one (real change)
private ProxyProperties mDefaultProxy = null;
private Object mProxyLock = new Object();
private boolean mDefaultProxyDisabled = false;
// track the global proxy.
private ProxyProperties mGlobalProxy = null;
private PacManager mPacManager = null;
private SettingsObserver mSettingsObserver;
NetworkConfig[] mNetConfigs;
int mNetworksDefined;
private static class RadioAttributes {
public int mSimultaneity;
public int mType;
public RadioAttributes(String init) {
String fragments[] = init.split(",");
mType = Integer.parseInt(fragments[0]);
mSimultaneity = Integer.parseInt(fragments[1]);
}
}
RadioAttributes[] mRadioAttributes;
// the set of network types that can only be enabled by system/sig apps
List mProtectedNetworks;
private DataConnectionStats mDataConnectionStats;
private AtomicInteger mEnableFailFastMobileDataTag = new AtomicInteger(0);
TelephonyManager mTelephonyManager;
public ConnectivityService(Context context, INetworkManagementService netd,
INetworkStatsService statsService, INetworkPolicyManager policyManager) {
// Currently, omitting a NetworkFactory will create one internally
// TODO: create here when we have cleaner WiMAX support
this(context, netd, statsService, policyManager, null);
}
public ConnectivityService(Context context, INetworkManagementService netManager,
INetworkStatsService statsService, INetworkPolicyManager policyManager,
NetworkFactory netFactory) {
if (DBG) log("ConnectivityService starting up");
HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
handlerThread.start();
mHandler = new InternalHandler(handlerThread.getLooper());
mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
if (netFactory == null) {
netFactory = new DefaultNetworkFactory(context, mTrackerHandler);
}
// setup our unique device name
String hostname = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.DEVICE_HOSTNAME);
if (TextUtils.isEmpty(hostname) && TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
String id = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ANDROID_ID);
if (id != null && id.length() > 0) {
String name = new String("android-").concat(id);
SystemProperties.set("net.hostname", name);
}
} else {
SystemProperties.set("net.hostname", hostname);
}
// read our default dns server ip
String dns = Settings.Global.getString(context.getContentResolver(),
Settings.Global.DEFAULT_DNS_SERVER);
if (dns == null || dns.length() == 0) {
dns = context.getResources().getString(
com.android.internal.R.string.config_default_dns_server);
}
try {
mDefaultDns = NetworkUtils.numericToInetAddress(dns);
} catch (IllegalArgumentException e) {
loge("Error setting defaultDns using " + dns);
}
mContext = checkNotNull(context, "missing Context");
mNetd = checkNotNull(netManager, "missing INetworkManagementService");
mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
mKeyStore = KeyStore.getInstance();
mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
try {
mPolicyManager.registerListener(mPolicyListener);
} catch (RemoteException e) {
// ouch, no rules updates means some processes may never get network
loge("unable to register INetworkPolicyListener" + e.toString());
}
final PowerManager powerManager = (PowerManager) context.getSystemService(
Context.POWER_SERVICE);
mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
com.android.internal.R.integer.config_networkTransitionTimeout);
mNetTrackers = new NetworkStateTracker[
ConnectivityManager.MAX_NETWORK_TYPE+1];
mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
mRadioAttributes = new RadioAttributes[ConnectivityManager.MAX_RADIO_TYPE+1];
mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
// Load device network attributes from resources
String[] raStrings = context.getResources().getStringArray(
com.android.internal.R.array.radioAttributes);
for (String raString : raStrings) {
RadioAttributes r = new RadioAttributes(raString);
if (VDBG) log("raString=" + raString + " r=" + r);
if (r.mType > ConnectivityManager.MAX_RADIO_TYPE) {
loge("Error in radioAttributes - ignoring attempt to define type " + r.mType);
continue;
}
if (mRadioAttributes[r.mType] != null) {
loge("Error in radioAttributes - ignoring attempt to redefine type " +
r.mType);
continue;
}
mRadioAttributes[r.mType] = r;
}
// TODO: What is the "correct" way to do determine if this is a wifi only device?
boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
log("wifiOnly=" + wifiOnly);
String[] naStrings = context.getResources().getStringArray(
com.android.internal.R.array.networkAttributes);
for (String naString : naStrings) {
try {
NetworkConfig n = new NetworkConfig(naString);
if (VDBG) log("naString=" + naString + " config=" + n);
if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
loge("Error in networkAttributes - ignoring attempt to define type " +
n.type);
continue;
}
if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
n.type);
continue;
}
if (mNetConfigs[n.type] != null) {
loge("Error in networkAttributes - ignoring attempt to redefine type " +
n.type);
continue;
}
if (mRadioAttributes[n.radio] == null) {
loge("Error in networkAttributes - ignoring attempt to use undefined " +
"radio " + n.radio + " in network type " + n.type);
continue;
}
mNetConfigs[n.type] = n;
mNetworksDefined++;
} catch(Exception e) {
// ignore it - leave the entry null
}
}
if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
mProtectedNetworks = new ArrayList<Integer>();
int[] protectedNetworks = context.getResources().getIntArray(
com.android.internal.R.array.config_protectedNetworks);
for (int p : protectedNetworks) {
if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
mProtectedNetworks.add(p);
} else {
if (DBG) loge("Ignoring protectedNetwork " + p);
}
}
// high priority first
mPriorityList = new int[mNetworksDefined];
{
int insertionPoint = mNetworksDefined-1;
int currentLowest = 0;
int nextLowest = 0;
while (insertionPoint > -1) {
for (NetworkConfig na : mNetConfigs) {
if (na == null) continue;
if (na.priority < currentLowest) continue;
if (na.priority > currentLowest) {
if (na.priority < nextLowest || nextLowest == 0) {
nextLowest = na.priority;
}
continue;
}
mPriorityList[insertionPoint--] = na.type;
}
currentLowest = nextLowest;
nextLowest = 0;
}
}
// Update mNetworkPreference according to user mannually first then overlay config.xml
mNetworkPreference = getPersistedNetworkPreference();
if (mNetworkPreference == -1) {
for (int n : mPriorityList) {
if (mNetConfigs[n].isDefault() && ConnectivityManager.isNetworkTypeValid(n)) {
mNetworkPreference = n;
break;
}
}
if (mNetworkPreference == -1) {
throw new IllegalStateException(
"You should set at least one default Network in config.xml!");
}
}
mNetRequestersPids =
(List<Integer> [])new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE+1];
for (int i : mPriorityList) {
mNetRequestersPids[i] = new ArrayList<Integer>();
}
mFeatureUsers = new ArrayList<FeatureUser>();
mTestMode = SystemProperties.get("cm.test.mode").equals("true")
&& SystemProperties.get("ro.build.type").equals("eng");
// Create and start trackers for hard-coded networks
for (int targetNetworkType : mPriorityList) {
final NetworkConfig config = mNetConfigs[targetNetworkType];
final NetworkStateTracker tracker;
try {
tracker = netFactory.createTracker(targetNetworkType, config);
mNetTrackers[targetNetworkType] = tracker;
} catch (IllegalArgumentException e) {
Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
+ " tracker: " + e);
continue;
}
tracker.startMonitoring(context, mTrackerHandler);
if (config.isDefault()) {
tracker.reconnect();
}
}
mTethering = new Tethering(mContext, mNetd, statsService, this, mHandler.getLooper());
//set up the listener for user state for creating user VPNs
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_USER_STARTING);
intentFilter.addAction(Intent.ACTION_USER_STOPPING);
mContext.registerReceiverAsUser(
mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
mClat = new Nat464Xlat(mContext, mNetd, this, mTrackerHandler);
try {
mNetd.registerObserver(mTethering);
mNetd.registerObserver(mDataActivityObserver);
mNetd.registerObserver(mClat);
} catch (RemoteException e) {
loge("Error registering observer :" + e);
}
if (DBG) {
mInetLog = new ArrayList();
}
mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
mSettingsObserver.observe(mContext);
mDataConnectionStats = new DataConnectionStats(mContext);
mDataConnectionStats.startMonitoring();
// start network sampling ..
Intent intent = new Intent(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED, null);
mSampleIntervalElapsedIntent = PendingIntent.getBroadcast(mContext,
SAMPLE_INTERVAL_ELAPSED_REQUEST_CODE, intent, 0);
mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
setAlarm(DEFAULT_START_SAMPLING_INTERVAL_IN_SECONDS * 1000, mSampleIntervalElapsedIntent);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED);
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ACTION_PKT_CNT_SAMPLE_INTERVAL_ELAPSED)) {
mHandler.sendMessage(mHandler.obtainMessage
(EVENT_SAMPLE_INTERVAL_ELAPSED));
}
}
},
new IntentFilter(filter));
mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
filter = new IntentFilter();
filter.addAction(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
mContext.registerReceiver(mProvisioningReceiver, filter);
}
/**
* Factory that creates {@link NetworkStateTracker} instances using given
* {@link NetworkConfig}.
*/
public interface NetworkFactory {
public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config);
}
private static class DefaultNetworkFactory implements NetworkFactory {
private final Context mContext;
private final Handler mTrackerHandler;
public DefaultNetworkFactory(Context context, Handler trackerHandler) {
mContext = context;
mTrackerHandler = trackerHandler;
}
@Override
public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
switch (config.radio) {
case TYPE_WIFI:
return new WifiStateTracker(targetNetworkType, config.name);
case TYPE_MOBILE:
return new MobileDataStateTracker(targetNetworkType, config.name);
case TYPE_DUMMY:
return new DummyDataStateTracker(targetNetworkType, config.name);
case TYPE_BLUETOOTH:
return BluetoothTetheringDataTracker.getInstance();
case TYPE_WIMAX:
return makeWimaxStateTracker(mContext, mTrackerHandler);
case TYPE_ETHERNET:
return EthernetDataTracker.getInstance();
default:
throw new IllegalArgumentException(
"Trying to create a NetworkStateTracker for an unknown radio type: "
+ config.radio);
}
}
}
/**
* Loads external WiMAX library and registers as system service, returning a
* {@link NetworkStateTracker} for WiMAX. Caller is still responsible for
* invoking {@link NetworkStateTracker#startMonitoring(Context, Handler)}.
*/
private static NetworkStateTracker makeWimaxStateTracker(
Context context, Handler trackerHandler) {
// Initialize Wimax
DexClassLoader wimaxClassLoader;
Class wimaxStateTrackerClass = null;
Class wimaxServiceClass = null;
Class wimaxManagerClass;
String wimaxManagerClassName;
String wimaxServiceClassName;
String wimaxStateTrackerClassName;
NetworkStateTracker wimaxStateTracker = null;
boolean isWimaxEnabled = context.getResources().getBoolean(
com.android.internal.R.bool.config_wimaxEnabled);
if (isWimaxEnabled) {
try {
wimaxManagerClassName = context.getResources().getString(
com.android.internal.R.string.config_wimaxManagerClassname);
wimaxServiceClassName = context.getResources().getString(
com.android.internal.R.string.config_wimaxServiceClassname);
wimaxStateTrackerClassName = context.getResources().getString(
com.android.internal.R.string.config_wimaxStateTrackerClassname);
wimaxClassLoader = WimaxHelper.getWimaxClassLoader(context);
try {
wimaxManagerClass = wimaxClassLoader.loadClass(wimaxManagerClassName);
wimaxStateTrackerClass = wimaxClassLoader.loadClass(wimaxStateTrackerClassName);
wimaxServiceClass = wimaxClassLoader.loadClass(wimaxServiceClassName);
} catch (ClassNotFoundException ex) {
loge("Exception finding Wimax classes: " + ex.toString());
return null;
}
} catch(Resources.NotFoundException ex) {
loge("Wimax Resources does not exist!!! ");
return null;
}
try {
if (DBG) log("Starting Wimax Service... ");
Constructor wmxStTrkrConst = wimaxStateTrackerClass.getConstructor
(new Class[] {Context.class, Handler.class});
wimaxStateTracker = (NetworkStateTracker) wmxStTrkrConst.newInstance(
context, trackerHandler);
Constructor wmxSrvConst = wimaxServiceClass.getDeclaredConstructor
(new Class[] {Context.class, wimaxStateTrackerClass});
wmxSrvConst.setAccessible(true);
IBinder svcInvoker = (IBinder)wmxSrvConst.newInstance(context, wimaxStateTracker);
wmxSrvConst.setAccessible(false);
ServiceManager.addService(WimaxManagerConstants.WIMAX_SERVICE, svcInvoker);
} catch(Exception ex) {
loge("Exception creating Wimax classes: " + ex.toString());
return null;
}
} else {
loge("Wimax is not enabled or not added to the network attributes!!! ");
return null;
}
return wimaxStateTracker;
}
/**
* Sets the preferred network.
* @param preference the new preference
*/
public void setNetworkPreference(int preference) {
enforceChangePermission();
mHandler.sendMessage(
mHandler.obtainMessage(EVENT_SET_NETWORK_PREFERENCE, preference, 0));
}
public int getNetworkPreference() {
enforceAccessPermission();
int preference;
synchronized(this) {
preference = mNetworkPreference;
}
return preference;
}
private void handleSetNetworkPreference(int preference) {
if (ConnectivityManager.isNetworkTypeValid(preference) &&
mNetConfigs[preference] != null &&
mNetConfigs[preference].isDefault()) {
if (mNetworkPreference != preference) {
final ContentResolver cr = mContext.getContentResolver();
Settings.Global.putInt(cr, Settings.Global.NETWORK_PREFERENCE, preference);
synchronized(this) {
mNetworkPreference = preference;
}
enforcePreference();
}
}
}
private int getConnectivityChangeDelay() {
final ContentResolver cr = mContext.getContentResolver();
/** Check system properties for the default value then use secure settings value, if any. */
int defaultDelay = SystemProperties.getInt(
"conn." + Settings.Global.CONNECTIVITY_CHANGE_DELAY,
ConnectivityManager.CONNECTIVITY_CHANGE_DELAY_DEFAULT);
return Settings.Global.getInt(cr, Settings.Global.CONNECTIVITY_CHANGE_DELAY,
defaultDelay);
}
private int getPersistedNetworkPreference() {
final ContentResolver cr = mContext.getContentResolver();
final int networkPrefSetting = Settings.Global
.getInt(cr, Settings.Global.NETWORK_PREFERENCE, -1);
return networkPrefSetting;
}
/**
* Make the state of network connectivity conform to the preference settings
* In this method, we only tear down a non-preferred network. Establishing
* a connection to the preferred network is taken care of when we handle
* the disconnect event from the non-preferred network
* (see {@link #handleDisconnect(NetworkInfo)}).
*/
private void enforcePreference() {
if (mNetTrackers[mNetworkPreference].getNetworkInfo().isConnected())
return;
if (!mNetTrackers[mNetworkPreference].isAvailable())
return;
for (int t=0; t <= ConnectivityManager.MAX_RADIO_TYPE; t++) {
if (t != mNetworkPreference && mNetTrackers[t] != null &&
mNetTrackers[t].getNetworkInfo().isConnected()) {
if (DBG) {
log("tearing down " + mNetTrackers[t].getNetworkInfo() +
" in enforcePreference");
}
teardown(mNetTrackers[t]);
}
}
}
private boolean teardown(NetworkStateTracker netTracker) {
if (netTracker.teardown()) {
netTracker.setTeardownRequested(true);
return true;
} else {
return false;
}
}
/**
* Check if UID should be blocked from using the network represented by the
* given {@link NetworkStateTracker}.
*/
private boolean isNetworkBlocked(NetworkStateTracker tracker, int uid) {
final String iface = tracker.getLinkProperties().getInterfaceName();
final boolean networkCostly;
final int uidRules;
synchronized (mRulesLock) {
networkCostly = mMeteredIfaces.contains(iface);
uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
}
if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
return true;
}
// no restrictive rules; network is visible
return false;
}
/**
* Return a filtered {@link NetworkInfo}, potentially marked
* {@link DetailedState#BLOCKED} based on
* {@link #isNetworkBlocked(NetworkStateTracker, int)}.
*/
private NetworkInfo getFilteredNetworkInfo(NetworkStateTracker tracker, int uid) {
NetworkInfo info = tracker.getNetworkInfo();
if (isNetworkBlocked(tracker, uid)) {
// network is blocked; clone and override state
info = new NetworkInfo(info);
info.setDetailedState(DetailedState.BLOCKED, null, null);
}
if (mLockdownTracker != null) {
info = mLockdownTracker.augmentNetworkInfo(info);
}
return info;
}
/**
* Return NetworkInfo for the active (i.e., connected) network interface.
* It is assumed that at most one network is active at a time. If more
* than one is active, it is indeterminate which will be returned.
* @return the info for the active network, or {@code null} if none is
* active
*/
@Override
public NetworkInfo getActiveNetworkInfo() {
enforceAccessPermission();
final int uid = Binder.getCallingUid();
return getNetworkInfo(mActiveDefaultNetwork, uid);
}
/**
* Find the first Provisioning network.
*
* @return NetworkInfo or null if none.
*/
private NetworkInfo getProvisioningNetworkInfo() {
enforceAccessPermission();
// Find the first Provisioning Network
NetworkInfo provNi = null;
for (NetworkInfo ni : getAllNetworkInfo()) {
if (ni.isConnectedToProvisioningNetwork()) {
provNi = ni;
break;
}
}
if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
return provNi;
}
/**
* Find the first Provisioning network or the ActiveDefaultNetwork
* if there is no Provisioning network
*
* @return NetworkInfo or null if none.
*/
@Override
public NetworkInfo getProvisioningOrActiveNetworkInfo() {
enforceAccessPermission();
NetworkInfo provNi = getProvisioningNetworkInfo();
if (provNi == null) {
final int uid = Binder.getCallingUid();
provNi = getNetworkInfo(mActiveDefaultNetwork, uid);
}
if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
return provNi;
}
public NetworkInfo getActiveNetworkInfoUnfiltered() {
enforceAccessPermission();
if (isNetworkTypeValid(mActiveDefaultNetwork)) {
final NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
if (tracker != null) {
return tracker.getNetworkInfo();
}
}
return null;
}
@Override
public NetworkInfo getActiveNetworkInfoForUid(int uid) {
enforceConnectivityInternalPermission();
return getNetworkInfo(mActiveDefaultNetwork, uid);
}
@Override
public NetworkInfo getNetworkInfo(int networkType) {
enforceAccessPermission();
final int uid = Binder.getCallingUid();
return getNetworkInfo(networkType, uid);
}
private NetworkInfo getNetworkInfo(int networkType, int uid) {
NetworkInfo info = null;
if (isNetworkTypeValid(networkType)) {
final NetworkStateTracker tracker = mNetTrackers[networkType];
if (tracker != null) {
info = getFilteredNetworkInfo(tracker, uid);
}
}
return info;
}
@Override
public NetworkInfo[] getAllNetworkInfo() {
enforceAccessPermission();
final int uid = Binder.getCallingUid();
final ArrayList<NetworkInfo> result = Lists.newArrayList();
synchronized (mRulesLock) {
for (NetworkStateTracker tracker : mNetTrackers) {
if (tracker != null) {
result.add(getFilteredNetworkInfo(tracker, uid));
}
}
}
return result.toArray(new NetworkInfo[result.size()]);
}
@Override
public boolean isNetworkSupported(int networkType) {
enforceAccessPermission();
return (isNetworkTypeValid(networkType) && (mNetTrackers[networkType] != null));
}
/**
* Return LinkProperties for the active (i.e., connected) default
* network interface. It is assumed that at most one default network
* is active at a time. If more than one is active, it is indeterminate
* which will be returned.
* @return the ip properties for the active network, or {@code null} if
* none is active
*/
@Override
public LinkProperties getActiveLinkProperties() {
return getLinkProperties(mActiveDefaultNetwork);
}
@Override
public LinkProperties getLinkProperties(int networkType) {
enforceAccessPermission();
if (isNetworkTypeValid(networkType)) {
final NetworkStateTracker tracker = mNetTrackers[networkType];
if (tracker != null) {
return tracker.getLinkProperties();
}
}
return null;
}
@Override
public NetworkState[] getAllNetworkState() {
enforceAccessPermission();
final int uid = Binder.getCallingUid();
final ArrayList<NetworkState> result = Lists.newArrayList();
synchronized (mRulesLock) {
for (NetworkStateTracker tracker : mNetTrackers) {
if (tracker != null) {
final NetworkInfo info = getFilteredNetworkInfo(tracker, uid);
result.add(new NetworkState(
info, tracker.getLinkProperties(), tracker.getLinkCapabilities()));
}
}
}
return result.toArray(new NetworkState[result.size()]);
}
private NetworkState getNetworkStateUnchecked(int networkType) {
if (isNetworkTypeValid(networkType)) {
final NetworkStateTracker tracker = mNetTrackers[networkType];
if (tracker != null) {
return new NetworkState(tracker.getNetworkInfo(), tracker.getLinkProperties(),
tracker.getLinkCapabilities());
}
}
return null;
}
@Override
public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
enforceAccessPermission();
final long token = Binder.clearCallingIdentity();
try {
final NetworkState state = getNetworkStateUnchecked(mActiveDefaultNetwork);
if (state != null) {
try {
return mPolicyManager.getNetworkQuotaInfo(state);
} catch (RemoteException e) {
}
}
return null;
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public boolean isActiveNetworkMetered() {
enforceAccessPermission();
final long token = Binder.clearCallingIdentity();
try {
return isNetworkMeteredUnchecked(mActiveDefaultNetwork);
} finally {
Binder.restoreCallingIdentity(token);
}
}
private boolean isNetworkMeteredUnchecked(int networkType) {
final NetworkState state = getNetworkStateUnchecked(networkType);
if (state != null) {
try {
return mPolicyManager.isNetworkMetered(state);
} catch (RemoteException e) {
}
}
return false;
}
public boolean setRadios(boolean turnOn) {
boolean result = true;
enforceChangePermission();
for (NetworkStateTracker t : mNetTrackers) {
if (t != null) result = t.setRadio(turnOn) && result;
}
return result;
}
public boolean setRadio(int netType, boolean turnOn) {
enforceChangePermission();
if (!ConnectivityManager.isNetworkTypeValid(netType)) {
return false;
}
NetworkStateTracker tracker = mNetTrackers[netType];
return tracker != null && tracker.setRadio(turnOn);
}
private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
@Override
public void interfaceClassDataActivityChanged(String label, boolean active) {
int deviceType = Integer.parseInt(label);
sendDataActivityBroadcast(deviceType, active);
}
};
/**
* Used to notice when the calling process dies so we can self-expire
*
* Also used to know if the process has cleaned up after itself when
* our auto-expire timer goes off. The timer has a link to an object.
*
*/
private class FeatureUser implements IBinder.DeathRecipient {
int mNetworkType;
String mFeature;
IBinder mBinder;
int mPid;
int mUid;
long mCreateTime;
FeatureUser(int type, String feature, IBinder binder) {
super();
mNetworkType = type;
mFeature = feature;
mBinder = binder;
mPid = getCallingPid();
mUid = getCallingUid();
mCreateTime = System.currentTimeMillis();
try {
mBinder.linkToDeath(this, 0);
} catch (RemoteException e) {
binderDied();
}
}
void unlinkDeathRecipient() {
mBinder.unlinkToDeath(this, 0);
}
public void binderDied() {
log("ConnectivityService FeatureUser binderDied(" +
mNetworkType + ", " + mFeature + ", " + mBinder + "), created " +
(System.currentTimeMillis() - mCreateTime) + " mSec ago");
stopUsingNetworkFeature(this, false);
}
public void expire() {
if (VDBG) {
log("ConnectivityService FeatureUser expire(" +
mNetworkType + ", " + mFeature + ", " + mBinder +"), created " +
(System.currentTimeMillis() - mCreateTime) + " mSec ago");
}
stopUsingNetworkFeature(this, false);
}
public boolean isSameUser(FeatureUser u) {
if (u == null) return false;
return isSameUser(u.mPid, u.mUid, u.mNetworkType, u.mFeature);
}
public boolean isSameUser(int pid, int uid, int networkType, String feature) {
if ((mPid == pid) && (mUid == uid) && (mNetworkType == networkType) &&
TextUtils.equals(mFeature, feature)) {
return true;
}
return false;
}
public String toString() {
return "FeatureUser("+mNetworkType+","+mFeature+","+mPid+","+mUid+"), created " +
(System.currentTimeMillis() - mCreateTime) + " mSec ago";
}
}
// javadoc from interface
public int startUsingNetworkFeature(int networkType, String feature,
IBinder binder) {
long startTime = 0;
if (DBG) {
startTime = SystemClock.elapsedRealtime();
}
if (VDBG) {
log("startUsingNetworkFeature for net " + networkType + ": " + feature + ", uid="
+ Binder.getCallingUid());
}
enforceChangePermission();
try {
if (!ConnectivityManager.isNetworkTypeValid(networkType) ||
mNetConfigs[networkType] == null) {
return PhoneConstants.APN_REQUEST_FAILED;
}
FeatureUser f = new FeatureUser(networkType, feature, binder);
// TODO - move this into individual networktrackers
int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
if (mLockdownEnabled) {
// Since carrier APNs usually aren't available from VPN
// endpoint, mark them as unavailable.
return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
}
if (mProtectedNetworks.contains(usedNetworkType)) {
enforceConnectivityInternalPermission();
}
// if UID is restricted, don't allow them to bring up metered APNs
final boolean networkMetered = isNetworkMeteredUnchecked(usedNetworkType);
final int uidRules;
synchronized (mRulesLock) {
uidRules = mUidRules.get(Binder.getCallingUid(), RULE_ALLOW_ALL);
}
if (networkMetered && (uidRules & RULE_REJECT_METERED) != 0) {
return PhoneConstants.APN_REQUEST_FAILED;
}
NetworkStateTracker network = mNetTrackers[usedNetworkType];
if (network != null) {
Integer currentPid = new Integer(getCallingPid());
if (usedNetworkType != networkType) {
NetworkInfo ni = network.getNetworkInfo();
if (ni.isAvailable() == false) {
if (!TextUtils.equals(feature,Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
if (DBG) log("special network not available ni=" + ni.getTypeName());
return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
} else {
// else make the attempt anyway - probably giving REQUEST_STARTED below
if (DBG) {
log("special network not available, but try anyway ni=" +
ni.getTypeName());
}
}
}
int restoreTimer = getRestoreDefaultNetworkDelay(usedNetworkType);
synchronized(this) {
boolean addToList = true;
if (restoreTimer < 0) {
// In case there is no timer is specified for the feature,
// make sure we don't add duplicate entry with the same request.
for (FeatureUser u : mFeatureUsers) {
if (u.isSameUser(f)) {
// Duplicate user is found. Do not add.
addToList = false;
break;
}
}
}
if (addToList) mFeatureUsers.add(f);
if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
// this gets used for per-pid dns when connected
mNetRequestersPids[usedNetworkType].add(currentPid);
}
}
if (restoreTimer >= 0) {
mHandler.sendMessageDelayed(mHandler.obtainMessage(
EVENT_RESTORE_DEFAULT_NETWORK, f), restoreTimer);
}
if ((ni.isConnectedOrConnecting() == true) &&
!network.isTeardownRequested()) {
if (ni.isConnected() == true) {
final long token = Binder.clearCallingIdentity();
try {
// add the pid-specific dns
handleDnsConfigurationChange(usedNetworkType);
if (VDBG) log("special network already active");
} finally {
Binder.restoreCallingIdentity(token);
}
return PhoneConstants.APN_ALREADY_ACTIVE;
}
if (VDBG) log("special network already connecting");
return PhoneConstants.APN_REQUEST_STARTED;
}
// check if the radio in play can make another contact
// assume if cannot for now
if (DBG) {
log("startUsingNetworkFeature reconnecting to " + networkType + ": " +
feature);
}
if (network.reconnect()) {
if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_STARTED");
return PhoneConstants.APN_REQUEST_STARTED;
} else {
if (DBG) log("startUsingNetworkFeature X: return APN_REQUEST_FAILED");
return PhoneConstants.APN_REQUEST_FAILED;
}
} else {
// need to remember this unsupported request so we respond appropriately on stop
synchronized(this) {
mFeatureUsers.add(f);
if (!mNetRequestersPids[usedNetworkType].contains(currentPid)) {
// this gets used for per-pid dns when connected
mNetRequestersPids[usedNetworkType].add(currentPid);
}
}
if (DBG) log("startUsingNetworkFeature X: return -1 unsupported feature.");
return -1;
}
}
if (DBG) log("startUsingNetworkFeature X: return APN_TYPE_NOT_AVAILABLE");
return PhoneConstants.APN_TYPE_NOT_AVAILABLE;
} finally {
if (DBG) {
final long execTime = SystemClock.elapsedRealtime() - startTime;
if (execTime > 250) {
loge("startUsingNetworkFeature took too long: " + execTime + "ms");
} else {
if (VDBG) log("startUsingNetworkFeature took " + execTime + "ms");
}
}
}
}
// javadoc from interface
public int stopUsingNetworkFeature(int networkType, String feature) {
enforceChangePermission();
int pid = getCallingPid();
int uid = getCallingUid();
FeatureUser u = null;
boolean found = false;
synchronized(this) {
for (FeatureUser x : mFeatureUsers) {
if (x.isSameUser(pid, uid, networkType, feature)) {
u = x;
found = true;
break;
}
}
}
if (found && u != null) {
if (VDBG) log("stopUsingNetworkFeature: X");
// stop regardless of how many other time this proc had called start
return stopUsingNetworkFeature(u, true);
} else {
// none found!
if (VDBG) log("stopUsingNetworkFeature: X not a live request, ignoring");
return 1;
}
}
private int stopUsingNetworkFeature(FeatureUser u, boolean ignoreDups) {
int networkType = u.mNetworkType;
String feature = u.mFeature;
int pid = u.mPid;
int uid = u.mUid;
NetworkStateTracker tracker = null;
boolean callTeardown = false; // used to carry our decision outside of sync block
if (VDBG) {
log("stopUsingNetworkFeature: net " + networkType + ": " + feature);
}
if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
if (DBG) {
log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
", net is invalid");
}
return -1;
}
// need to link the mFeatureUsers list with the mNetRequestersPids state in this
// sync block
synchronized(this) {
// check if this process still has an outstanding start request
if (!mFeatureUsers.contains(u)) {
if (VDBG) {
log("stopUsingNetworkFeature: this process has no outstanding requests" +
", ignoring");
}
return 1;
}
u.unlinkDeathRecipient();
mFeatureUsers.remove(mFeatureUsers.indexOf(u));
// If we care about duplicate requests, check for that here.
//
// This is done to support the extension of a request - the app
// can request we start the network feature again and renew the
// auto-shutoff delay. Normal "stop" calls from the app though
// do not pay attention to duplicate requests - in effect the
// API does not refcount and a single stop will counter multiple starts.
if (ignoreDups == false) {
for (FeatureUser x : mFeatureUsers) {
if (x.isSameUser(u)) {
if (VDBG) log("stopUsingNetworkFeature: dup is found, ignoring");
return 1;
}
}
}
// TODO - move to individual network trackers
int usedNetworkType = convertFeatureToNetworkType(networkType, feature);
tracker = mNetTrackers[usedNetworkType];
if (tracker == null) {
if (DBG) {
log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
" no known tracker for used net type " + usedNetworkType);
}
return -1;
}
if (usedNetworkType != networkType) {
Integer currentPid = new Integer(pid);
mNetRequestersPids[usedNetworkType].remove(currentPid);
final long token = Binder.clearCallingIdentity();
try {
reassessPidDns(pid, true);
} finally {
Binder.restoreCallingIdentity(token);
}
flushVmDnsCache();
if (mNetRequestersPids[usedNetworkType].size() != 0) {
if (VDBG) {
log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
" others still using it");
}
return 1;
}
callTeardown = true;
} else {
if (DBG) {
log("stopUsingNetworkFeature: net " + networkType + ": " + feature +
" not a known feature - dropping");
}
}
}
if (callTeardown) {
if (DBG) {
log("stopUsingNetworkFeature: teardown net " + networkType + ": " + feature);
}
tracker.teardown();
return 1;
} else {
return -1;
}
}
/**
* @deprecated use requestRouteToHostAddress instead
*
* Ensure that a network route exists to deliver traffic to the specified
* host via the specified network interface.
* @param networkType the type of the network over which traffic to the
* specified host is to be routed
* @param hostAddress the IP address of the host to which the route is
* desired
* @return {@code true} on success, {@code false} on failure
*/
public boolean requestRouteToHost(int networkType, int hostAddress) {
InetAddress inetAddress = NetworkUtils.intToInetAddress(hostAddress);
if (inetAddress == null) {
return false;
}
return requestRouteToHostAddress(networkType, inetAddress.getAddress());
}
/**
* Ensure that a network route exists to deliver traffic to the specified
* host via the specified network interface.
* @param networkType the type of the network over which traffic to the
* specified host is to be routed
* @param hostAddress the IP address of the host to which the route is
* desired
* @return {@code true} on success, {@code false} on failure
*/
public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
enforceChangePermission();
if (mProtectedNetworks.contains(networkType)) {
enforceConnectivityInternalPermission();
}
if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
return false;
}
NetworkStateTracker tracker = mNetTrackers[networkType];
DetailedState netState = DetailedState.DISCONNECTED;
if (tracker != null) {
netState = tracker.getNetworkInfo().getDetailedState();
}
if ((netState != DetailedState.CONNECTED &&
netState != DetailedState.CAPTIVE_PORTAL_CHECK) ||
tracker.isTeardownRequested()) {
if (VDBG) {
log("requestRouteToHostAddress on down network "
+ "(" + networkType + ") - dropped"
+ " tracker=" + tracker
+ " netState=" + netState
+ " isTeardownRequested="
+ ((tracker != null) ? tracker.isTeardownRequested() : "tracker:null"));
}
return false;
}
final long token = Binder.clearCallingIdentity();
try {
InetAddress addr = InetAddress.getByAddress(hostAddress);
LinkProperties lp = tracker.getLinkProperties();
boolean ok = addRouteToAddress(lp, addr, EXEMPT);
if (DBG) log("requestRouteToHostAddress ok=" + ok);
return ok;
} catch (UnknownHostException e) {
if (DBG) log("requestRouteToHostAddress got " + e.toString());
} finally {
Binder.restoreCallingIdentity(token);
}
if (DBG) log("requestRouteToHostAddress X bottom return false");
return false;
}
private boolean addRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable,
boolean exempt) {
return modifyRoute(p, r, 0, ADD, toDefaultTable, exempt);
}
private boolean removeRoute(LinkProperties p, RouteInfo r, boolean toDefaultTable) {
return modifyRoute(p, r, 0, REMOVE, toDefaultTable, UNEXEMPT);
}
private boolean addRouteToAddress(LinkProperties lp, InetAddress addr, boolean exempt) {
return modifyRouteToAddress(lp, addr, ADD, TO_DEFAULT_TABLE, exempt);
}
private boolean removeRouteToAddress(LinkProperties lp, InetAddress addr) {
return modifyRouteToAddress(lp, addr, REMOVE, TO_DEFAULT_TABLE, UNEXEMPT);
}
private boolean modifyRouteToAddress(LinkProperties lp, InetAddress addr, boolean doAdd,
boolean toDefaultTable, boolean exempt) {
RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
if (bestRoute == null) {
bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
} else {
String iface = bestRoute.getInterface();
if (bestRoute.getGateway().equals(addr)) {
// if there is no better route, add the implied hostroute for our gateway
bestRoute = RouteInfo.makeHostRoute(addr, iface);
} else {
// if we will connect to this through another route, add a direct route
// to it's gateway
bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
}
}
return modifyRoute(lp, bestRoute, 0, doAdd, toDefaultTable, exempt);
}
private boolean modifyRoute(LinkProperties lp, RouteInfo r, int cycleCount, boolean doAdd,
boolean toDefaultTable, boolean exempt) {
if ((lp == null) || (r == null)) {
if (DBG) log("modifyRoute got unexpected null: " + lp + ", " + r);
return false;
}
if (cycleCount > MAX_HOSTROUTE_CYCLE_COUNT) {
loge("Error modifying route - too much recursion");
return false;
}
String ifaceName = r.getInterface();
if(ifaceName == null) {
loge("Error modifying route - no interface name");
return false;
}
if (r.hasGateway()) {
RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), r.getGateway());
if (bestRoute != null) {
if (bestRoute.getGateway().equals(r.getGateway())) {
// if there is no better route, add the implied hostroute for our gateway
bestRoute = RouteInfo.makeHostRoute(r.getGateway(), ifaceName);
} else {
// if we will connect to our gateway through another route, add a direct
// route to it's gateway
bestRoute = RouteInfo.makeHostRoute(r.getGateway(),
bestRoute.getGateway(),
ifaceName);
}
modifyRoute(lp, bestRoute, cycleCount+1, doAdd, toDefaultTable, exempt);
}
}
if (doAdd) {
if (VDBG) log("Adding " + r + " for interface " + ifaceName);
try {
if (toDefaultTable) {
synchronized (mRoutesLock) {
// only track default table - only one apps can effect
mAddedRoutes.add(r);
mNetd.addRoute(ifaceName, r);
if (exempt) {
LinkAddress dest = r.getDestination();
if (!mExemptAddresses.contains(dest)) {
mNetd.setHostExemption(dest);
mExemptAddresses.add(dest);
}
}
}
} else {
mNetd.addSecondaryRoute(ifaceName, r);
}
} catch (Exception e) {
// never crash - catch them all
if (DBG) loge("Exception trying to add a route: " + e);
return false;
}
} else {
// if we remove this one and there are no more like it, then refcount==0 and
// we can remove it from the table
if (toDefaultTable) {
synchronized (mRoutesLock) {
mAddedRoutes.remove(r);
if (mAddedRoutes.contains(r) == false) {
if (VDBG) log("Removing " + r + " for interface " + ifaceName);
try {
mNetd.removeRoute(ifaceName, r);
LinkAddress dest = r.getDestination();
if (mExemptAddresses.contains(dest)) {
mNetd.clearHostExemption(dest);
mExemptAddresses.remove(dest);
}
} catch (Exception e) {
// never crash - catch them all
if (VDBG) loge("Exception trying to remove a route: " + e);
return false;
}
} else {
if (VDBG) log("not removing " + r + " as it's still in use");
}
}
} else {
if (VDBG) log("Removing " + r + " for interface " + ifaceName);
try {
mNetd.removeSecondaryRoute(ifaceName, r);
} catch (Exception e) {
// never crash - catch them all
if (VDBG) loge("Exception trying to remove a route: " + e);
return false;
}
}
}
return true;
}
/**
* @see ConnectivityManager#getMobileDataEnabled()
*/
public boolean getMobileDataEnabled() {
// TODO: This detail should probably be in DataConnectionTracker's
// which is where we store the value and maybe make this
// asynchronous.
enforceAccessPermission();
boolean retVal = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.MOBILE_DATA, 1) == 1;
if (VDBG) log("getMobileDataEnabled returning " + retVal);
return retVal;
}
public void setDataDependency(int networkType, boolean met) {
enforceConnectivityInternalPermission();
mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_DEPENDENCY_MET,
(met ? ENABLED : DISABLED), networkType));
}
private void handleSetDependencyMet(int networkType, boolean met) {
if (mNetTrackers[networkType] != null) {
if (DBG) {
log("handleSetDependencyMet(" + networkType + ", " + met + ")");
}
mNetTrackers[networkType].setDependencyMet(met);
}
}
private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
@Override
public void onUidRulesChanged(int uid, int uidRules) {
// caller is NPMS, since we only register with them
if (LOGD_RULES) {
log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
}
synchronized (mRulesLock) {
// skip update when we've already applied rules
final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
if (oldRules == uidRules) return;
mUidRules.put(uid, uidRules);
}
// TODO: notify UID when it has requested targeted updates
}
@Override
public void onMeteredIfacesChanged(String[] meteredIfaces) {
// caller is NPMS, since we only register with them
if (LOGD_RULES) {
log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
}
synchronized (mRulesLock) {
mMeteredIfaces.clear();
for (String iface : meteredIfaces) {
mMeteredIfaces.add(iface);
}
}
}
@Override
public void onRestrictBackgroundChanged(boolean restrictBackground) {
// caller is NPMS, since we only register with them
if (LOGD_RULES) {
log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
}
// kick off connectivity change broadcast for active network, since
// global background policy change is radical.
final int networkType = mActiveDefaultNetwork;
if (isNetworkTypeValid(networkType)) {
final NetworkStateTracker tracker = mNetTrackers[networkType];
if (tracker != null) {
final NetworkInfo info = tracker.getNetworkInfo();
if (info != null && info.isConnected()) {
sendConnectedBroadcast(info);
}
}
}
}
};
/**
* @see ConnectivityManager#setMobileDataEnabled(boolean)
*/
public void setMobileDataEnabled(boolean enabled) {
enforceChangePermission();
if (DBG) log("setMobileDataEnabled(" + enabled + ")");
mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_MOBILE_DATA,
(enabled ? ENABLED : DISABLED), 0));
}
private void handleSetMobileData(boolean enabled) {
if (mNetTrackers[ConnectivityManager.TYPE_MOBILE] != null) {
if (VDBG) {
log(mNetTrackers[ConnectivityManager.TYPE_MOBILE].toString() + enabled);
}
mNetTrackers[ConnectivityManager.TYPE_MOBILE].setUserDataEnable(enabled);
}
if (mNetTrackers[ConnectivityManager.TYPE_WIMAX] != null) {
if (VDBG) {
log(mNetTrackers[ConnectivityManager.TYPE_WIMAX].toString() + enabled);
}
mNetTrackers[ConnectivityManager.TYPE_WIMAX].setUserDataEnable(enabled);
}
}
@Override
public void setPolicyDataEnable(int networkType, boolean enabled) {
// only someone like NPMS should only be calling us
mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
mHandler.sendMessage(mHandler.obtainMessage(
EVENT_SET_POLICY_DATA_ENABLE, networkType, (enabled ? ENABLED : DISABLED)));
}
private void handleSetPolicyDataEnable(int networkType, boolean enabled) {
if (isNetworkTypeValid(networkType)) {
final NetworkStateTracker tracker = mNetTrackers[networkType];
if (tracker != null) {
tracker.setPolicyDataEnable(enabled);
}
}
}
private void enforceAccessPermission() {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.ACCESS_NETWORK_STATE,
"ConnectivityService");
}
private void enforceChangePermission() {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.CHANGE_NETWORK_STATE,
"ConnectivityService");
}
// TODO Make this a special check when it goes public
private void enforceTetherChangePermission() {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.CHANGE_NETWORK_STATE,
"ConnectivityService");
}
private void enforceTetherAccessPermission() {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.ACCESS_NETWORK_STATE,
"ConnectivityService");
}
private void enforceConnectivityInternalPermission() {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.CONNECTIVITY_INTERNAL,
"ConnectivityService");
}
private void enforceMarkNetworkSocketPermission() {
//Media server special case
if (Binder.getCallingUid() == Process.MEDIA_UID) {
return;
}
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.MARK_NETWORK_SOCKET,
"ConnectivityService");
}
/**
* Handle a {@code DISCONNECTED} event. If this pertains to the non-active
* network, we ignore it. If it is for the active network, we send out a
* broadcast. But first, we check whether it might be possible to connect
* to a different network.
* @param info the {@code NetworkInfo} for the network
*/
private void handleDisconnect(NetworkInfo info) {
int prevNetType = info.getType();
mNetTrackers[prevNetType].setTeardownRequested(false);
// Remove idletimer previously setup in {@code handleConnect}
removeDataActivityTracking(prevNetType);
/*
* If the disconnected network is not the active one, then don't report
* this as a loss of connectivity. What probably happened is that we're
* getting the disconnect for a network that we explicitly disabled
* in accordance with network preference policies.
*/
if (!mNetConfigs[prevNetType].isDefault()) {
List<Integer> pids = mNetRequestersPids[prevNetType];
for (Integer pid : pids) {
// will remove them because the net's no longer connected
// need to do this now as only now do we know the pids and
// can properly null things that are no longer referenced.
reassessPidDns(pid.intValue(), false);
}
}
Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
if (info.isFailover()) {
intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
info.setFailover(false);
}
if (info.getReason() != null) {
intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
}
if (info.getExtraInfo() != null) {
intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
info.getExtraInfo());
}
if (mNetConfigs[prevNetType].isDefault()) {
tryFailover(prevNetType);
if (mActiveDefaultNetwork != -1) {
NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
} else {
mDefaultInetConditionPublished = 0; // we're not connected anymore
intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
}
}
intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
// Reset interface if no other connections are using the same interface
boolean doReset = true;
LinkProperties linkProperties = mNetTrackers[prevNetType].getLinkProperties();
if (linkProperties != null) {
String oldIface = linkProperties.getInterfaceName();
if (TextUtils.isEmpty(oldIface) == false) {
for (NetworkStateTracker networkStateTracker : mNetTrackers) {
if (networkStateTracker == null) continue;
NetworkInfo networkInfo = networkStateTracker.getNetworkInfo();
if (networkInfo.isConnected() && networkInfo.getType() != prevNetType) {
LinkProperties l = networkStateTracker.getLinkProperties();
if (l == null) continue;
if (oldIface.equals(l.getInterfaceName())) {
doReset = false;
break;
}
}
}
}
}
// do this before we broadcast the change
handleConnectivityChange(prevNetType, doReset);
final Intent immediateIntent = new Intent(intent);
immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
sendStickyBroadcast(immediateIntent);
sendStickyBroadcastDelayed(intent, getConnectivityChangeDelay());
/*
* If the failover network is already connected, then immediately send
* out a followup broadcast indicating successful failover
*/
if (mActiveDefaultNetwork != -1) {
sendConnectedBroadcastDelayed(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo(),
getConnectivityChangeDelay());
}
}
private void tryFailover(int prevNetType) {
/*
* If this is a default network, check if other defaults are available.
* Try to reconnect on all available and let them hash it out when
* more than one connects.
*/
if (mNetConfigs[prevNetType].isDefault()) {
if (mActiveDefaultNetwork == prevNetType) {
if (DBG) {
log("tryFailover: set mActiveDefaultNetwork=-1, prevNetType=" + prevNetType);
}
mActiveDefaultNetwork = -1;
}
// don't signal a reconnect for anything lower or equal priority than our
// current connected default
// TODO - don't filter by priority now - nice optimization but risky
// int currentPriority = -1;
// if (mActiveDefaultNetwork != -1) {
// currentPriority = mNetConfigs[mActiveDefaultNetwork].mPriority;
// }
for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
if (checkType == prevNetType) continue;
if (mNetConfigs[checkType] == null) continue;
if (!mNetConfigs[checkType].isDefault()) continue;
if (mNetTrackers[checkType] == null) continue;
// Enabling the isAvailable() optimization caused mobile to not get
// selected if it was in the middle of error handling. Specifically
// a moble connection that took 30 seconds to complete the DEACTIVATE_DATA_CALL
// would not be available and we wouldn't get connected to anything.
// So removing the isAvailable() optimization below for now. TODO: This
// optimization should work and we need to investigate why it doesn't work.
// This could be related to how DEACTIVATE_DATA_CALL is reporting its
// complete before it is really complete.
// if (!mNetTrackers[checkType].isAvailable()) continue;
// if (currentPriority >= mNetConfigs[checkType].mPriority) continue;
NetworkStateTracker checkTracker = mNetTrackers[checkType];
NetworkInfo checkInfo = checkTracker.getNetworkInfo();
if (!checkInfo.isConnectedOrConnecting() || checkTracker.isTeardownRequested()) {
checkInfo.setFailover(true);
checkTracker.reconnect();
}
if (DBG) log("Attempting to switch to " + checkInfo.getTypeName());
}
}
}
public void sendConnectedBroadcast(NetworkInfo info) {
enforceConnectivityInternalPermission();
sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
}
private void sendConnectedBroadcastDelayed(NetworkInfo info, int delayMs) {
sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
sendGeneralBroadcastDelayed(info, CONNECTIVITY_ACTION, delayMs);
}
private void sendInetConditionBroadcast(NetworkInfo info) {
sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
}
private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
if (mLockdownTracker != null) {
info = mLockdownTracker.augmentNetworkInfo(info);
}
Intent intent = new Intent(bcastType);
intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
if (info.isFailover()) {
intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
info.setFailover(false);
}
if (info.getReason() != null) {
intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
}
if (info.getExtraInfo() != null) {
intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
info.getExtraInfo());
}
intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
return intent;
}
private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
sendStickyBroadcast(makeGeneralIntent(info, bcastType));
}
private void sendGeneralBroadcastDelayed(NetworkInfo info, String bcastType, int delayMs) {
sendStickyBroadcastDelayed(makeGeneralIntent(info, bcastType), delayMs);
}
private void sendDataActivityBroadcast(int deviceType, boolean active) {
Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
final long ident = Binder.clearCallingIdentity();
try {
mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
/**
* Called when an attempt to fail over to another network has failed.
* @param info the {@link NetworkInfo} for the failed network
*/
private void handleConnectionFailure(NetworkInfo info) {
mNetTrackers[info.getType()].setTeardownRequested(false);
String reason = info.getReason();
String extraInfo = info.getExtraInfo();
String reasonText;
if (reason == null) {
reasonText = ".";
} else {
reasonText = " (" + reason + ").";
}
loge("Attempt to connect to " + info.getTypeName() + " failed" + reasonText);
Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
if (getActiveNetworkInfo() == null) {
intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
}
if (reason != null) {
intent.putExtra(ConnectivityManager.EXTRA_REASON, reason);
}
if (extraInfo != null) {
intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, extraInfo);
}
if (info.isFailover()) {
intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
info.setFailover(false);
}
if (mNetConfigs[info.getType()].isDefault()) {
tryFailover(info.getType());
if (mActiveDefaultNetwork != -1) {
NetworkInfo switchTo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO, switchTo);
} else {
mDefaultInetConditionPublished = 0;
intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
}
}
intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
final Intent immediateIntent = new Intent(intent);
immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
sendStickyBroadcast(immediateIntent);
sendStickyBroadcast(intent);
/*
* If the failover network is already connected, then immediately send
* out a followup broadcast indicating successful failover
*/
if (mActiveDefaultNetwork != -1) {
sendConnectedBroadcast(mNetTrackers[mActiveDefaultNetwork].getNetworkInfo());
}
}
private void sendStickyBroadcast(Intent intent) {
synchronized(this) {
if (!mSystemReady) {
mInitialBroadcast = new Intent(intent);
}
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
if (VDBG) {
log("sendStickyBroadcast: action=" + intent.getAction());
}
final long ident = Binder.clearCallingIdentity();
try {
mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
}
private void sendStickyBroadcastDelayed(Intent intent, int delayMs) {
if (delayMs <= 0) {
sendStickyBroadcast(intent);
} else {
if (VDBG) {
log("sendStickyBroadcastDelayed: delayMs=" + delayMs + ", action="
+ intent.getAction());
}
mHandler.sendMessageDelayed(mHandler.obtainMessage(
EVENT_SEND_STICKY_BROADCAST_INTENT, intent), delayMs);
}
}
void systemReady() {
mCaptivePortalTracker = CaptivePortalTracker.makeCaptivePortalTracker(mContext, this);
loadGlobalProxy();
synchronized(this) {
mSystemReady = true;
if (mInitialBroadcast != null) {
mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
mInitialBroadcast = null;
}
}
// load the global proxy at startup
mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
// Try bringing up tracker, but if KeyStore isn't ready yet, wait
// for user to unlock device.
if (!updateLockdownVpn()) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
mContext.registerReceiver(mUserPresentReceiver, filter);
}
}
private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Try creating lockdown tracker, since user present usually means
// unlocked keystore.
if (updateLockdownVpn()) {
mContext.unregisterReceiver(this);
}
}
};
private boolean isNewNetTypePreferredOverCurrentNetType(int type) {
if (((type != mNetworkPreference)
&& (mNetConfigs[mActiveDefaultNetwork].priority > mNetConfigs[type].priority))
|| (mNetworkPreference == mActiveDefaultNetwork)) {
return false;
}
return true;
}
private void handleConnect(NetworkInfo info) {
final int newNetType = info.getType();
setupDataActivityTracking(newNetType);
// snapshot isFailover, because sendConnectedBroadcast() resets it
boolean isFailover = info.isFailover();
final NetworkStateTracker thisNet = mNetTrackers[newNetType];
final String thisIface = thisNet.getLinkProperties().getInterfaceName();
if (VDBG) {
log("handleConnect: E newNetType=" + newNetType + " thisIface=" + thisIface
+ " isFailover" + isFailover);
}
// if this is a default net and other default is running
// kill the one not preferred
if (mNetConfigs[newNetType].isDefault()) {
if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != newNetType) {
if (isNewNetTypePreferredOverCurrentNetType(newNetType)) {
// tear down the other
NetworkStateTracker otherNet =
mNetTrackers[mActiveDefaultNetwork];
if (DBG) {
log("Policy requires " + otherNet.getNetworkInfo().getTypeName() +
" teardown");
}
if (!teardown(otherNet)) {
loge("Network declined teardown request");
teardown(thisNet);
return;
}
} else {
// don't accept this one
if (VDBG) {
log("Not broadcasting CONNECT_ACTION " +
"to torn down network " + info.getTypeName());
}
teardown(thisNet);
return;
}
}
synchronized (ConnectivityService.this) {
// have a new default network, release the transition wakelock in a second
// if it's held. The second pause is to allow apps to reconnect over the
// new network
if (mNetTransitionWakeLock.isHeld()) {
mHandler.sendMessageDelayed(mHandler.obtainMessage(
EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
mNetTransitionWakeLockSerialNumber, 0),
1000);
}
}
mActiveDefaultNetwork = newNetType;
// this will cause us to come up initially as unconnected and switching
// to connected after our normal pause unless somebody reports us as reall
// disconnected
mDefaultInetConditionPublished = 0;
mDefaultConnectionSequence++;
mInetConditionChangeInFlight = false;
// Don't do this - if we never sign in stay, grey
//reportNetworkCondition(mActiveDefaultNetwork, 100);
}
thisNet.setTeardownRequested(false);
updateNetworkSettings(thisNet);
updateMtuSizeSettings(thisNet);
handleConnectivityChange(newNetType, false);
sendConnectedBroadcastDelayed(info, getConnectivityChangeDelay());
// notify battery stats service about this network
if (thisIface != null) {
try {
BatteryStatsService.getService().noteNetworkInterfaceType(thisIface, newNetType);
} catch (RemoteException e) {
// ignored; service lives in system_server
}
}
}
private void handleCaptivePortalTrackerCheck(NetworkInfo info) {
if (DBG) log("Captive portal check " + info);
int type = info.getType();
final NetworkStateTracker thisNet = mNetTrackers[type];
if (mNetConfigs[type].isDefault()) {
if (mActiveDefaultNetwork != -1 && mActiveDefaultNetwork != type) {
if (isNewNetTypePreferredOverCurrentNetType(type)) {
if (DBG) log("Captive check on " + info.getTypeName());
mCaptivePortalTracker.detectCaptivePortal(new NetworkInfo(info));
return;
} else {
if (DBG) log("Tear down low priority net " + info.getTypeName());
teardown(thisNet);
return;
}
}
}
if (DBG) log("handleCaptivePortalTrackerCheck: call captivePortalCheckComplete ni=" + info);
thisNet.captivePortalCheckComplete();
}
/** @hide */
@Override
public void captivePortalCheckComplete(NetworkInfo info) {
enforceConnectivityInternalPermission();
if (DBG) log("captivePortalCheckComplete: ni=" + info);
mNetTrackers[info.getType()].captivePortalCheckComplete();
}
/** @hide */
@Override
public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
enforceConnectivityInternalPermission();
if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
}
/**
* Setup data activity tracking for the given network interface.
*
* Every {@code setupDataActivityTracking} should be paired with a
* {@link removeDataActivityTracking} for cleanup.
*/
private void setupDataActivityTracking(int type) {
final NetworkStateTracker thisNet = mNetTrackers[type];
final String iface = thisNet.getLinkProperties().getInterfaceName();
final int timeout;
if (ConnectivityManager.isNetworkTypeMobile(type)) {
timeout = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
0);
// Canonicalize mobile network type
type = ConnectivityManager.TYPE_MOBILE;
} else if (ConnectivityManager.TYPE_WIFI == type) {
timeout = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
0);
} else {
// do not track any other networks
timeout = 0;
}
if (timeout > 0 && iface != null) {
try {
mNetd.addIdleTimer(iface, timeout, Integer.toString(type));
} catch (RemoteException e) {
}
}
}
/**
* Remove data activity tracking when network disconnects.
*/
private void removeDataActivityTracking(int type) {
final NetworkStateTracker net = mNetTrackers[type];
final String iface = net.getLinkProperties().getInterfaceName();
if (iface != null && (ConnectivityManager.isNetworkTypeMobile(type) ||
ConnectivityManager.TYPE_WIFI == type)) {
try {
// the call fails silently if no idletimer setup for this interface
mNetd.removeIdleTimer(iface);
} catch (RemoteException e) {
}
}
}
/**
* After a change in the connectivity state of a network. We're mainly
* concerned with making sure that the list of DNS servers is set up
* according to which networks are connected, and ensuring that the
* right routing table entries exist.
*/
private void handleConnectivityChange(int netType, boolean doReset) {
int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
boolean exempt = ConnectivityManager.isNetworkTypeExempt(netType);
if (VDBG) {
log("handleConnectivityChange: netType=" + netType + " doReset=" + doReset
+ " resetMask=" + resetMask);
}
/*
* If a non-default network is enabled, add the host routes that
* will allow it's DNS servers to be accessed.
*/
handleDnsConfigurationChange(netType);
LinkProperties curLp = mCurrentLinkProperties[netType];
LinkProperties newLp = null;
if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
newLp = mNetTrackers[netType].getLinkProperties();
if (VDBG) {
log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
" doReset=" + doReset + " resetMask=" + resetMask +
"\n curLp=" + curLp +
"\n newLp=" + newLp);
}
if (curLp != null) {
if (curLp.isIdenticalInterfaceName(newLp)) {
CompareResult<LinkAddress> car = curLp.compareAddresses(newLp);
if ((car.removed.size() != 0) || (car.added.size() != 0)) {
for (LinkAddress linkAddr : car.removed) {
if (linkAddr.getAddress() instanceof Inet4Address) {
resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
}
if (linkAddr.getAddress() instanceof Inet6Address) {
resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
}
}
if (DBG) {
log("handleConnectivityChange: addresses changed" +
" linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
"\n car=" + car);
}
} else {
if (DBG) {
log("handleConnectivityChange: address are the same reset per doReset" +
" linkProperty[" + netType + "]:" +
" resetMask=" + resetMask);
}
}
} else {
resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
if (DBG) {
log("handleConnectivityChange: interface not not equivalent reset both" +
" linkProperty[" + netType + "]:" +
" resetMask=" + resetMask);
}
}
}
if (mNetConfigs[netType].isDefault()) {
handleApplyDefaultProxy(newLp.getHttpProxy());
}
} else {
if (VDBG) {
log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
" doReset=" + doReset + " resetMask=" + resetMask +
"\n curLp=" + curLp +
"\n newLp= null");
}
}
mCurrentLinkProperties[netType] = newLp;
boolean resetDns = updateRoutes(newLp, curLp, mNetConfigs[netType].isDefault(), exempt);
if (resetMask != 0 || resetDns) {
if (VDBG) log("handleConnectivityChange: resetting");
if (curLp != null) {
if (VDBG) log("handleConnectivityChange: resetting curLp=" + curLp);
for (String iface : curLp.getAllInterfaceNames()) {
if (TextUtils.isEmpty(iface) == false) {
if (resetMask != 0) {
if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
NetworkUtils.resetConnections(iface, resetMask);
// Tell VPN the interface is down. It is a temporary
// but effective fix to make VPN aware of the change.
if ((resetMask & NetworkUtils.RESET_IPV4_ADDRESSES) != 0) {
synchronized(mVpns) {
for (int i = 0; i < mVpns.size(); i++) {
mVpns.valueAt(i).interfaceStatusChanged(iface, false);
}
}
}
}
if (resetDns) {
flushVmDnsCache();
if (VDBG) log("resetting DNS cache for " + iface);
try {
mNetd.flushInterfaceDnsCache(iface);
} catch (Exception e) {
// never crash - catch them all
if (DBG) loge("Exception resetting dns cache: " + e);
}
}
} else {
loge("Can't reset connection for type "+netType);
}
}
}
}
// Update 464xlat state.
NetworkStateTracker tracker = mNetTrackers[netType];
if (mClat.requiresClat(netType, tracker)) {
// If the connection was previously using clat, but is not using it now, stop the clat
// daemon. Normally, this happens automatically when the connection disconnects, but if
// the disconnect is not reported, or if the connection's LinkProperties changed for
// some other reason (e.g., handoff changes the IP addresses on the link), it would
// still be running. If it's not running, then stopping it is a no-op.
if (Nat464Xlat.isRunningClat(curLp) && !Nat464Xlat.isRunningClat(newLp)) {
mClat.stopClat();
}
// If the link requires clat to be running, then start the daemon now.
if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
mClat.startClat(tracker);
} else {
mClat.stopClat();
}
}
// TODO: Temporary notifying upstread change to Tethering.
// @see bug/4455071
/** Notify TetheringService if interface name has been changed. */
if (TextUtils.equals(mNetTrackers[netType].getNetworkInfo().getReason(),
PhoneConstants.REASON_LINK_PROPERTIES_CHANGED)) {
if (isTetheringSupported()) {
mTethering.handleTetherIfaceChange(mNetTrackers[netType].getNetworkInfo());
}
}
}
/**
* Add and remove routes using the old properties (null if not previously connected),
* new properties (null if becoming disconnected). May even be double null, which
* is a noop.
* Uses isLinkDefault to determine if default routes should be set or conversely if
* host routes should be set to the dns servers
* returns a boolean indicating the routes changed
*/
private boolean updateRoutes(LinkProperties newLp, LinkProperties curLp,
boolean isLinkDefault, boolean exempt) {
Collection<RouteInfo> routesToAdd = null;
CompareResult<InetAddress> dnsDiff = new CompareResult<InetAddress>();
CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
if (curLp != null) {
// check for the delta between the current set and the new
routeDiff = curLp.compareAllRoutes(newLp);
dnsDiff = curLp.compareDnses(newLp);
} else if (newLp != null) {
routeDiff.added = newLp.getAllRoutes();
dnsDiff.added = newLp.getDnses();
}
boolean routesChanged = (routeDiff.removed.size() != 0 || routeDiff.added.size() != 0);
for (RouteInfo r : routeDiff.removed) {
if (isLinkDefault || ! r.isDefaultRoute()) {
if (VDBG) log("updateRoutes: default remove route r=" + r);
removeRoute(curLp, r, TO_DEFAULT_TABLE);
}
if (isLinkDefault == false) {
// remove from a secondary route table
removeRoute(curLp, r, TO_SECONDARY_TABLE);
}
}
if (!isLinkDefault) {
// handle DNS routes
if (routesChanged) {
// routes changed - remove all old dns entries and add new
if (curLp != null) {
for (InetAddress oldDns : curLp.getDnses()) {
removeRouteToAddress(curLp, oldDns);
}
}
if (newLp != null) {
for (InetAddress newDns : newLp.getDnses()) {
addRouteToAddress(newLp, newDns, exempt);
}
}
} else {
// no change in routes, check for change in dns themselves
for (InetAddress oldDns : dnsDiff.removed) {
removeRouteToAddress(curLp, oldDns);
}
for (InetAddress newDns : dnsDiff.added) {
addRouteToAddress(newLp, newDns, exempt);
}
}
}
for (RouteInfo r : routeDiff.added) {
if (isLinkDefault || ! r.isDefaultRoute()) {
addRoute(newLp, r, TO_DEFAULT_TABLE, exempt);
} else {
// add to a secondary route table
addRoute(newLp, r, TO_SECONDARY_TABLE, UNEXEMPT);
// many radios add a default route even when we don't want one.
// remove the default route unless somebody else has asked for it
String ifaceName = newLp.getInterfaceName();
synchronized (mRoutesLock) {
if (!TextUtils.isEmpty(ifaceName) && !mAddedRoutes.contains(r)) {
if (VDBG) log("Removing " + r + " for interface " + ifaceName);
try {
mNetd.removeRoute(ifaceName, r);
} catch (Exception e) {
// never crash - catch them all
if (DBG) loge("Exception trying to remove a route: " + e);
}
}
}
}
}
return routesChanged;
}
/**
* Reads the network specific MTU size from reources.
* and set it on it's iface.
*/
private void updateMtuSizeSettings(NetworkStateTracker nt) {
final String iface = nt.getLinkProperties().getInterfaceName();
final int mtu = nt.getLinkProperties().getMtu();
if (mtu < 68 || mtu > 10000) {
loge("Unexpected mtu value: " + nt);
return;
}
try {
if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
mNetd.setMtu(iface, mtu);
} catch (Exception e) {
Slog.e(TAG, "exception in setMtu()" + e);
}
}
/**
* Reads the network specific TCP buffer sizes from SystemProperties
* net.tcp.buffersize.[default|wifi|umts|edge|gprs] and set them for system
* wide use
*/
private void updateNetworkSettings(NetworkStateTracker nt) {
String key = nt.getTcpBufferSizesPropName();
String bufferSizes = key == null ? null : SystemProperties.get(key);
if (TextUtils.isEmpty(bufferSizes)) {
if (VDBG) log(key + " not found in system properties. Using defaults");
// Setting to default values so we won't be stuck to previous values
key = "net.tcp.buffersize.default";
bufferSizes = SystemProperties.get(key);
}
// Set values in kernel
if (bufferSizes.length() != 0) {
if (VDBG) {
log("Setting TCP values: [" + bufferSizes
+ "] which comes from [" + key + "]");
}
setBufferSize(bufferSizes);
}
}
/**
* Writes TCP buffer sizes to /sys/kernel/ipv4/tcp_[r/w]mem_[min/def/max]
* which maps to /proc/sys/net/ipv4/tcp_rmem and tcpwmem
*
* @param bufferSizes in the format of "readMin, readInitial, readMax,
* writeMin, writeInitial, writeMax"
*/
private void setBufferSize(String bufferSizes) {
try {
String[] values = bufferSizes.split(",");
if (values.length == 6) {
final String prefix = "/sys/kernel/ipv4/tcp_";
FileUtils.stringToFile(prefix + "rmem_min", values[0]);
FileUtils.stringToFile(prefix + "rmem_def", values[1]);
FileUtils.stringToFile(prefix + "rmem_max", values[2]);
FileUtils.stringToFile(prefix + "wmem_min", values[3]);
FileUtils.stringToFile(prefix + "wmem_def", values[4]);
FileUtils.stringToFile(prefix + "wmem_max", values[5]);
} else {
loge("Invalid buffersize string: " + bufferSizes);
}
} catch (IOException e) {
loge("Can't set tcp buffer sizes:" + e);
}
}
/**
* Adjust the per-process dns entries (net.dns<x>.<pid>) based
* on the highest priority active net which this process requested.
* If there aren't any, clear it out
*/
private void reassessPidDns(int pid, boolean doBump)
{
if (VDBG) log("reassessPidDns for pid " + pid);
Integer myPid = new Integer(pid);
for(int i : mPriorityList) {
if (mNetConfigs[i].isDefault()) {
continue;
}
NetworkStateTracker nt = mNetTrackers[i];
if (nt.getNetworkInfo().isConnected() &&
!nt.isTeardownRequested()) {
LinkProperties p = nt.getLinkProperties();
if (p == null) continue;
if (mNetRequestersPids[i].contains(myPid)) {
try {
mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
} catch (Exception e) {
Slog.e(TAG, "exception reasseses pid dns: " + e);
}
return;
}
}
}
// nothing found - delete
try {
mNetd.clearDnsInterfaceForPid(pid);
} catch (Exception e) {
Slog.e(TAG, "exception clear interface from pid: " + e);
}
}
private void flushVmDnsCache() {
/*
* Tell the VMs to toss their DNS caches
*/
Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
/*
* Connectivity events can happen before boot has completed ...
*/
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
final long ident = Binder.clearCallingIdentity();
try {
mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
// Caller must grab mDnsLock.
private void updateDnsLocked(String network, String iface,
Collection<InetAddress> dnses, String domains, boolean defaultDns) {
int last = 0;
if (dnses.size() == 0 && mDefaultDns != null) {
dnses = new ArrayList();
dnses.add(mDefaultDns);
if (DBG) {
loge("no dns provided for " + network + " - using " + mDefaultDns.getHostAddress());
}
}
try {
mNetd.setDnsServersForInterface(iface, NetworkUtils.makeStrings(dnses), domains);
if (defaultDns) {
mNetd.setDefaultInterfaceForDns(iface);
}
for (InetAddress dns : dnses) {
++last;
String key = "net.dns" + last;
String value = dns.getHostAddress();
SystemProperties.set(key, value);
}
for (int i = last + 1; i <= mNumDnsEntries; ++i) {
String key = "net.dns" + i;
SystemProperties.set(key, "");
}
mNumDnsEntries = last;
} catch (Exception e) {
loge("exception setting default dns interface: " + e);
}
}
private void handleDnsConfigurationChange(int netType) {
// add default net's dns entries
NetworkStateTracker nt = mNetTrackers[netType];
if (nt != null && nt.getNetworkInfo().isConnected() && !nt.isTeardownRequested()) {
LinkProperties p = nt.getLinkProperties();
if (p == null) return;
Collection<InetAddress> dnses = p.getDnses();
if (mNetConfigs[netType].isDefault()) {
String network = nt.getNetworkInfo().getTypeName();
synchronized (mDnsLock) {
updateDnsLocked(network, p.getInterfaceName(), dnses, p.getDomains(), true);
}
} else {
try {
mNetd.setDnsServersForInterface(p.getInterfaceName(),
NetworkUtils.makeStrings(dnses), p.getDomains());
} catch (Exception e) {
if (DBG) loge("exception setting dns servers: " + e);
}
// set per-pid dns for attached secondary nets
List<Integer> pids = mNetRequestersPids[netType];
for (Integer pid : pids) {
try {
mNetd.setDnsInterfaceForPid(p.getInterfaceName(), pid);
} catch (Exception e) {
Slog.e(TAG, "exception setting interface for pid: " + e);
}
}
}
flushVmDnsCache();
}
}
private int getRestoreDefaultNetworkDelay(int networkType) {
String restoreDefaultNetworkDelayStr = SystemProperties.get(
NETWORK_RESTORE_DELAY_PROP_NAME);
if(restoreDefaultNetworkDelayStr != null &&
restoreDefaultNetworkDelayStr.length() != 0) {
try {
return Integer.valueOf(restoreDefaultNetworkDelayStr);
} catch (NumberFormatException e) {
}
}
// if the system property isn't set, use the value for the apn type
int ret = RESTORE_DEFAULT_NETWORK_DELAY;
if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
(mNetConfigs[networkType] != null)) {
ret = mNetConfigs[networkType].restoreTime;
}
return ret;
}
@Override
protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
if (mContext.checkCallingOrSelfPermission(
android.Manifest.permission.DUMP)
!= PackageManager.PERMISSION_GRANTED) {
pw.println("Permission Denial: can't dump ConnectivityService " +
"from from pid=" + Binder.getCallingPid() + ", uid=" +
Binder.getCallingUid());
return;
}
// TODO: add locking to get atomic snapshot
pw.println();
for (int i = 0; i < mNetTrackers.length; i++) {
final NetworkStateTracker nst = mNetTrackers[i];
if (nst != null) {
pw.println("NetworkStateTracker for " + getNetworkTypeName(i) + ":");
pw.increaseIndent();
if (nst.getNetworkInfo().isConnected()) {
pw.println("Active network: " + nst.getNetworkInfo().
getTypeName());
}
pw.println(nst.getNetworkInfo());
pw.println(nst.getLinkProperties());
pw.println(nst);
pw.println();
pw.decreaseIndent();
}
}
pw.println("Network Requester Pids:");
pw.increaseIndent();
for (int net : mPriorityList) {
String pidString = net + ": ";
for (Integer pid : mNetRequestersPids[net]) {
pidString = pidString + pid.toString() + ", ";
}
pw.println(pidString);
}
pw.println();
pw.decreaseIndent();
pw.println("FeatureUsers:");
pw.increaseIndent();
for (Object requester : mFeatureUsers) {
pw.println(requester.toString());
}
pw.println();
pw.decreaseIndent();
synchronized (this) {
pw.println("NetworkTranstionWakeLock is currently " +
(mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
}
pw.println();
mTethering.dump(fd, pw, args);
if (mInetLog != null) {
pw.println();
pw.println("Inet condition reports:");
pw.increaseIndent();
for(int i = 0; i < mInetLog.size(); i++) {
pw.println(mInetLog.get(i));
}
pw.decreaseIndent();
}
}
// must be stateless - things change under us.
private class NetworkStateTrackerHandler extends Handler {
public NetworkStateTrackerHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
NetworkInfo info;
switch (msg.what) {
case NetworkStateTracker.EVENT_STATE_CHANGED: {
info = (NetworkInfo) msg.obj;
NetworkInfo.State state = info.getState();
if (VDBG || (state == NetworkInfo.State.CONNECTED) ||
(state == NetworkInfo.State.DISCONNECTED) ||
(state == NetworkInfo.State.SUSPENDED)) {
log("ConnectivityChange for " +
info.getTypeName() + ": " +
state + "/" + info.getDetailedState());
}
// Since mobile has the notion of a network/apn that can be used for
// provisioning we need to check every time we're connected as
// CaptiveProtalTracker won't detected it because DCT doesn't report it
// as connected as ACTION_ANY_DATA_CONNECTION_STATE_CHANGED instead its
// reported as ACTION_DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN. Which
// is received by MDST and sent here as EVENT_STATE_CHANGED.
if (ConnectivityManager.isNetworkTypeMobile(info.getType())
&& (0 != Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.DEVICE_PROVISIONED, 0))
&& (((state == NetworkInfo.State.CONNECTED)
&& (info.getType() == ConnectivityManager.TYPE_MOBILE))
|| info.isConnectedToProvisioningNetwork())) {
log("ConnectivityChange checkMobileProvisioning for"
+ " TYPE_MOBILE or ProvisioningNetwork");
checkMobileProvisioning(CheckMp.MAX_TIMEOUT_MS);
}
EventLogTags.writeConnectivityStateChanged(
info.getType(), info.getSubtype(), info.getDetailedState().ordinal());
if (info.getDetailedState() ==
NetworkInfo.DetailedState.FAILED) {
handleConnectionFailure(info);
} else if (info.getDetailedState() ==
DetailedState.CAPTIVE_PORTAL_CHECK) {
handleCaptivePortalTrackerCheck(info);
} else if (info.isConnectedToProvisioningNetwork()) {
/**
* TODO: Create ConnectivityManager.TYPE_MOBILE_PROVISIONING
* for now its an in between network, its a network that
* is actually a default network but we don't want it to be
* announced as such to keep background applications from
* trying to use it. It turns out that some still try so we
* take the additional step of clearing any default routes
* to the link that may have incorrectly setup by the lower
* levels.
*/
LinkProperties lp = getLinkProperties(info.getType());
if (DBG) {
log("EVENT_STATE_CHANGED: connected to provisioning network, lp=" + lp);
}
// Clear any default routes setup by the radio so
// any activity by applications trying to use this
// connection will fail until the provisioning network
// is enabled.
for (RouteInfo r : lp.getRoutes()) {
removeRoute(lp, r, TO_DEFAULT_TABLE);
}
} else if (state == NetworkInfo.State.DISCONNECTED) {
handleDisconnect(info);
} else if (state == NetworkInfo.State.SUSPENDED) {
// TODO: need to think this over.
// the logic here is, handle SUSPENDED the same as
// DISCONNECTED. The only difference being we are
// broadcasting an intent with NetworkInfo that's
// suspended. This allows the applications an
// opportunity to handle DISCONNECTED and SUSPENDED
// differently, or not.
handleDisconnect(info);
} else if (state == NetworkInfo.State.CONNECTED) {
handleConnect(info);
}
if (mLockdownTracker != null) {
mLockdownTracker.onNetworkInfoChanged(info);
}
break;
}
case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
info = (NetworkInfo) msg.obj;
// TODO: Temporary allowing network configuration
// change not resetting sockets.
// @see bug/4455071
handleConnectivityChange(info.getType(), false);
break;
}
case NetworkStateTracker.EVENT_NETWORK_SUBTYPE_CHANGED: {
info = (NetworkInfo) msg.obj;
int type = info.getType();
updateNetworkSettings(mNetTrackers[type]);
break;
}
}
}
}
private class InternalHandler extends Handler {
public InternalHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
NetworkInfo info;
switch (msg.what) {
case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
String causedBy = null;
synchronized (ConnectivityService.this) {
if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
mNetTransitionWakeLock.isHeld()) {
mNetTransitionWakeLock.release();
causedBy = mNetTransitionWakeLockCausedBy;
}
}
if (causedBy != null) {
log("NetTransition Wakelock for " + causedBy + " released by timeout");
}
break;
}
case EVENT_RESTORE_DEFAULT_NETWORK: {
FeatureUser u = (FeatureUser)msg.obj;
u.expire();
break;
}
case EVENT_INET_CONDITION_CHANGE: {
int netType = msg.arg1;
int condition = msg.arg2;
handleInetConditionChange(netType, condition);
break;
}
case EVENT_INET_CONDITION_HOLD_END: {
int netType = msg.arg1;
int sequence = msg.arg2;
handleInetConditionHoldEnd(netType, sequence);
break;
}
case EVENT_SET_NETWORK_PREFERENCE: {
int preference = msg.arg1;
handleSetNetworkPreference(preference);
break;
}
case EVENT_SET_MOBILE_DATA: {
boolean enabled = (msg.arg1 == ENABLED);
handleSetMobileData(enabled);
break;
}
case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
handleDeprecatedGlobalHttpProxy();
break;
}
case EVENT_SET_DEPENDENCY_MET: {
boolean met = (msg.arg1 == ENABLED);
handleSetDependencyMet(msg.arg2, met);
break;
}
case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Intent intent = (Intent)msg.obj;
sendStickyBroadcast(intent);
break;
}
case EVENT_SET_POLICY_DATA_ENABLE: {
final int networkType = msg.arg1;
final boolean enabled = msg.arg2 == ENABLED;
handleSetPolicyDataEnable(networkType, enabled);
break;
}
case EVENT_VPN_STATE_CHANGED: {
if (mLockdownTracker != null) {
mLockdownTracker.onVpnStateChanged((NetworkInfo) msg.obj);
}
break;
}
case EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: {
int tag = mEnableFailFastMobileDataTag.get();
if (msg.arg1 == tag) {
MobileDataStateTracker mobileDst =
(MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE];
if (mobileDst != null) {
mobileDst.setEnableFailFastMobileData(msg.arg2);
}
} else {
log("EVENT_ENABLE_FAIL_FAST_MOBILE_DATA: stale arg1:" + msg.arg1
+ " != tag:" + tag);
}
break;
}
case EVENT_SAMPLE_INTERVAL_ELAPSED: {
handleNetworkSamplingTimeout();
break;
}
case EVENT_PROXY_HAS_CHANGED: {
handleApplyDefaultProxy((ProxyProperties)msg.obj);
break;
}
}
}
}
// javadoc from interface
public int tether(String iface) {
enforceTetherChangePermission();
if (isTetheringSupported()) {
return mTethering.tether(iface);
} else {
return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
}
}
// javadoc from interface
public int untether(String iface) {
enforceTetherChangePermission();
if (isTetheringSupported()) {
return mTethering.untether(iface);
} else {
return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
}
}
// javadoc from interface
public int getLastTetherError(String iface) {
enforceTetherAccessPermission();
if (isTetheringSupported()) {
return mTethering.getLastTetherError(iface);
} else {
return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
}
}
// TODO - proper iface API for selection by property, inspection, etc
public String[] getTetherableUsbRegexs() {
enforceTetherAccessPermission();
if (isTetheringSupported()) {
return mTethering.getTetherableUsbRegexs();
} else {
return new String[0];
}
}
public String[] getTetherableWifiRegexs() {
enforceTetherAccessPermission();
if (isTetheringSupported()) {
return mTethering.getTetherableWifiRegexs();
} else {
return new String[0];
}
}
public String[] getTetherableBluetoothRegexs() {
enforceTetherAccessPermission();
if (isTetheringSupported()) {
return mTethering.getTetherableBluetoothRegexs();
} else {
return new String[0];
}
}
public int setUsbTethering(boolean enable) {
enforceTetherChangePermission();
if (isTetheringSupported()) {
return mTethering.setUsbTethering(enable);
} else {
return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
}
}
// TODO - move iface listing, queries, etc to new module
// javadoc from interface
public String[] getTetherableIfaces() {
enforceTetherAccessPermission();
return mTethering.getTetherableIfaces();
}
public String[] getTetheredIfaces() {
enforceTetherAccessPermission();
return mTethering.getTetheredIfaces();
}
public String[] getTetheringErroredIfaces() {
enforceTetherAccessPermission();
return mTethering.getErroredIfaces();
}
// if ro.tether.denied = true we default to no tethering
// gservices could set the secure setting to 1 though to enable it on a build where it
// had previously been turned off.
public boolean isTetheringSupported() {
enforceTetherAccessPermission();
int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.TETHER_SUPPORTED, defaultVal) != 0);
return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
mTethering.getTetherableWifiRegexs().length != 0 ||
mTethering.getTetherableBluetoothRegexs().length != 0) &&
mTethering.getUpstreamIfaceTypes().length != 0);
}
// An API NetworkStateTrackers can call when they lose their network.
// This will automatically be cleared after X seconds or a network becomes CONNECTED,
// whichever happens first. The timer is started by the first caller and not
// restarted by subsequent callers.
public void requestNetworkTransitionWakelock(String forWhom) {
enforceConnectivityInternalPermission();
synchronized (this) {
if (mNetTransitionWakeLock.isHeld()) return;
mNetTransitionWakeLockSerialNumber++;
mNetTransitionWakeLock.acquire();
mNetTransitionWakeLockCausedBy = forWhom;
}
mHandler.sendMessageDelayed(mHandler.obtainMessage(
EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
mNetTransitionWakeLockSerialNumber, 0),
mNetTransitionWakeLockTimeout);
return;
}
// 100 percent is full good, 0 is full bad.
public void reportInetCondition(int networkType, int percentage) {
if (VDBG) log("reportNetworkCondition(" + networkType + ", " + percentage + ")");
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.STATUS_BAR,
"ConnectivityService");
if (DBG) {
int pid = getCallingPid();
int uid = getCallingUid();
String s = pid + "(" + uid + ") reports inet is " +
(percentage > 50 ? "connected" : "disconnected") + " (" + percentage + ") on " +
"network Type " + networkType + " at " + GregorianCalendar.getInstance().getTime();
mInetLog.add(s);
while(mInetLog.size() > INET_CONDITION_LOG_MAX_SIZE) {
mInetLog.remove(0);
}
}
mHandler.sendMessage(mHandler.obtainMessage(
EVENT_INET_CONDITION_CHANGE, networkType, percentage));
}
private void handleInetConditionChange(int netType, int condition) {
if (mActiveDefaultNetwork == -1) {
if (DBG) log("handleInetConditionChange: no active default network - ignore");
return;
}
if (mActiveDefaultNetwork != netType) {
if (DBG) log("handleInetConditionChange: net=" + netType +
" != default=" + mActiveDefaultNetwork + " - ignore");
return;
}
if (VDBG) {
log("handleInetConditionChange: net=" +
netType + ", condition=" + condition +
",mActiveDefaultNetwork=" + mActiveDefaultNetwork);
}
mDefaultInetCondition = condition;
int delay;
if (mInetConditionChangeInFlight == false) {
if (VDBG) log("handleInetConditionChange: starting a change hold");
// setup a new hold to debounce this
if (mDefaultInetCondition > 50) {
delay = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.INET_CONDITION_DEBOUNCE_UP_DELAY, 500);
} else {
delay = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.INET_CONDITION_DEBOUNCE_DOWN_DELAY, 3000);
}
mInetConditionChangeInFlight = true;
mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_INET_CONDITION_HOLD_END,
mActiveDefaultNetwork, mDefaultConnectionSequence), delay);
} else {
// we've set the new condition, when this hold ends that will get picked up
if (VDBG) log("handleInetConditionChange: currently in hold - not setting new end evt");
}
}
private void handleInetConditionHoldEnd(int netType, int sequence) {
if (DBG) {
log("handleInetConditionHoldEnd: net=" + netType +
", condition=" + mDefaultInetCondition +
", published condition=" + mDefaultInetConditionPublished);
}
mInetConditionChangeInFlight = false;
if (mActiveDefaultNetwork == -1) {
if (DBG) log("handleInetConditionHoldEnd: no active default network - ignoring");
return;
}
if (mDefaultConnectionSequence != sequence) {
if (DBG) log("handleInetConditionHoldEnd: event hold for obsolete network - ignoring");
return;
}
// TODO: Figure out why this optimization sometimes causes a
// change in mDefaultInetCondition to be missed and the
// UI to not be updated.
//if (mDefaultInetConditionPublished == mDefaultInetCondition) {
// if (DBG) log("no change in condition - aborting");
// return;
//}
NetworkInfo networkInfo = mNetTrackers[mActiveDefaultNetwork].getNetworkInfo();
if (networkInfo.isConnected() == false) {
if (DBG) log("handleInetConditionHoldEnd: default network not connected - ignoring");
return;
}
mDefaultInetConditionPublished = mDefaultInetCondition;
sendInetConditionBroadcast(networkInfo);
return;
}
public ProxyProperties getProxy() {
// this information is already available as a world read/writable jvm property
// so this API change wouldn't have a benifit. It also breaks the passing
// of proxy info to all the JVMs.
// enforceAccessPermission();
synchronized (mProxyLock) {
ProxyProperties ret = mGlobalProxy;
if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
return ret;
}
}
public void setGlobalProxy(ProxyProperties proxyProperties) {
enforceConnectivityInternalPermission();
synchronized (mProxyLock) {
if (proxyProperties == mGlobalProxy) return;
if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
String host = "";
int port = 0;
String exclList = "";
String pacFileUrl = "";
if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
!TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
if (!proxyProperties.isValid()) {
if (DBG)
log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
return;
}
mGlobalProxy = new ProxyProperties(proxyProperties);
host = mGlobalProxy.getHost();
port = mGlobalProxy.getPort();
exclList = mGlobalProxy.getExclusionList();
if (proxyProperties.getPacFileUrl() != null) {
pacFileUrl = proxyProperties.getPacFileUrl();
}
} else {
mGlobalProxy = null;
}
ContentResolver res = mContext.getContentResolver();
final long token = Binder.clearCallingIdentity();
try {
Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
exclList);
Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
} finally {
Binder.restoreCallingIdentity(token);
}
}
if (mGlobalProxy == null) {
proxyProperties = mDefaultProxy;
}
sendProxyBroadcast(proxyProperties);
}
private void loadGlobalProxy() {
ContentResolver res = mContext.getContentResolver();
String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
String exclList = Settings.Global.getString(res,
Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
ProxyProperties proxyProperties;
if (!TextUtils.isEmpty(pacFileUrl)) {
proxyProperties = new ProxyProperties(pacFileUrl);
} else {
proxyProperties = new ProxyProperties(host, port, exclList);
}
if (!proxyProperties.isValid()) {
if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
return;
}
synchronized (mProxyLock) {
mGlobalProxy = proxyProperties;
}
}
}
public ProxyProperties getGlobalProxy() {
// this information is already available as a world read/writable jvm property
// so this API change wouldn't have a benifit. It also breaks the passing
// of proxy info to all the JVMs.
// enforceAccessPermission();
synchronized (mProxyLock) {
return mGlobalProxy;
}
}
private void handleApplyDefaultProxy(ProxyProperties proxy) {
if (proxy != null && TextUtils.isEmpty(proxy.getHost())
&& TextUtils.isEmpty(proxy.getPacFileUrl())) {
proxy = null;
}
synchronized (mProxyLock) {
if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
if (mDefaultProxy == proxy) return; // catches repeated nulls
if (proxy != null && !proxy.isValid()) {
if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
return;
}
mDefaultProxy = proxy;
if (mGlobalProxy != null) return;
if (!mDefaultProxyDisabled) {
sendProxyBroadcast(proxy);
}
}
}
private void handleDeprecatedGlobalHttpProxy() {
String proxy = Settings.Global.getString(mContext.getContentResolver(),
Settings.Global.HTTP_PROXY);
if (!TextUtils.isEmpty(proxy)) {
String data[] = proxy.split(":");
if (data.length == 0) {
return;
}
String proxyHost = data[0];
int proxyPort = 8080;
if (data.length > 1) {
try {
proxyPort = Integer.parseInt(data[1]);
} catch (NumberFormatException e) {
return;
}
}
ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
setGlobalProxy(p);
}
}
private void sendProxyBroadcast(ProxyProperties proxy) {
if (proxy == null) proxy = new ProxyProperties("", 0, "");
if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
if (DBG) log("sending Proxy Broadcast for " + proxy);
Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
final long ident = Binder.clearCallingIdentity();
try {
mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
private static class SettingsObserver extends ContentObserver {
private int mWhat;
private Handler mHandler;
SettingsObserver(Handler handler, int what) {
super(handler);
mHandler = handler;
mWhat = what;
}
void observe(Context context) {
ContentResolver resolver = context.getContentResolver();
resolver.registerContentObserver(Settings.Global.getUriFor(
Settings.Global.HTTP_PROXY), false, this);
}
@Override
public void onChange(boolean selfChange) {
mHandler.obtainMessage(mWhat).sendToTarget();
}
}
private static void log(String s) {
Slog.d(TAG, s);
}
private static void loge(String s) {
Slog.e(TAG, s);
}
int convertFeatureToNetworkType(int networkType, String feature) {
int usedNetworkType = networkType;
if(networkType == ConnectivityManager.TYPE_MOBILE) {
if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_MMS)) {
usedNetworkType = ConnectivityManager.TYPE_MOBILE_MMS;
} else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_SUPL)) {
usedNetworkType = ConnectivityManager.TYPE_MOBILE_SUPL;
} else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN) ||
TextUtils.equals(feature, Phone.FEATURE_ENABLE_DUN_ALWAYS)) {
usedNetworkType = ConnectivityManager.TYPE_MOBILE_DUN;
} else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_HIPRI)) {
usedNetworkType = ConnectivityManager.TYPE_MOBILE_HIPRI;
} else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_FOTA)) {
usedNetworkType = ConnectivityManager.TYPE_MOBILE_FOTA;
} else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_IMS)) {
usedNetworkType = ConnectivityManager.TYPE_MOBILE_IMS;
} else if (TextUtils.equals(feature, Phone.FEATURE_ENABLE_CBS)) {
usedNetworkType = ConnectivityManager.TYPE_MOBILE_CBS;
} else {
Slog.e(TAG, "Can't match any mobile netTracker!");
}
} else if (networkType == ConnectivityManager.TYPE_WIFI) {
if (TextUtils.equals(feature, "p2p")) {
usedNetworkType = ConnectivityManager.TYPE_WIFI_P2P;
} else {
Slog.e(TAG, "Can't match any wifi netTracker!");
}
} else {
Slog.e(TAG, "Unexpected network type");
}
return usedNetworkType;
}
private static <T> T checkNotNull(T value, String message) {
if (value == null) {
throw new NullPointerException(message);
}
return value;
}
/**
* Protect a socket from VPN routing rules. This method is used by
* VpnBuilder and not available in ConnectivityManager. Permissions
* are checked in Vpn class.
* @hide
*/
@Override
public boolean protectVpn(ParcelFileDescriptor socket) {
throwIfLockdownEnabled();
try {
int type = mActiveDefaultNetwork;
int user = UserHandle.getUserId(Binder.getCallingUid());
if (ConnectivityManager.isNetworkTypeValid(type) && mNetTrackers[type] != null) {
synchronized(mVpns) {
mVpns.get(user).protect(socket,
mNetTrackers[type].getLinkProperties().getInterfaceName());
}
return true;
}
} catch (Exception e) {
// ignore
} finally {
try {
socket.close();
} catch (Exception e) {
// ignore
}
}
return false;
}
/**
* Prepare for a VPN application. This method is used by VpnDialogs
* and not available in ConnectivityManager. Permissions are checked
* in Vpn class.
* @hide
*/
@Override
public boolean prepareVpn(String oldPackage, String newPackage) {
throwIfLockdownEnabled();
int user = UserHandle.getUserId(Binder.getCallingUid());
synchronized(mVpns) {
return mVpns.get(user).prepare(oldPackage, newPackage);
}
}
@Override
public void markSocketAsUser(ParcelFileDescriptor socket, int uid) {
enforceMarkNetworkSocketPermission();
final long token = Binder.clearCallingIdentity();
try {
int mark = mNetd.getMarkForUid(uid);
// Clear the mark on the socket if no mark is needed to prevent socket reuse issues
if (mark == -1) {
mark = 0;
}
NetworkUtils.markSocket(socket.getFd(), mark);
} catch (RemoteException e) {
} finally {
Binder.restoreCallingIdentity(token);
}
}
/**
* Configure a TUN interface and return its file descriptor. Parameters
* are encoded and opaque to this class. This method is used by VpnBuilder
* and not available in ConnectivityManager. Permissions are checked in
* Vpn class.
* @hide
*/
@Override
public ParcelFileDescriptor establishVpn(VpnConfig config) {
throwIfLockdownEnabled();
int user = UserHandle.getUserId(Binder.getCallingUid());
synchronized(mVpns) {
return mVpns.get(user).establish(config);
}
}
/**
* Start legacy VPN, controlling native daemons as needed. Creates a
* secondary thread to perform connection work, returning quickly.
*/
@Override
public void startLegacyVpn(VpnProfile profile) {
throwIfLockdownEnabled();
final LinkProperties egress = getActiveLinkProperties();
if (egress == null) {
throw new IllegalStateException("Missing active network connection");
}
int user = UserHandle.getUserId(Binder.getCallingUid());
synchronized(mVpns) {
mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
}
}
/**
* Return the information of the ongoing legacy VPN. This method is used
* by VpnSettings and not available in ConnectivityManager. Permissions
* are checked in Vpn class.
* @hide
*/
@Override
public LegacyVpnInfo getLegacyVpnInfo() {
throwIfLockdownEnabled();
int user = UserHandle.getUserId(Binder.getCallingUid());
synchronized(mVpns) {
return mVpns.get(user).getLegacyVpnInfo();
}
}
/**
* Returns the information of the ongoing VPN. This method is used by VpnDialogs and
* not available in ConnectivityManager.
* Permissions are checked in Vpn class.
* @hide
*/
@Override
public VpnConfig getVpnConfig() {
int user = UserHandle.getUserId(Binder.getCallingUid());
synchronized(mVpns) {
return mVpns.get(user).getVpnConfig();
}
}
/**
* Callback for VPN subsystem. Currently VPN is not adapted to the service
* through NetworkStateTracker since it works differently. For example, it
* needs to override DNS servers but never takes the default routes. It
* relies on another data network, and it could keep existing connections
* alive after reconnecting, switching between networks, or even resuming
* from deep sleep. Calls from applications should be done synchronously
* to avoid race conditions. As these are all hidden APIs, refactoring can
* be done whenever a better abstraction is developed.
*/
public class VpnCallback {
private VpnCallback() {
}
public void onStateChanged(NetworkInfo info) {
mHandler.obtainMessage(EVENT_VPN_STATE_CHANGED, info).sendToTarget();
}
public void override(String iface, List<String> dnsServers, List<String> searchDomains) {
if (dnsServers == null) {
restore();
return;
}
// Convert DNS servers into addresses.
List<InetAddress> addresses = new ArrayList<InetAddress>();
for (String address : dnsServers) {
// Double check the addresses and remove invalid ones.
try {
addresses.add(InetAddress.parseNumericAddress(address));
} catch (Exception e) {
// ignore
}
}
if (addresses.isEmpty()) {
restore();
return;
}
// Concatenate search domains into a string.
StringBuilder buffer = new StringBuilder();
if (searchDomains != null) {
for (String domain : searchDomains) {
buffer.append(domain).append(' ');
}
}
String domains = buffer.toString().trim();
// Apply DNS changes.
synchronized (mDnsLock) {
updateDnsLocked("VPN", iface, addresses, domains, false);
}
// Temporarily disable the default proxy (not global).
synchronized (mProxyLock) {
mDefaultProxyDisabled = true;
if (mGlobalProxy == null && mDefaultProxy != null) {
sendProxyBroadcast(null);
}
}
// TODO: support proxy per network.
}
public void restore() {
synchronized (mProxyLock) {
mDefaultProxyDisabled = false;
if (mGlobalProxy == null && mDefaultProxy != null) {
sendProxyBroadcast(mDefaultProxy);
}
}
}
public void protect(ParcelFileDescriptor socket) {
try {
final int mark = mNetd.getMarkForProtect();
NetworkUtils.markSocket(socket.getFd(), mark);
} catch (RemoteException e) {
}
}
public void setRoutes(String interfaze, List<RouteInfo> routes) {
for (RouteInfo route : routes) {
try {
mNetd.setMarkedForwardingRoute(interfaze, route);
} catch (RemoteException e) {
}
}
}
public void setMarkedForwarding(String interfaze) {
try {
mNetd.setMarkedForwarding(interfaze);
} catch (RemoteException e) {
}
}
public void clearMarkedForwarding(String interfaze) {
try {
mNetd.clearMarkedForwarding(interfaze);
} catch (RemoteException e) {
}
}
public void addUserForwarding(String interfaze, int uid, boolean forwardDns) {
int uidStart = uid * UserHandle.PER_USER_RANGE;
int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
addUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
}
public void clearUserForwarding(String interfaze, int uid, boolean forwardDns) {
int uidStart = uid * UserHandle.PER_USER_RANGE;
int uidEnd = uidStart + UserHandle.PER_USER_RANGE - 1;
clearUidForwarding(interfaze, uidStart, uidEnd, forwardDns);
}
public void addUidForwarding(String interfaze, int uidStart, int uidEnd,
boolean forwardDns) {
try {
mNetd.setUidRangeRoute(interfaze,uidStart, uidEnd);
if (forwardDns) mNetd.setDnsInterfaceForUidRange(interfaze, uidStart, uidEnd);
} catch (RemoteException e) {
}
}
public void clearUidForwarding(String interfaze, int uidStart, int uidEnd,
boolean forwardDns) {
try {
mNetd.clearUidRangeRoute(interfaze, uidStart, uidEnd);
if (forwardDns) mNetd.clearDnsInterfaceForUidRange(uidStart, uidEnd);
} catch (RemoteException e) {
}
}
}
@Override
public boolean updateLockdownVpn() {
if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
return false;
}
// Tear down existing lockdown if profile was removed
mLockdownEnabled = LockdownVpnTracker.isEnabled();
if (mLockdownEnabled) {
if (!mKeyStore.isUnlocked()) {
Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
return false;
}
final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
final VpnProfile profile = VpnProfile.decode(
profileName, mKeyStore.get(Credentials.VPN + profileName));
int user = UserHandle.getUserId(Binder.getCallingUid());
synchronized(mVpns) {
setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
profile));
}
} else {
setLockdownTracker(null);
}
return true;
}
/**
* Internally set new {@link LockdownVpnTracker}, shutting down any existing
* {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
*/
private void setLockdownTracker(LockdownVpnTracker tracker) {
// Shutdown any existing tracker
final LockdownVpnTracker existing = mLockdownTracker;
mLockdownTracker = null;
if (existing != null) {
existing.shutdown();
}
try {
if (tracker != null) {
mNetd.setFirewallEnabled(true);
mNetd.setFirewallInterfaceRule("lo", true);
mLockdownTracker = tracker;
mLockdownTracker.init();
} else {
mNetd.setFirewallEnabled(false);
}
} catch (RemoteException e) {
// ignored; NMS lives inside system_server
}
}
private void throwIfLockdownEnabled() {
if (mLockdownEnabled) {
throw new IllegalStateException("Unavailable in lockdown mode");
}
}
public void supplyMessenger(int networkType, Messenger messenger) {
enforceConnectivityInternalPermission();
if (isNetworkTypeValid(networkType) && mNetTrackers[networkType] != null) {
mNetTrackers[networkType].supplyMessenger(messenger);
}
}
public int findConnectionTypeForIface(String iface) {
enforceConnectivityInternalPermission();
if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
for (NetworkStateTracker tracker : mNetTrackers) {
if (tracker != null) {
LinkProperties lp = tracker.getLinkProperties();
if (lp != null && iface.equals(lp.getInterfaceName())) {
return tracker.getNetworkInfo().getType();
}
}
}
return ConnectivityManager.TYPE_NONE;
}
/**
* Have mobile data fail fast if enabled.
*
* @param enabled DctConstants.ENABLED/DISABLED
*/
private void setEnableFailFastMobileData(int enabled) {
int tag;
if (enabled == DctConstants.ENABLED) {
tag = mEnableFailFastMobileDataTag.incrementAndGet();
} else {
tag = mEnableFailFastMobileDataTag.get();
}
mHandler.sendMessage(mHandler.obtainMessage(EVENT_ENABLE_FAIL_FAST_MOBILE_DATA, tag,
enabled));
}
private boolean isMobileDataStateTrackerReady() {
MobileDataStateTracker mdst =
(MobileDataStateTracker) mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
return (mdst != null) && (mdst.isReady());
}
/**
* The ResultReceiver resultCode for checkMobileProvisioning (CMP_RESULT_CODE)
*/
/**
* No connection was possible to the network.
* This is NOT a warm sim.
*/
private static final int CMP_RESULT_CODE_NO_CONNECTION = 0;
/**
* A connection was made to the internet, all is well.
* This is NOT a warm sim.
*/
private static final int CMP_RESULT_CODE_CONNECTABLE = 1;
/**
* A connection was made but no dns server was available to resolve a name to address.
* This is NOT a warm sim since provisioning network is supported.
*/
private static final int CMP_RESULT_CODE_NO_DNS = 2;
/**
* A connection was made but could not open a TCP connection.
* This is NOT a warm sim since provisioning network is supported.
*/
private static final int CMP_RESULT_CODE_NO_TCP_CONNECTION = 3;
/**
* A connection was made but there was a redirection, we appear to be in walled garden.
* This is an indication of a warm sim on a mobile network such as T-Mobile.
*/
private static final int CMP_RESULT_CODE_REDIRECTED = 4;
/**
* The mobile network is a provisioning network.
* This is an indication of a warm sim on a mobile network such as AT&T.
*/
private static final int CMP_RESULT_CODE_PROVISIONING_NETWORK = 5;
private AtomicBoolean mIsCheckingMobileProvisioning = new AtomicBoolean(false);
@Override
public int checkMobileProvisioning(int suggestedTimeOutMs) {
int timeOutMs = -1;
if (DBG) log("checkMobileProvisioning: E suggestedTimeOutMs=" + suggestedTimeOutMs);
enforceConnectivityInternalPermission();
final long token = Binder.clearCallingIdentity();
try {
timeOutMs = suggestedTimeOutMs;
if (suggestedTimeOutMs > CheckMp.MAX_TIMEOUT_MS) {
timeOutMs = CheckMp.MAX_TIMEOUT_MS;
}
// Check that mobile networks are supported
if (!isNetworkSupported(ConnectivityManager.TYPE_MOBILE)
|| !isNetworkSupported(ConnectivityManager.TYPE_MOBILE_HIPRI)) {
if (DBG) log("checkMobileProvisioning: X no mobile network");
return timeOutMs;
}
// If we're already checking don't do it again
// TODO: Add a queue of results...
if (mIsCheckingMobileProvisioning.getAndSet(true)) {
if (DBG) log("checkMobileProvisioning: X already checking ignore for the moment");
return timeOutMs;
}
// Start off with mobile notification off
setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
CheckMp checkMp = new CheckMp(mContext, this);
CheckMp.CallBack cb = new CheckMp.CallBack() {
@Override
void onComplete(Integer result) {
if (DBG) log("CheckMp.onComplete: result=" + result);
NetworkInfo ni =
mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI].getNetworkInfo();
switch(result) {
case CMP_RESULT_CODE_CONNECTABLE:
case CMP_RESULT_CODE_NO_CONNECTION:
case CMP_RESULT_CODE_NO_DNS:
case CMP_RESULT_CODE_NO_TCP_CONNECTION: {
if (DBG) log("CheckMp.onComplete: ignore, connected or no connection");
break;
}
case CMP_RESULT_CODE_REDIRECTED: {
if (DBG) log("CheckMp.onComplete: warm sim");
String url = getMobileProvisioningUrl();
if (TextUtils.isEmpty(url)) {
url = getMobileRedirectedProvisioningUrl();
}
if (TextUtils.isEmpty(url) == false) {
if (DBG) log("CheckMp.onComplete: warm (redirected), url=" + url);
setProvNotificationVisible(true,
ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
url);
} else {
if (DBG) log("CheckMp.onComplete: warm (redirected), no url");
}
break;
}
case CMP_RESULT_CODE_PROVISIONING_NETWORK: {
String url = getMobileProvisioningUrl();
if (TextUtils.isEmpty(url) == false) {
if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), url=" + url);
setProvNotificationVisible(true,
ConnectivityManager.TYPE_MOBILE_HIPRI, ni.getExtraInfo(),
url);
} else {
if (DBG) log("CheckMp.onComplete: warm (no dns/tcp), no url");
}
break;
}
default: {
loge("CheckMp.onComplete: ignore unexpected result=" + result);
break;
}
}
mIsCheckingMobileProvisioning.set(false);
}
};
CheckMp.Params params =
new CheckMp.Params(checkMp.getDefaultUrl(), timeOutMs, cb);
if (DBG) log("checkMobileProvisioning: params=" + params);
checkMp.execute(params);
} finally {
Binder.restoreCallingIdentity(token);
if (DBG) log("checkMobileProvisioning: X");
}
return timeOutMs;
}
static class CheckMp extends
AsyncTask<CheckMp.Params, Void, Integer> {
private static final String CHECKMP_TAG = "CheckMp";
// adb shell setprop persist.checkmp.testfailures 1 to enable testing failures
private static boolean mTestingFailures;
// Choosing 4 loops as half of them will use HTTPS and the other half HTTP
private static final int MAX_LOOPS = 4;
// Number of milli-seconds to complete all of the retires
public static final int MAX_TIMEOUT_MS = 60000;
// The socket should retry only 5 seconds, the default is longer
private static final int SOCKET_TIMEOUT_MS = 5000;
// Sleep time for network errors
private static final int NET_ERROR_SLEEP_SEC = 3;
// Sleep time for network route establishment
private static final int NET_ROUTE_ESTABLISHMENT_SLEEP_SEC = 3;
// Short sleep time for polling :(
private static final int POLLING_SLEEP_SEC = 1;
private Context mContext;
private ConnectivityService mCs;
private TelephonyManager mTm;
private Params mParams;
/**
* Parameters for AsyncTask.execute
*/
static class Params {
private String mUrl;
private long mTimeOutMs;
private CallBack mCb;
Params(String url, long timeOutMs, CallBack cb) {
mUrl = url;
mTimeOutMs = timeOutMs;
mCb = cb;
}
@Override
public String toString() {
return "{" + " url=" + mUrl + " mTimeOutMs=" + mTimeOutMs + " mCb=" + mCb + "}";
}
}
// As explained to me by Brian Carlstrom and Kenny Root, Certificates can be
// issued by name or ip address, for Google its by name so when we construct
// this HostnameVerifier we'll pass the original Uri and use it to verify
// the host. If the host name in the original uril fails we'll test the
// hostname parameter just incase things change.
static class CheckMpHostnameVerifier implements HostnameVerifier {
Uri mOrgUri;
CheckMpHostnameVerifier(Uri orgUri) {
mOrgUri = orgUri;
}
@Override
public boolean verify(String hostname, SSLSession session) {
HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
String orgUriHost = mOrgUri.getHost();
boolean retVal = hv.verify(orgUriHost, session) || hv.verify(hostname, session);
if (DBG) {
log("isMobileOk: hostnameVerify retVal=" + retVal + " hostname=" + hostname
+ " orgUriHost=" + orgUriHost);
}
return retVal;
}
}
/**
* The call back object passed in Params. onComplete will be called
* on the main thread.
*/
abstract static class CallBack {
// Called on the main thread.
abstract void onComplete(Integer result);
}
public CheckMp(Context context, ConnectivityService cs) {
if (Build.IS_DEBUGGABLE) {
mTestingFailures =
SystemProperties.getInt("persist.checkmp.testfailures", 0) == 1;
} else {
mTestingFailures = false;
}
mContext = context;
mCs = cs;
// Setup access to TelephonyService we'll be using.
mTm = (TelephonyManager) mContext.getSystemService(
Context.TELEPHONY_SERVICE);
}
/**
* Get the default url to use for the test.
*/
public String getDefaultUrl() {
// See http://go/clientsdns for usage approval
String server = Settings.Global.getString(mContext.getContentResolver(),
Settings.Global.CAPTIVE_PORTAL_SERVER);
if (server == null) {
server = "clients3.google.com";
}
return "http://" + server + "/generate_204";
}
/**
* Detect if its possible to connect to the http url. DNS based detection techniques
* do not work at all hotspots. The best way to check is to perform a request to
* a known address that fetches the data we expect.
*/
private synchronized Integer isMobileOk(Params params) {
Integer result = CMP_RESULT_CODE_NO_CONNECTION;
Uri orgUri = Uri.parse(params.mUrl);
Random rand = new Random();
mParams = params;
if (mCs.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false) {
result = CMP_RESULT_CODE_NO_CONNECTION;
log("isMobileOk: X not mobile capable result=" + result);
return result;
}
// See if we've already determined we've got a provisioning connection,
// if so we don't need to do anything active.
MobileDataStateTracker mdstDefault = (MobileDataStateTracker)
mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE];
boolean isDefaultProvisioning = mdstDefault.isProvisioningNetwork();
log("isMobileOk: isDefaultProvisioning=" + isDefaultProvisioning);
MobileDataStateTracker mdstHipri = (MobileDataStateTracker)
mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
boolean isHipriProvisioning = mdstHipri.isProvisioningNetwork();
log("isMobileOk: isHipriProvisioning=" + isHipriProvisioning);
if (isDefaultProvisioning || isHipriProvisioning) {
result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
log("isMobileOk: X default || hipri is provisioning result=" + result);
return result;
}
try {
// Continue trying to connect until time has run out
long endTime = SystemClock.elapsedRealtime() + params.mTimeOutMs;
if (!mCs.isMobileDataStateTrackerReady()) {
// Wait for MobileDataStateTracker to be ready.
if (DBG) log("isMobileOk: mdst is not ready");
while(SystemClock.elapsedRealtime() < endTime) {
if (mCs.isMobileDataStateTrackerReady()) {
// Enable fail fast as we'll do retries here and use a
// hipri connection so the default connection stays active.
if (DBG) log("isMobileOk: mdst ready, enable fail fast of mobile data");
mCs.setEnableFailFastMobileData(DctConstants.ENABLED);
break;
}
sleep(POLLING_SLEEP_SEC);
}
}
log("isMobileOk: start hipri url=" + params.mUrl);
// First wait until we can start using hipri
Binder binder = new Binder();
while(SystemClock.elapsedRealtime() < endTime) {
int ret = mCs.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
Phone.FEATURE_ENABLE_HIPRI, binder);
if ((ret == PhoneConstants.APN_ALREADY_ACTIVE)
|| (ret == PhoneConstants.APN_REQUEST_STARTED)) {
log("isMobileOk: hipri started");
break;
}
if (VDBG) log("isMobileOk: hipri not started yet");
result = CMP_RESULT_CODE_NO_CONNECTION;
sleep(POLLING_SLEEP_SEC);
}
// Continue trying to connect until time has run out
while(SystemClock.elapsedRealtime() < endTime) {
try {
// Wait for hipri to connect.
// TODO: Don't poll and handle situation where hipri fails
// because default is retrying. See b/9569540
NetworkInfo.State state = mCs
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
if (state != NetworkInfo.State.CONNECTED) {
if (true/*VDBG*/) {
log("isMobileOk: not connected ni=" +
mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
}
sleep(POLLING_SLEEP_SEC);
result = CMP_RESULT_CODE_NO_CONNECTION;
continue;
}
// Hipri has started check if this is a provisioning url
MobileDataStateTracker mdst = (MobileDataStateTracker)
mCs.mNetTrackers[ConnectivityManager.TYPE_MOBILE_HIPRI];
if (mdst.isProvisioningNetwork()) {
result = CMP_RESULT_CODE_PROVISIONING_NETWORK;
if (DBG) log("isMobileOk: X isProvisioningNetwork result=" + result);
return result;
} else {
if (DBG) log("isMobileOk: isProvisioningNetwork is false, continue");
}
// Get of the addresses associated with the url host. We need to use the
// address otherwise HttpURLConnection object will use the name to get
// the addresses and will try every address but that will bypass the
// route to host we setup and the connection could succeed as the default
// interface might be connected to the internet via wifi or other interface.
InetAddress[] addresses;
try {
addresses = InetAddress.getAllByName(orgUri.getHost());
} catch (UnknownHostException e) {
result = CMP_RESULT_CODE_NO_DNS;
log("isMobileOk: X UnknownHostException result=" + result);
return result;
}
log("isMobileOk: addresses=" + inetAddressesToString(addresses));
// Get the type of addresses supported by this link
LinkProperties lp = mCs.getLinkProperties(
ConnectivityManager.TYPE_MOBILE_HIPRI);
boolean linkHasIpv4 = lp.hasIPv4Address();
boolean linkHasIpv6 = lp.hasIPv6Address();
log("isMobileOk: linkHasIpv4=" + linkHasIpv4
+ " linkHasIpv6=" + linkHasIpv6);
final ArrayList<InetAddress> validAddresses =
new ArrayList<InetAddress>(addresses.length);
for (InetAddress addr : addresses) {
if (((addr instanceof Inet4Address) && linkHasIpv4) ||
((addr instanceof Inet6Address) && linkHasIpv6)) {
validAddresses.add(addr);
}
}
if (validAddresses.size() == 0) {
return CMP_RESULT_CODE_NO_CONNECTION;
}
int addrTried = 0;
while (true) {
// Loop through at most MAX_LOOPS valid addresses or until
// we run out of time
if (addrTried++ >= MAX_LOOPS) {
log("isMobileOk: too many loops tried - giving up");
break;
}
if (SystemClock.elapsedRealtime() >= endTime) {
log("isMobileOk: spend too much time - giving up");
break;
}
InetAddress hostAddr = validAddresses.get(rand.nextInt(
validAddresses.size()));
// Make a route to host so we check the specific interface.
if (mCs.requestRouteToHostAddress(ConnectivityManager.TYPE_MOBILE_HIPRI,
hostAddr.getAddress())) {
// Wait a short time to be sure the route is established ??
log("isMobileOk:"
+ " wait to establish route to hostAddr=" + hostAddr);
sleep(NET_ROUTE_ESTABLISHMENT_SLEEP_SEC);
} else {
log("isMobileOk:"
+ " could not establish route to hostAddr=" + hostAddr);
// Wait a short time before the next attempt
sleep(NET_ERROR_SLEEP_SEC);
continue;
}
// Rewrite the url to have numeric address to use the specific route
// using http for half the attempts and https for the other half.
// Doing https first and http second as on a redirected walled garden
// such as t-mobile uses we get a SocketTimeoutException: "SSL
// handshake timed out" which we declare as
// CMP_RESULT_CODE_NO_TCP_CONNECTION. We could change this, but by
// having http second we will be using logic used for some time.
URL newUrl;
String scheme = (addrTried <= (MAX_LOOPS/2)) ? "https" : "http";
newUrl = new URL(scheme, hostAddr.getHostAddress(),
orgUri.getPath());
log("isMobileOk: newUrl=" + newUrl);
HttpURLConnection urlConn = null;
try {
// Open the connection set the request headers and get the response
urlConn = (HttpURLConnection)newUrl.openConnection(
java.net.Proxy.NO_PROXY);
if (scheme.equals("https")) {
((HttpsURLConnection)urlConn).setHostnameVerifier(
new CheckMpHostnameVerifier(orgUri));
}
urlConn.setInstanceFollowRedirects(false);
urlConn.setConnectTimeout(SOCKET_TIMEOUT_MS);
urlConn.setReadTimeout(SOCKET_TIMEOUT_MS);
urlConn.setUseCaches(false);
urlConn.setAllowUserInteraction(false);
// Set the "Connection" to "Close" as by default "Keep-Alive"
// is used which is useless in this case.
urlConn.setRequestProperty("Connection", "close");
int responseCode = urlConn.getResponseCode();
// For debug display the headers
Map<String, List<String>> headers = urlConn.getHeaderFields();
log("isMobileOk: headers=" + headers);
// Close the connection
urlConn.disconnect();
urlConn = null;
if (mTestingFailures) {
// Pretend no connection, this tests using http and https
result = CMP_RESULT_CODE_NO_CONNECTION;
log("isMobileOk: TESTING_FAILURES, pretend no connction");
continue;
}
if (responseCode == 204) {
// Return
result = CMP_RESULT_CODE_CONNECTABLE;
log("isMobileOk: X got expected responseCode=" + responseCode
+ " result=" + result);
return result;
} else {
// Retry to be sure this was redirected, we've gotten
// occasions where a server returned 200 even though
// the device didn't have a "warm" sim.
log("isMobileOk: not expected responseCode=" + responseCode);
// TODO - it would be nice in the single-address case to do
// another DNS resolve here, but flushing the cache is a bit
// heavy-handed.
result = CMP_RESULT_CODE_REDIRECTED;
}
} catch (Exception e) {
log("isMobileOk: HttpURLConnection Exception" + e);
result = CMP_RESULT_CODE_NO_TCP_CONNECTION;
if (urlConn != null) {
urlConn.disconnect();
urlConn = null;
}
sleep(NET_ERROR_SLEEP_SEC);
continue;
}
}
log("isMobileOk: X loops|timed out result=" + result);
return result;
} catch (Exception e) {
log("isMobileOk: Exception e=" + e);
continue;
}
}
log("isMobileOk: timed out");
} finally {
log("isMobileOk: F stop hipri");
mCs.setEnableFailFastMobileData(DctConstants.DISABLED);
mCs.stopUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE,
Phone.FEATURE_ENABLE_HIPRI);
// Wait for hipri to disconnect.
long endTime = SystemClock.elapsedRealtime() + 5000;
while(SystemClock.elapsedRealtime() < endTime) {
NetworkInfo.State state = mCs
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI).getState();
if (state != NetworkInfo.State.DISCONNECTED) {
if (VDBG) {
log("isMobileOk: connected ni=" +
mCs.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_HIPRI));
}
sleep(POLLING_SLEEP_SEC);
continue;
}
}
log("isMobileOk: X result=" + result);
}
return result;
}
@Override
protected Integer doInBackground(Params... params) {
return isMobileOk(params[0]);
}
@Override
protected void onPostExecute(Integer result) {
log("onPostExecute: result=" + result);
if ((mParams != null) && (mParams.mCb != null)) {
mParams.mCb.onComplete(result);
}
}
private String inetAddressesToString(InetAddress[] addresses) {
StringBuffer sb = new StringBuffer();
boolean firstTime = true;
for(InetAddress addr : addresses) {
if (firstTime) {
firstTime = false;
} else {
sb.append(",");
}
sb.append(addr);
}
return sb.toString();
}
private void printNetworkInfo() {
boolean hasIccCard = mTm.hasIccCard();
int simState = mTm.getSimState();
log("hasIccCard=" + hasIccCard
+ " simState=" + simState);
NetworkInfo[] ni = mCs.getAllNetworkInfo();
if (ni != null) {
log("ni.length=" + ni.length);
for (NetworkInfo netInfo: ni) {
log("netInfo=" + netInfo.toString());
}
} else {
log("no network info ni=null");
}
}
/**
* Sleep for a few seconds then return.
* @param seconds
*/
private static void sleep(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void log(String s) {
Slog.d(ConnectivityService.TAG, "[" + CHECKMP_TAG + "] " + s);
}
}
// TODO: Move to ConnectivityManager and make public?
private static final String CONNECTED_TO_PROVISIONING_NETWORK_ACTION =
"com.android.server.connectivityservice.CONNECTED_TO_PROVISIONING_NETWORK_ACTION";
private BroadcastReceiver mProvisioningReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(CONNECTED_TO_PROVISIONING_NETWORK_ACTION)) {
handleMobileProvisioningAction(intent.getStringExtra("EXTRA_URL"));
}
}
};
private void handleMobileProvisioningAction(String url) {
// Notication mark notification as not visible
setProvNotificationVisible(false, ConnectivityManager.TYPE_MOBILE_HIPRI, null, null);
// If provisioning network handle as a special case,
// otherwise launch browser with the intent directly.
NetworkInfo ni = getProvisioningNetworkInfo();
if ((ni != null) && ni.isConnectedToProvisioningNetwork()) {
if (DBG) log("handleMobileProvisioningAction: on provisioning network");
MobileDataStateTracker mdst = (MobileDataStateTracker)
mNetTrackers[ConnectivityManager.TYPE_MOBILE];
mdst.enableMobileProvisioning(url);
} else {
if (DBG) log("handleMobileProvisioningAction: on default network");
Intent newIntent = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN,
Intent.CATEGORY_APP_BROWSER);
newIntent.setData(Uri.parse(url));
newIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
Intent.FLAG_ACTIVITY_NEW_TASK);
try {
mContext.startActivity(newIntent);
} catch (ActivityNotFoundException e) {
loge("handleMobileProvisioningAction: startActivity failed" + e);
}
}
}
private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
private volatile boolean mIsNotificationVisible = false;
private void setProvNotificationVisible(boolean visible, int networkType, String extraInfo,
String url) {
if (DBG) {
log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
+ " extraInfo=" + extraInfo + " url=" + url);
}
Resources r = Resources.getSystem();
NotificationManager notificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
if (visible) {
CharSequence title;
CharSequence details;
int icon;
Intent intent;
Notification notification = new Notification();
switch (networkType) {
case ConnectivityManager.TYPE_WIFI:
title = r.getString(R.string.wifi_available_sign_in, 0);
details = r.getString(R.string.network_available_sign_in_detailed,
extraInfo);
icon = R.drawable.stat_notify_wifi_in_range;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
Intent.FLAG_ACTIVITY_NEW_TASK);
notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
break;
case ConnectivityManager.TYPE_MOBILE:
case ConnectivityManager.TYPE_MOBILE_HIPRI:
title = r.getString(R.string.network_available_sign_in, 0);
// TODO: Change this to pull from NetworkInfo once a printable
// name has been added to it
details = mTelephonyManager.getNetworkOperatorName();
icon = R.drawable.stat_notify_rssi_in_range;
intent = new Intent(CONNECTED_TO_PROVISIONING_NETWORK_ACTION);
intent.putExtra("EXTRA_URL", url);
intent.setFlags(0);
notification.contentIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
break;
default:
title = r.getString(R.string.network_available_sign_in, 0);
details = r.getString(R.string.network_available_sign_in_detailed,
extraInfo);
icon = R.drawable.stat_notify_rssi_in_range;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT |
Intent.FLAG_ACTIVITY_NEW_TASK);
notification.contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
break;
}
notification.when = 0;
notification.icon = icon;
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.tickerText = title;
notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
try {
notificationManager.notify(NOTIFICATION_ID, networkType, notification);
} catch (NullPointerException npe) {
loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
npe.printStackTrace();
}
} else {
try {
notificationManager.cancel(NOTIFICATION_ID, networkType);
} catch (NullPointerException npe) {
loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
npe.printStackTrace();
}
}
mIsNotificationVisible = visible;
}
/** Location to an updatable file listing carrier provisioning urls.
* An example:
*
* <?xml version="1.0" encoding="utf-8"?>
* <provisioningUrls>
* <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
* <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
* </provisioningUrls>
*/
private static final String PROVISIONING_URL_PATH =
"/data/misc/radio/provisioning_urls.xml";
private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
/** XML tag for root element. */
private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
/** XML tag for individual url */
private static final String TAG_PROVISIONING_URL = "provisioningUrl";
/** XML tag for redirected url */
private static final String TAG_REDIRECTED_URL = "redirectedUrl";
/** XML attribute for mcc */
private static final String ATTR_MCC = "mcc";
/** XML attribute for mnc */
private static final String ATTR_MNC = "mnc";
private static final int REDIRECTED_PROVISIONING = 1;
private static final int PROVISIONING = 2;
private String getProvisioningUrlBaseFromFile(int type) {
FileReader fileReader = null;
XmlPullParser parser = null;
Configuration config = mContext.getResources().getConfiguration();
String tagType;
switch (type) {
case PROVISIONING:
tagType = TAG_PROVISIONING_URL;
break;
case REDIRECTED_PROVISIONING:
tagType = TAG_REDIRECTED_URL;
break;
default:
throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
type);
}
try {
fileReader = new FileReader(mProvisioningUrlFile);
parser = Xml.newPullParser();
parser.setInput(fileReader);
XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
while (true) {
XmlUtils.nextElement(parser);
String element = parser.getName();
if (element == null) break;
if (element.equals(tagType)) {
String mcc = parser.getAttributeValue(null, ATTR_MCC);
try {
if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
String mnc = parser.getAttributeValue(null, ATTR_MNC);
if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
parser.next();
if (parser.getEventType() == XmlPullParser.TEXT) {
return parser.getText();
}
}
}
} catch (NumberFormatException e) {
loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
}
}
}
return null;
} catch (FileNotFoundException e) {
loge("Carrier Provisioning Urls file not found");
} catch (XmlPullParserException e) {
loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
} catch (IOException e) {
loge("I/O exception reading Carrier Provisioning Urls file: " + e);
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {}
}
}
return null;
}
@Override
public String getMobileRedirectedProvisioningUrl() {
enforceConnectivityInternalPermission();
String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
if (TextUtils.isEmpty(url)) {
url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
}
return url;
}
@Override
public String getMobileProvisioningUrl() {
enforceConnectivityInternalPermission();
String url = getProvisioningUrlBaseFromFile(PROVISIONING);
if (TextUtils.isEmpty(url)) {
url = mContext.getResources().getString(R.string.mobile_provisioning_url);
log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
} else {
log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
}
// populate the iccid, imei and phone number in the provisioning url.
if (!TextUtils.isEmpty(url)) {
String phoneNumber = mTelephonyManager.getLine1Number();
if (TextUtils.isEmpty(phoneNumber)) {
phoneNumber = "0000000000";
}
url = String.format(url,
mTelephonyManager.getSimSerialNumber() /* ICCID */,
mTelephonyManager.getDeviceId() /* IMEI */,
phoneNumber /* Phone numer */);
}
return url;
}
@Override
public void setProvisioningNotificationVisible(boolean visible, int networkType,
String extraInfo, String url) {
enforceConnectivityInternalPermission();
setProvNotificationVisible(visible, networkType, extraInfo, url);
}
@Override
public void setAirplaneMode(boolean enable) {
enforceConnectivityInternalPermission();
final long ident = Binder.clearCallingIdentity();
try {
final ContentResolver cr = mContext.getContentResolver();
Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", enable);
mContext.sendBroadcast(intent);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
private void onUserStart(int userId) {
synchronized(mVpns) {
Vpn userVpn = mVpns.get(userId);
if (userVpn != null) {
loge("Starting user already has a VPN");
return;
}
userVpn = new Vpn(mContext, mVpnCallback, mNetd, this, userId);
mVpns.put(userId, userVpn);
userVpn.startMonitoring(mContext, mTrackerHandler);
}
}
private void onUserStop(int userId) {
synchronized(mVpns) {
Vpn userVpn = mVpns.get(userId);
if (userVpn == null) {
loge("Stopping user has no VPN");
return;
}
mVpns.delete(userId);
}
}
private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
if (userId == UserHandle.USER_NULL) return;
if (Intent.ACTION_USER_STARTING.equals(action)) {
onUserStart(userId);
} else if (Intent.ACTION_USER_STOPPING.equals(action)) {
onUserStop(userId);
}
}
};
@Override
public LinkQualityInfo getLinkQualityInfo(int networkType) {
enforceAccessPermission();
if (isNetworkTypeValid(networkType)) {
return mNetTrackers[networkType].getLinkQualityInfo();
} else {
return null;
}
}
@Override
public LinkQualityInfo getActiveLinkQualityInfo() {
enforceAccessPermission();
if (isNetworkTypeValid(mActiveDefaultNetwork)) {
return mNetTrackers[mActiveDefaultNetwork].getLinkQualityInfo();
} else {
return null;
}
}
@Override
public LinkQualityInfo[] getAllLinkQualityInfo() {
enforceAccessPermission();
final ArrayList<LinkQualityInfo> result = Lists.newArrayList();
for (NetworkStateTracker tracker : mNetTrackers) {
if (tracker != null) {
LinkQualityInfo li = tracker.getLinkQualityInfo();
if (li != null) {
result.add(li);
}
}
}
return result.toArray(new LinkQualityInfo[result.size()]);
}
/* Infrastructure for network sampling */
private void handleNetworkSamplingTimeout() {
log("Sampling interval elapsed, updating statistics ..");
// initialize list of interfaces ..
Map<String, SamplingDataTracker.SamplingSnapshot> mapIfaceToSample =
new HashMap<String, SamplingDataTracker.SamplingSnapshot>();
for (NetworkStateTracker tracker : mNetTrackers) {
if (tracker != null) {
String ifaceName = tracker.getNetworkInterfaceName();
if (ifaceName != null) {
mapIfaceToSample.put(ifaceName, null);
}
}
}
// Read samples for all interfaces
SamplingDataTracker.getSamplingSnapshots(mapIfaceToSample);
// process samples for all networks
for (NetworkStateTracker tracker : mNetTrackers) {
if (tracker != null) {
String ifaceName = tracker.getNetworkInterfaceName();
SamplingDataTracker.SamplingSnapshot ss = mapIfaceToSample.get(ifaceName);
if (ss != null) {
// end the previous sampling cycle
tracker.stopSampling(ss);
// start a new sampling cycle ..
tracker.startSampling(ss);
}
}
}
log("Done.");
int samplingIntervalInSeconds = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.CONNECTIVITY_SAMPLING_INTERVAL_IN_SECONDS,
DEFAULT_SAMPLING_INTERVAL_IN_SECONDS);
if (DBG) log("Setting timer for " + String.valueOf(samplingIntervalInSeconds) + "seconds");
setAlarm(samplingIntervalInSeconds * 1000, mSampleIntervalElapsedIntent);
}
void setAlarm(int timeoutInMilliseconds, PendingIntent intent) {
long wakeupTime = SystemClock.elapsedRealtime() + timeoutInMilliseconds;
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime, intent);
}
}
| [
"mchnet3@gmail.com"
] | mchnet3@gmail.com |
dbce5209d198c5744f4afa93189ce25fc7d9c41e | c86cef7e3bcd57c31b42703d83e5aaabaf59a7b1 | /src/sortingalgorithm/SortCompare.java | 60b5803def5819f58aa9b0d518ce484a78cbe908 | [] | no_license | gkj/data-structure-algorithm-java | 7398c05424d268daadcfd11b7b3a1ff8f92be2e5 | 3854f9ab88074a50bb6b10ef3ee3aedbc40aecce | refs/heads/master | 2021-01-21T13:57:39.450594 | 2016-05-29T18:35:17 | 2016-05-29T18:35:17 | 53,750,963 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,558 | java | package sortingalgorithm;
import java.util.Arrays;
import util.StdRandom;
import util.Stopwatch;
public class SortCompare
{
public static double time(String alg, Double[] a)
{
Stopwatch sw = new Stopwatch();
if (alg.equals("Insertion"))
Insertion.sort(a);
else if (alg.equals("InsertionX"))
InsertionX.sort(a);
else if (alg.equals("BinaryInsertion"))
BinaryInsertion.sort(a);
else if (alg.equals("Selection"))
Selection.sort(a);
else if (alg.equals("Bubble"))
Bubble.sort(a);
else if (alg.equals("Shell"))
Shell.sort(a);
else if (alg.equals("Merge"))
Merge.sort(a);
else if (alg.equals("MergeX"))
MergeX.sort(a);
else if (alg.equals("MergeBU"))
MergeBU.sort(a);
else if (alg.equals("Quick"))
Quick.sort(a);
else if (alg.equals("Quick3way"))
Quick3Way.sort(a);
else if (alg.equals("QuickX"))
QuickX.sort(a);
else if (alg.equals("Heap"))
Heap.sort(a);
else if (alg.equals("System"))
Arrays.sort(a);
else
throw new IllegalArgumentException("Invalid algorithm: " + alg);
return sw.elapsedTime();
}
// Use alg to sort T random arrays of length N.
public static double timeRandomInput(String alg, int N, int T)
{
double total = 0.0;
Double[] a = new Double[N];
// Perform one experiment (generate and sort an array).
for (int t = 0; t < T; t++)
{
for (int i = 0; i < N; i++)
a[i] = StdRandom.uniform();
total += time(alg, a);
}
return total;
}
// Use alg to sort T random arrays of length N.
public static double timeSortedInput(String alg, int N, int T)
{
double total = 0.0;
Double[] a = new Double[N];
// Perform one experiment (generate and sort an array).
for (int t = 0; t < T; t++)
{
for (int i = 0; i < N; i++)
a[i] = 1.0 * i;
total += time(alg, a);
}
return total;
}
public static void main(String[] args)
{
String alg1 = args[0];
String alg2 = args[1];
int N = Integer.parseInt(args[2]);
int T = Integer.parseInt(args[3]);
double time1, time2;
if (args.length == 5 && args[4].equals("sorted"))
{
time1 = timeSortedInput(alg1, N, T); // Total for alg1.
time2 = timeSortedInput(alg2, N, T); // Total for alg2.
}
else
{
time1 = timeRandomInput(alg1, N, T); // Total for alg1.
time2 = timeRandomInput(alg2, N, T); // Total for alg2.
}
System.out.printf("For %d random Doubles\n %s is", N, alg1);
System.out.printf(" %.1f times faster than %s\n", time2 / time1, alg2);
}
}
| [
"Gilang Kusuma Jati@DESKTOP-LE1SNSK"
] | Gilang Kusuma Jati@DESKTOP-LE1SNSK |
55e2bc68bfaeab7e66f963d352d77ad7abf5f6f5 | 41e38d0675ff0f45cbbd769e932348446604a276 | /app/src/androidTest/java/id/ac/poliban/mi/maya/registrasimahasiswa/ExampleInstrumentedTest.java | 4e2697773f90d008b956fb8f0bf3afeb3f313145 | [] | no_license | mayadiahatikasari/registrasimahasiswa | 1ba859fc66ca8972e2f2d2e7f5002b8abe301708 | 23d9b8580bd4198b9eff0a01f8b01b52202577a8 | refs/heads/master | 2020-12-28T16:20:31.534198 | 2020-02-05T08:36:46 | 2020-02-05T08:36:46 | 238,403,345 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 753 | java | package id.ac.poliban.mi.maya.registrasimahasiswa;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("id.ac.poliban.mi.maya.registrasimahasiswa", appContext.getPackageName());
}
}
| [
"mayadiahatikasari@gmail.com"
] | mayadiahatikasari@gmail.com |
e531f412439062ea148c7c2087a9d7830a7f70dc | e0d52bbf5d1b657afb07795bf456e8e680302980 | /ModelibraWicket/src/org/modelibra/wicket/container/DmPageableListView.java | c074b49453de0179b944c320ad7774e30821a753 | [
"Apache-2.0"
] | permissive | youp911/modelibra | acc391da16ab6b14616cd7bda094506a05414b0f | 00387bd9f1f82df3b7d844650e5a57d2060a2ec7 | refs/heads/master | 2021-01-25T09:59:19.388394 | 2011-11-24T21:46:26 | 2011-11-24T21:46:26 | 42,008,889 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,441 | java | /*
* Modelibra
*
* 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.modelibra.wicket.container;
import java.util.List;
import org.apache.wicket.markup.html.list.PageableListView;
import org.apache.wicket.model.PropertyModel;
import org.modelibra.IEntities;
import org.modelibra.wicket.security.AppSession;
import org.modelibra.wicket.util.LocalizedText;
import org.modelibra.wicket.view.View;
import org.modelibra.wicket.view.ViewModel;
/**
* Dm pageable list view.
*
* @author Dzenan Ridjanovic
* @author Vedad Kirlic
* @version 2008-09-30
*/
@SuppressWarnings("serial")
public abstract class DmPageableListView extends PageableListView {
/**
* Constructs a dmLite pageable list view.
*
* @param wicketId
* Wicket id
* @param list
* list
* @param pageBlockSize
* page block size
*/
public DmPageableListView(final String wicketId, final List<?> list,
final int pageBlockSize) {
super(wicketId, list, pageBlockSize);
}
/**
* Constructs a dmLite pageable list view.
*
* @param wicketId
* Wicket id
* @param entities
* entities
* @param pageBlockSize
* page block size
*/
public DmPageableListView(final String wicketId,
final IEntities<?> entities, final int pageBlockSize) {
super(wicketId, new PropertyModel(entities, "entityList"),
pageBlockSize);
}
/**
* Constructs a dmLite pageable list view.
*
* @param viewModel
* view model
* @param view
* view
* @param pageBlockSize
* page block size
*/
public DmPageableListView(final ViewModel viewModel, final View view,
final int pageBlockSize) {
super(view.getWicketId(), new PropertyModel(viewModel.getEntities(),
"list"), pageBlockSize);
}
/**
* Gets an application session.
*
* @return application session
*/
public AppSession getAppSession() {
return (AppSession) getSession();
}
/**
* Adds an error based on the error key.
*
* @param key
* error key
*/
protected void addErrorByKey(String key) {
String validationError = LocalizedText.getText(this, key);
error(validationError);
}
/**
* Adds errors based on error keys.
*
* @param entities
* entities
*/
protected void addErrorsByKeys(IEntities<?> entities) {
List<String> errorKeys = entities.getErrors().getKeyList();
for (String errorKey : errorKeys) {
String errorMsg = LocalizedText.getErrorMessage(this, errorKey);
error(errorMsg);
}
}
/**
* Adds errors.
*
* @param entities
* entities
*/
protected void addErrors(IEntities<?> entities) {
List<String> errorMsgs = entities.getErrors().getErrorList();
for (String errorMsg : errorMsgs) {
error(errorMsg);
}
}
}
| [
"dzenanr@c25eb2fc-9753-11de-83f8-39e71e4dc75d"
] | dzenanr@c25eb2fc-9753-11de-83f8-39e71e4dc75d |
db158c96769cabfbdbdc417bb41027838d0aa098 | 12996535b07b6565a3eccb7d92dacdee064e45ae | /src/Cmd.java | 157c1482dce8bf0912b649d72c7690598b180168 | [] | no_license | cricsY/Monitor | 31f202d12baaa54730cf1769314f9b7085672065 | f95fcba6e09ff7adea5eb9df82168f9be6727baa | refs/heads/master | 2020-07-24T07:11:03.605336 | 2019-09-11T15:14:31 | 2019-09-11T15:14:31 | 207,841,006 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,600 | java | import java.io.*;
import java.util.*;
public class Cmd {
//暂存所有的计算机名称
private List<String> computerNameList = new ArrayList<>();
public String getRemoteComputerName(List<String> Ips, String ip) {
if (Ips == null) {
Util.record(ConstantParameter.RemoteComputerPath, ip + ".xml", new Date().toString() + ":0" + " users!");
return null;
}
String returnString = new String();
StringBuilder msg = new StringBuilder();
msg.append(new Date().toString() + ":" + Ips.size() + " users!");
//用来存储所有查询线程
List<Thread> threads = new ArrayList<>();
//多线程查询计算机名称
for (String s : Ips) {
String temp = Main.IpAndComputerNameCache.get(s);
if (temp != null) { //调试信息
System.out.println(s + "->" + temp + "缓存命中"); //调试信息
computerNameList.add(temp);
} //调试信息
if (temp == null) { //没有缓存则调用命令行查询
cmdQueryRunnable runnable = new cmdQueryRunnable(s, Ips);
Thread thread = new Thread(runnable);
thread.start();
threads.add(thread);
}
}
try {
//同步所有查询线程
for (Thread s : threads) {
s.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
for (String s : computerNameList) {
returnString = returnString + s.toUpperCase() + " "; //转换成大写
msg.append("<" + s + "> ");
}
msg.append("\r\n");
Util.record(ConstantParameter.RemoteComputerPath, ip + ".xml", msg.toString());
return returnString;
}
private class cmdQueryRunnable implements Runnable {
private String ipElement;
private List<String> ipList;
cmdQueryRunnable(String string, List<String> ipList) {
ipElement = string;
this.ipList = ipList;
}
@Override
public void run() {
try {
String command = "nbtstat -a " + ipElement;
String line = null, temp = ipElement, computerName = null;
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
InputStream inputStream = process.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//用来打断卡死进程
protectRunnable timerRunnable = new protectRunnable(process, Thread.currentThread());
Thread timerThread = new Thread(timerRunnable);
timerThread.start();
while ((line = bufferedReader.readLine()) != null) {
if (line.trim().startsWith("---")) {
int count = 0;
//在该while循环中取得计算机名并赋值给computerName,如果computerName为null,则未查询到计算机名
while ((line = bufferedReader.readLine().trim()) != null) {
temp = line.split("[ ]{1,}")[0];
if (++count > 30 || temp.startsWith("MAC") || temp == null) {
System.out.println(ipElement + "未找到");
break;
}
if (temp.startsWith("CHINA")) {
continue;
}
computerName = temp;
System.out.println(ipElement + "读取" + count + "行");
break;
}
break;
}
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
//根据不同情况将计算机名或IP地址填入数据
if (computerName == null) {
computerNameList.add(ipElement);
Main.IpAndComputerNameCache.put(ipElement, ipElement);
} else {
computerNameList.add(computerName);
Main.IpAndComputerNameCache.put(ipElement, computerName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class protectRunnable implements Runnable {
private Thread thread;
private Process process;
protectRunnable(Process process, Thread thread) {
this.process = process;
this.thread = thread;
}
@Override
public void run() {
try {
Thread.currentThread().sleep(ConstantParameter.CmdMaxTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (thread.isAlive()) {
System.out.println(thread.getName() + "强制打断!");
process.destroy();
}
}
}
} | [
"474910631@qq.com"
] | 474910631@qq.com |
af569b635c94a9acecd1e788eb7d6beca6ba3e94 | d764cac36392234190fe852e5c834828bee5d925 | /android/app/src/main/java/com/rnnpmcompat/MainActivity.java | 7d12945a38432a00ab1c733ec8677a5820fd0dd1 | [] | no_license | vespakoen/RNNPMCompat | 3819b4887ebca455990854cf889da2642acf4ed4 | e9c5a2465f58cf6549655f7a58f1d7439c1b253e | refs/heads/master | 2021-01-10T02:00:51.358463 | 2016-04-11T18:26:30 | 2016-04-11T18:26:30 | 55,945,041 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,036 | java | package com.rnnpmcompat;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "RNNPMCompat";
}
/**
* Returns whether dev mode should be enabled.
* This enables e.g. the dev menu.
*/
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage()
);
}
}
| [
"k.schmeets@gmail.com"
] | k.schmeets@gmail.com |
1def0b1411192e77057b14e77b9fb2bec2540f83 | d676303d357a7abdf060f63664d10ec118739a1f | /src/main/java/com/guoguo/fengyulou/constant/UserConstant.java | 6b473028f32be118774abef6116d8db28adb732d | [] | no_license | ofoo/fengyulou-server | 51dc1e7917bfd20e3e6f07843efa57c6e2f151f1 | e5b52d1ef04bd8bbae69c7a5b8ecfbbb6e1bb16d | refs/heads/master | 2023-04-07T00:31:55.326736 | 2020-05-23T19:26:05 | 2020-05-23T19:26:05 | 265,826,969 | 0 | 0 | null | 2020-05-21T11:24:06 | 2020-05-21T11:06:34 | Java | UTF-8 | Java | false | false | 166 | java | package com.guoguo.fengyulou.constant;
/**
* 用户常量
*/
public class UserConstant {
/**
* 管理员
*/
public static final int ADMIN = 1;
}
| [
"guochao@nxb100.com"
] | guochao@nxb100.com |
450c1038c9b46003260e960ce158470616fe8a31 | 75c478de8b0e1ad7538a6456e5e961c96e09afba | /src/org/kryogenic/SleepTest.java | 532f5622d58dfac29ad55949f7c5dd139ad96511 | [] | no_license | kryogenic/OldPowerBot | 846bf4f9bce4bb488e07316b5ac825d8f1104a6b | e0f115eebd18c30dd8268ada48328ff87dc644b7 | refs/heads/master | 2016-09-06T14:17:19.248509 | 2015-03-09T11:13:30 | 2015-03-09T11:13:30 | 31,887,807 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,136 | java | package org.kryogenic;
import org.powerbot.concurrent.Task;
import org.powerbot.concurrent.strategy.Strategy;
import org.powerbot.game.api.ActiveScript;
import org.powerbot.game.api.Manifest;
import org.powerbot.game.api.methods.Widgets;
import org.powerbot.game.api.util.Time;
/**
* @author: Kale
* @date: 02/08/12
* @version: 0.0
*/
@Manifest(
authors = {"kryo"},
description = "Tests stuff",
hidden = false,
name = "SleepTest",
topic = 0,
version = 0.0,
vip = false,
website = "http://www.kryogenic.org"
)
public class SleepTest extends ActiveScript {
@Override
protected void setup() {
provide(new Strategy(
new Task() {
@Override
public void run() {
while(Widgets.get(335, 49).getText() == null)
Time.sleep(2500);
System.out.println("Trade window found!");
}
}
) {
public boolean validate() {
return true;
}
});
}
}
| [
"krydrogen@gmail.com"
] | krydrogen@gmail.com |
80ba774ae3970b912afbf230092409ab6b215450 | 8e89723af6f45e0ce7aee57767c09fb336281855 | /src/main/java/com/laptrinhweb/controller/admin/HomeController.java | dbab3ecb3fa5f880691cc8f1d83ca740369e8b55 | [] | no_license | todinhvin/bookshop | 385c8aea7a44df8a58d02848a9817f03e9b903e5 | bf184ebce6084377b573929b90dfbef658f219e0 | refs/heads/main | 2023-06-10T01:29:57.993707 | 2021-06-30T13:23:14 | 2021-06-30T13:23:14 | 348,642,939 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 971 | java |
package com.laptrinhweb.controller.admin;
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.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.laptrinhweb.dto.CheckoutDTO;
import com.laptrinhweb.service.ICartService;
@Controller(value = "homeControllerOfAdmin")
public class HomeController {
@Autowired
private ICartService cartService;
@RequestMapping(value = "/quan-tri/trang-chu", method = RequestMethod.GET)
public ModelAndView homePage() {
List<CheckoutDTO> checkoutList = cartService.getAllCheckoutCart();
int totalOrder = cartService.getCountCheckoutCart();
ModelAndView mav = new ModelAndView("admin/dashboard");
mav.addObject("checkoutList",checkoutList);
mav.addObject("totalOrder",totalOrder);
return mav;
}
}
| [
"todinhvin12a1@gmail.com"
] | todinhvin12a1@gmail.com |
55495f83f6f4f69c6839bcd95453ffd54c501dd1 | 169fd5b84a208acf8856ac757656d752237175cc | /src/main/java/com/vidolima/ditiow/aspect/util/ResponseEntityUtil.java | 34146e77c0fb6a5b30c059cf06a3a6ae71b3637e | [
"MIT"
] | permissive | marcosvidolin/ditiow | f9f3a79e0bdafaf8d26007cedb0e1df7a183ddea | e5f14e026943ddf965cee618477ea6bfbeb3f517 | refs/heads/master | 2021-06-29T05:55:18.129338 | 2020-11-16T21:40:18 | 2020-11-16T21:40:18 | 229,589,609 | 8 | 6 | MIT | 2021-04-26T14:34:01 | 2019-12-22T15:33:02 | Java | UTF-8 | Java | false | false | 1,564 | java | package com.vidolima.ditiow.aspect.util;
import com.vidolima.ditiow.assembler.Assembler;
import com.vidolima.ditiow.assembler.ResourceAssembler;
import org.springframework.http.ResponseEntity;
/**
* Utility class used to prepare the HTTP Response.
*
* @author Marcos A. Vidolin de Lima
*/
public final class ResponseEntityUtil {
/**
* Converts the body response into an instance of the classOfBody.
*
* @param response {@link ResponseEntity}
* @param classOfBody the class of the new instance of the response body
* @return ResponseEntity
*/
public static ResponseEntity<?> convertBody(final ResponseEntity<?> response, final Class<?> classOfBody) {
Assembler assembler = new ResourceAssembler();
Object copied = assembler.assembly(response.getBody(), classOfBody);
return new ResponseEntity(copied, response.getHeaders(), response.getStatusCode());
}
/**
* Converts the body response into an instance of the classOfBody.
*
* @param response {@link ResponseEntity}
* @param classOfBody the class of the new instance of the response body
* @param excludedFields fields to be ignored
* @return ResponseEntity
*/
public static ResponseEntity<?> convertBody(final ResponseEntity<?> response, final Class<?> classOfBody
, final String[] excludedFields) {
Assembler assembler = new ResourceAssembler();
Object copied = assembler.assembly(response.getBody(), classOfBody, excludedFields);
return new ResponseEntity(copied, response.getHeaders(), response.getStatusCode());
}
}
| [
"marcosvidolin@gmail.com"
] | marcosvidolin@gmail.com |
1a0b7d2873d9ce441fb5e0f6bcaf2694fa1e327a | 8e502a7a343c97e94c3f114cbb84e0dee657c00d | /src/main/java/recommending/RecomSubscription.java | f83068330f560e99c88c9891db50622d8eb2e160 | [
"MIT"
] | permissive | Menion93/DataScientistBot | 036c7b9878d22940ab5fa8986623e342ed8831f9 | 31b19f169c7d02937822d92344ac25e4a589f5b9 | refs/heads/master | 2021-08-31T19:18:36.537639 | 2017-12-22T14:29:08 | 2017-12-22T14:29:08 | 105,999,880 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 791 | java | package main.java.recommending;
import main.java.database.MetadataRepository;
import main.java.database.MongoMetadataRepository;
import main.java.metadata.MetadataTask;
import main.java.metadata.tasks.Context2Modules;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Andrea on 07/11/2017.
*/
public class RecomSubscription {
public Map<String, Recommendation> recomTasks;
public RecomSubscription(){
MetadataRepository repository = new MongoMetadataRepository();
recomTasks = new HashMap<>();
}
public void runTaskByName(String name){
Recommendation recom = recomTasks.get(name);
if(recom != null)
recom.makeRecommendation();
else
System.out.println("Task name not found");
}
}
| [
"andrea.salvoni93@gmail.com"
] | andrea.salvoni93@gmail.com |
35e63fa05d7ef21df949c79251b96d97f7a36a42 | 45b2fe9712c389da6dbb2a012fec480d8d4eb8de | /android/support/v4/text/util/LinkifyCompat.java | 74b16349883d800d0b4539bd0709e0ac0f82b08c | [] | no_license | Whdora/SpeechCalculator | a5b23000ee56016d326358cf66e2ab80742d7a01 | 9785a266dcdbee6a695006ba94deab521348be8c | refs/heads/master | 2020-06-17T19:23:50.892496 | 2017-11-05T06:12:43 | 2017-11-05T06:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,056 | java | package android.support.v4.text.util;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.PatternsCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.text.util.Linkify.MatchFilter;
import android.text.util.Linkify.TransformFilter;
import android.webkit.WebView;
import android.widget.TextView;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class LinkifyCompat {
private static final Comparator<LinkSpec> COMPARATOR = new C00891();
private static final String[] EMPTY_STRING = new String[0];
static class C00891 implements Comparator<LinkSpec> {
C00891() {
}
public final int compare(LinkSpec a, LinkSpec b) {
if (a.start < b.start) {
return -1;
}
if (a.start > b.start) {
return 1;
}
if (a.end < b.end) {
return 1;
}
if (a.end <= b.end) {
return 0;
}
return -1;
}
}
private static class LinkSpec {
int end;
URLSpan frameworkAddedSpan;
int start;
String url;
LinkSpec() {
}
}
@Retention(RetentionPolicy.SOURCE)
public @interface LinkifyMask {
}
public static final boolean addLinks(@NonNull Spannable text, int mask) {
if (mask == 0) {
return false;
}
URLSpan[] old = (URLSpan[]) text.getSpans(0, text.length(), URLSpan.class);
for (int i = old.length - 1; i >= 0; i--) {
text.removeSpan(old[i]);
}
if ((mask & 4) != 0) {
boolean frameworkReturn = Linkify.addLinks(text, 4);
}
ArrayList<LinkSpec> links = new ArrayList();
if ((mask & 1) != 0) {
Spannable spannable = text;
gatherLinks(links, spannable, PatternsCompat.AUTOLINK_WEB_URL, new String[]{"http://", "https://", "rtsp://"}, Linkify.sUrlMatchFilter, null);
}
if ((mask & 2) != 0) {
gatherLinks(links, text, PatternsCompat.AUTOLINK_EMAIL_ADDRESS, new String[]{"mailto:"}, null, null);
}
if ((mask & 8) != 0) {
gatherMapLinks(links, text);
}
pruneOverlaps(links, text);
if (links.size() == 0) {
return false;
}
Iterator it = links.iterator();
while (it.hasNext()) {
LinkSpec link = (LinkSpec) it.next();
if (link.frameworkAddedSpan == null) {
applyLink(link.url, link.start, link.end, text);
}
}
return true;
}
public static final boolean addLinks(@NonNull TextView text, int mask) {
if (mask == 0) {
return false;
}
CharSequence t = text.getText();
if (!(t instanceof Spannable)) {
Spannable s = SpannableString.valueOf(t);
if (!addLinks(s, mask)) {
return false;
}
addLinkMovementMethod(text);
text.setText(s);
return true;
} else if (!addLinks((Spannable) t, mask)) {
return false;
} else {
addLinkMovementMethod(text);
return true;
}
}
public static final void addLinks(@NonNull TextView text, @NonNull Pattern pattern, @Nullable String scheme) {
addLinks(text, pattern, scheme, null, null, null);
}
public static final void addLinks(@NonNull TextView text, @NonNull Pattern pattern, @Nullable String scheme, @Nullable MatchFilter matchFilter, @Nullable TransformFilter transformFilter) {
addLinks(text, pattern, scheme, null, matchFilter, transformFilter);
}
public static final void addLinks(@NonNull TextView text, @NonNull Pattern pattern, @Nullable String defaultScheme, @Nullable String[] schemes, @Nullable MatchFilter matchFilter, @Nullable TransformFilter transformFilter) {
Spannable spannable = SpannableString.valueOf(text.getText());
if (addLinks(spannable, pattern, defaultScheme, schemes, matchFilter, transformFilter)) {
text.setText(spannable);
addLinkMovementMethod(text);
}
}
public static final boolean addLinks(@NonNull Spannable text, @NonNull Pattern pattern, @Nullable String scheme) {
return addLinks(text, pattern, scheme, null, null, null);
}
public static final boolean addLinks(@NonNull Spannable spannable, @NonNull Pattern pattern, @Nullable String scheme, @Nullable MatchFilter matchFilter, @Nullable TransformFilter transformFilter) {
return addLinks(spannable, pattern, scheme, null, matchFilter, transformFilter);
}
public static final boolean addLinks(@NonNull Spannable spannable, @NonNull Pattern pattern, @Nullable String defaultScheme, @Nullable String[] schemes, @Nullable MatchFilter matchFilter, @Nullable TransformFilter transformFilter) {
if (defaultScheme == null) {
defaultScheme = "";
}
if (schemes == null || schemes.length < 1) {
schemes = EMPTY_STRING;
}
String[] schemesCopy = new String[(schemes.length + 1)];
schemesCopy[0] = defaultScheme.toLowerCase(Locale.ROOT);
for (int index = 0; index < schemes.length; index++) {
String scheme = schemes[index];
schemesCopy[index + 1] = scheme == null ? "" : scheme.toLowerCase(Locale.ROOT);
}
boolean hasMatches = false;
Matcher m = pattern.matcher(spannable);
while (m.find()) {
int start = m.start();
int end = m.end();
boolean allowed = true;
if (matchFilter != null) {
allowed = matchFilter.acceptMatch(spannable, start, end);
}
if (allowed) {
applyLink(makeUrl(m.group(0), schemesCopy, m, transformFilter), start, end, spannable);
hasMatches = true;
}
}
return hasMatches;
}
private static void addLinkMovementMethod(@NonNull TextView t) {
MovementMethod m = t.getMovementMethod();
if ((m == null || !(m instanceof LinkMovementMethod)) && t.getLinksClickable()) {
t.setMovementMethod(LinkMovementMethod.getInstance());
}
}
private static String makeUrl(@NonNull String url, @NonNull String[] prefixes, Matcher matcher, @Nullable TransformFilter filter) {
if (filter != null) {
url = filter.transformUrl(matcher, url);
}
boolean hasPrefix = false;
for (int i = 0; i < prefixes.length; i++) {
if (url.regionMatches(true, 0, prefixes[i], 0, prefixes[i].length())) {
hasPrefix = true;
if (!url.regionMatches(false, 0, prefixes[i], 0, prefixes[i].length())) {
url = prefixes[i] + url.substring(prefixes[i].length());
}
if (hasPrefix && prefixes.length > 0) {
return prefixes[0] + url;
}
}
}
return hasPrefix ? url : url;
}
private static void gatherLinks(ArrayList<LinkSpec> links, Spannable s, Pattern pattern, String[] schemes, MatchFilter matchFilter, TransformFilter transformFilter) {
Matcher m = pattern.matcher(s);
while (m.find()) {
int start = m.start();
int end = m.end();
if (matchFilter == null || matchFilter.acceptMatch(s, start, end)) {
LinkSpec spec = new LinkSpec();
spec.url = makeUrl(m.group(0), schemes, m, transformFilter);
spec.start = start;
spec.end = end;
links.add(spec);
}
}
}
private static void applyLink(String url, int start, int end, Spannable text) {
text.setSpan(new URLSpan(url), start, end, 33);
}
private static final void gatherMapLinks(ArrayList<LinkSpec> links, Spannable s) {
String string = s.toString();
int base = 0;
while (true) {
String address = WebView.findAddress(string);
if (address != null) {
int start = string.indexOf(address);
if (start >= 0) {
LinkSpec spec = new LinkSpec();
int end = start + address.length();
spec.start = base + start;
spec.end = base + end;
string = string.substring(end);
base += end;
try {
} catch (UnsupportedEncodingException e) {
}
try {
spec.url = "geo:0,0?q=" + URLEncoder.encode(address, "UTF-8");
links.add(spec);
} catch (UnsupportedOperationException e2) {
return;
}
}
return;
}
return;
}
}
private static final void pruneOverlaps(ArrayList<LinkSpec> links, Spannable text) {
int i;
URLSpan[] urlSpans = (URLSpan[]) text.getSpans(0, text.length(), URLSpan.class);
for (i = 0; i < urlSpans.length; i++) {
LinkSpec spec = new LinkSpec();
spec.frameworkAddedSpan = urlSpans[i];
spec.start = text.getSpanStart(urlSpans[i]);
spec.end = text.getSpanEnd(urlSpans[i]);
links.add(spec);
}
Collections.sort(links, COMPARATOR);
int len = links.size();
i = 0;
while (i < len - 1) {
LinkSpec a = (LinkSpec) links.get(i);
LinkSpec b = (LinkSpec) links.get(i + 1);
int remove = -1;
if (a.start <= b.start && a.end > b.start) {
if (b.end <= a.end) {
remove = i + 1;
} else if (a.end - a.start > b.end - b.start) {
remove = i + 1;
} else if (a.end - a.start < b.end - b.start) {
remove = i;
}
if (remove != -1) {
URLSpan span = ((LinkSpec) links.get(remove)).frameworkAddedSpan;
if (span != null) {
text.removeSpan(span);
}
links.remove(remove);
len--;
}
}
i++;
}
}
private LinkifyCompat() {
}
}
| [
"vidyadheeshadn98@gmail.com"
] | vidyadheeshadn98@gmail.com |
fb3182bec882b4a39998ba17b17f049744fcf1a3 | b1ccc804af425c57ca2dcf04a67345b89c0791fe | /TravelLogAndroid/src/main/java/zarazio/travel/android/MemberController.java | 35d2340ecafabbb07adfc46eef021e2fad0eb726 | [] | no_license | Haru00524/Return_andserver | 3acf7e28241085a3116861a7ba83c64febf42382 | 52dc479f63988783adf40d84b153be76822ac6ac | refs/heads/master | 2021-01-22T06:18:48.347028 | 2017-09-12T15:37:23 | 2017-09-12T15:37:23 | 92,537,939 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 12,147 | java | package zarazio.travel.android;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import zarazio.travel.android.bean.Friend;
import zarazio.travel.android.bean.Member;
import zarazio.travel.android.bean.TravelStory;
import zarazio.travel.android.dao.MemberDAO;
import zarazio.travel.android.service.MemberService;
import zarazio.travel.android.service.TravelStoryService;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.imgscalr.Scalr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MemberController {
@Inject
private MemberService service;
@Inject
private JavaMailSender mailSender;
@Inject
private TravelStoryService mservice;
@RequestMapping(value="/expensive")
public void expenseInsert(HttpServletRequest request, TravelStory travelstory) throws Exception {
System.out.println("ddsadas");
mservice.expenseInsert(travelstory);
travelstory.setExpense_Code(mservice.fineMaxExpenseCode());
// System.out.println("그룹코드 : "+travelstory.getGroup_Code());
// System.out.println("사용자아이디 : "+travelstory.getUser_id());
// System.out.println("지출코드 : "+travelstory.getExpense_Code());
mservice.expenseInsertTravel(travelstory);
}
@RequestMapping(value="/register")
public void androidTest2(HttpServletRequest request, Member member) throws Exception {
service.insert(member);
}
@RequestMapping("firend")
public ResponseEntity<String> friendState(Friend friend) throws Exception{
HttpHeaders resHeaders = new HttpHeaders();
resHeaders.add("Content-Type", "application/json;charset=EUC_KR");
System.out.println(friend.getFriend_id() +" / " + friend.getUser_id());
Friend result = new Friend();
result = service.friendState(friend);
Gson gson = new Gson();
String data = gson.toJson(result);
System.out.println(data);
return new ResponseEntity<String>(data,resHeaders,HttpStatus.CREATED);
}
@RequestMapping(value="/firendADD")
public ResponseEntity<String> friend(Friend friend) throws Exception{
HttpHeaders resHeaders = new HttpHeaders();
resHeaders.add("Content-Type", "application/json;charset=EUC_KR");
System.out.println(friend.getFriend_State());
if(friend.getFriend_State().equals("친구신청")){
service.friendADD(friend);
}else if(friend.getFriend_State().equals("친구하기")){
service.friendUpdate(friend);
}else if(friend.getFriend_State().equals("친구")){
service.friendDelete(friend);
}else if(friend.getFriend_State().equals("친구신청중")){
service.friendDelete(friend);
}
return new ResponseEntity<String>("success",resHeaders,HttpStatus.CREATED);
}
@RequestMapping(value="/idCheck")
@ResponseBody
public String androidIdCheck(HttpServletRequest request, Member member) throws Exception {
String count = service.idCheck(member) + "";
System.out.println(count);
return count;
}
@RequestMapping("change_profile")
public ResponseEntity<String> changeProfile(HttpServletRequest request) throws Exception {
System.out.println("들어옴");
String result="Failed";
HttpHeaders resHeaders = new HttpHeaders();
resHeaders.add("Content-Type", "application/json;charset=EUC_KR");
String this_id = null;
String c_user_id = null;
String c_user_email = null;
String c_user_phone = null;
String c_user_gender = null;
String originalName = "";
HttpStatus a=HttpStatus.BAD_REQUEST;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items= null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Iterator itr = null;
if(items!=null){
itr= items.iterator();
}
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
System.out.println(item.isFormField());
if (item.isFormField()) { // 파일이 아닌 폼필드에 입력한 내용을 가져옴.
if(item!=null && item.getFieldName().equals("this_id")) {
this_id = item.getString("EUC_KR");//form field 안에 입력한 데이터를 가져옴
System.out.println("로그 제목:"+this_id+"<br>");
}else if(item!=null && item.getFieldName().equals("c_user_id")) {
c_user_id = item.getString("EUC_KR");
System.out.println("로그 내용:"+c_user_id+"<br>");
}else if(item!=null && item.getFieldName().equals("c_user_email")) {
c_user_email = item.getString("EUC_KR");
System.out.println("해시태그 내용:"+c_user_email+"<br>");
}else if(item!=null && item.getFieldName().equals("c_user_phone")) {
c_user_phone = item.getString("EUC_KR");
System.out.println("경도 내용:"+c_user_phone+"<br>");
}else if(item!=null && item.getFieldName().equals("c_user_gender")) {
c_user_gender = item.getString("EUC_KR");
System.out.println("위도 내용:"+c_user_gender+"<br>");
}
}
else{ // 폼 필드가 아니고 파일인 경우
try {
String itemName = item.getName();//로컬 시스템 상의 파일경로 및 파일 이름 포함
if(itemName==null || itemName.equals("") ) continue;
String fileName = FilenameUtils.getName(itemName);// 경로없이 파일이름만 추출함
if(fileName.equals("null")) continue;
// 전송된 파일을 서버에 저장하기 위한 절차
//String rootPath = getServletContext().getRealPath("/");
originalName = System.currentTimeMillis()+"Travel_log_";
File savedFile = new File("C:/Returns/src/main/webapp/resources/upload/logs/"+ originalName+fileName);
item.write(savedFile);// 지정 경로에 파일을 저장함
String uploadedFileName = null;
// 이미지 파일은 썸네일 사용
// 썸네일생성
uploadedFileName = makeThumbnail("C:/Returns/src/main/webapp/resources/upload/logs/", originalName+fileName);
originalName += fileName;
System.out.println("<tr><td><b>파일저장 경로:</b></td></tr><tr><td><b>"+savedFile+"</td></tr>");
System.out.println("<tr><td><b><a href=\"DownloadServlet?file="+fileName+"\">"+originalName+"</a></td></tr>");
} catch (Exception e) {
System.out.println("서버에 파일 저장중 에러: "+e);
}
}
}
Member member = new Member();
if(this_id != null)
member.setThis_id(this_id);
if(c_user_email != null)
member.setUser_email(c_user_email);
if(c_user_gender != null)
member.setUser_gender(c_user_gender);
if(c_user_phone != null)
member.setUser_phone(c_user_phone);
member.setUser_id(c_user_id);
String count = service.idCheck(member) + "";
/*if(count.equals("1")){
result = "idcheck";
a = HttpStatus.CREATED;
}else if(!count.equals("1")){
service.user_update(member);
a = HttpStatus.OK;
}else{
result = "Failed";
a = HttpStatus.BAD_REQUEST;
}*/
return new ResponseEntity<String>("success", resHeaders, a);
}
@RequestMapping("change_pass")
@ResponseBody
public String changePassWord(HttpServletRequest request ,Member member) throws Exception {
String result="Failed";
service.passUpdate(member);
result="success";
return result;
}
@RequestMapping("login")
@ResponseBody
public ResponseEntity<String> androidLogin(HttpServletRequest request, Member member) throws Exception {
HttpHeaders resHeaders = new HttpHeaders();
resHeaders.add("Content-Type", "application/json;charset=UTF-8");
Member List = new Member();
List = service.loginCheck(member);
Gson gson = new Gson();
String data = gson.toJson(List);
System.out.println(request.getParameter("user_id"));
System.out.println(request.getParameter("user_pass"));
return new ResponseEntity<String>(data,resHeaders,HttpStatus.CREATED);
}
@RequestMapping("findId")
@ResponseBody
public String idFind(Member member) throws Exception {
String user_id = service.idFind(member);
if (user_id == null) {
user_id = "NOT FOUND";
}
return user_id;
}
@RequestMapping("findPass")
@ResponseBody
public String passFind(Member member) throws Exception {
System.out.println(member.getUser_id());
Member mem = service.passFind(member);
String result = "FAILED";
if (mem != null) {
result = "SUCCESS";
String buf = getRandomPassword(15);
Member mem2 = new Member();
mem2.setUser_id(member.getUser_id());
mem2.setUser_pass(buf);
service.lostpass(mem2);
// mailSending 코드
String setfrom = "travellogproject@gmail.com";
String tomail = mem.getUser_email(); // 받는 사람 이메일
String title = "[Travel_log] 비밀번호 찾기 문의"; // 보내는 사람 이메일
String content = "임시 비밀번호는 "+buf + "입니다. 로그인시 비밀번호를 바꿔주세요"; // 보내는 사람 이메일
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8");
messageHelper.setFrom(setfrom); // 보내는사람 생략하거나 하면 정상작동을 안함
messageHelper.setTo(tomail); // 받는사람 이메일
messageHelper.setSubject(title); // 메일제목은 생략이 가능하다
messageHelper.setText(content); // 메일 내용
mailSender.send(message);
} catch (Exception e) {
System.out.println(e);
}
}
return result;
}
public String getRandomPassword( int length ){
char[] charaters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'};
StringBuffer sb = new StringBuffer();
Random rn = new Random();
for( int i = 0 ; i < length ; i++ ){
sb.append( charaters[ rn.nextInt( charaters.length ) ] );
}
return sb.toString();
}
// 썸네일 생성
private static String makeThumbnail(String uploadPath, String fileName) throws Exception{
// 이미지를 읽어들이기 위한 버퍼
BufferedImage sourceImg =
ImageIO.read(new File(uploadPath, fileName));
// 100 픽셀단위 썸네일 생성
BufferedImage destImg =
Scalr.resize(sourceImg, 600, null, null);
// Scalr.resize(sourceImg, Scalr.Method.AUTOMATIC, Scalr.Mode.FIT_TO_HEIGHT, 100);
// 썸네일의 이름생성 "s_"를 붙임
String thumbnailName =
uploadPath +"s_"+ fileName;
File newFile = new File(thumbnailName);
// 썸네일 생성
ImageIO.write(destImg, "jpg", newFile);
// 썸네일의 이름을 리턴
return thumbnailName.substring(uploadPath.length()).replace(File.separatorChar, '/');
}
}
| [
"akfm00524@gmail.com"
] | akfm00524@gmail.com |
cf8e01026e62dfdfaf4412beea0a8625d5802cf0 | a3dcad059c875a2bdd6a6bf4354e3ff440948e83 | /CyberQuestions/src/main/java/com/cyber/test/HelloWorldAction.java | 5ad5b582aa48a6a1b96f2ac8d8af65078c644a5f | [] | no_license | s4safety/S4SafetySurvey | 0b56b307adbd9d9d94d8be36828711d5ed1ae54a | 4c4ac892ece93d1c306cd429316c4e9313ece8b6 | refs/heads/master | 2020-12-24T17:54:51.898081 | 2015-03-22T19:06:39 | 2015-03-22T19:06:39 | 32,484,756 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 633 | java | package com.cyber.test;
import org.apache.log4j.Logger;
public class HelloWorldAction {
private String name;
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(HelloWorldAction.class);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute() throws Exception {
logger.info("Inside execute method");
String thisName = this.name.toUpperCase();
logger.info("The value of name is : "+ thisName);
if (thisName.equals("VINAY")) {
return "vinay";
} else {
return "success";
}
}
}
| [
"s4safety@github.com"
] | s4safety@github.com |
18700a658120612347970c80e125ad944377e182 | fcc77c18308bad80ef65516fcfc903ad3c2096fd | /Java Quiz Application/app/src/main/java/com/rbworks/dev/cquiz/com/rbwdcq/ResultActivity.java | bff015bf4aa9288b5e8df49f757e742d471f129d | [] | no_license | rohitbhokarikar/Java-Quiz-Application | 368f6adfec191f2bedff881ce1ce416f1464e283 | eff6b691ba46ec3f345177e4c0c4eef563610289 | refs/heads/master | 2020-07-16T19:32:30.140987 | 2019-09-02T12:34:34 | 2019-09-02T12:34:34 | 189,709,785 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,160 | java | package com.rbworks.dev.cquiz.com.rbwdcq;
/**
* Created by Admin on 21/12/2017.
*/
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.RatingBar;
import android.widget.TextView;
//import com.delaroystudios.quiz.R;
public class ResultActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
//get rating bar object
RatingBar bar = (RatingBar) findViewById(R.id.ratingBar1);
bar.setNumStars(5);
bar.setStepSize(0.5f);
//get text view
TextView t = (TextView) findViewById(R.id.textResult);
//get score
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
//display score
bar.setRating(score);
switch (score) {
case 0:
t.setText("You scored 0 %, keep learning");
break;
case 1:
t.setText("You have 20 %, study better");
break;
case 2:
t.setText("You have 40 %, keep learning");
break;
case 3:
t.setText("You have 60 %, good attempt");
break;
case 4:
t.setText("Congratulations You Have 80 % ");
break;
case 5:
t.setText("Congratulations You Have 100 % ");
break;
}
}
}
/*
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.activity_result, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_about) {
Intent settingsIntent = new Intent(this, QuizActivity.class);
startActivity(settingsIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
*/ | [
"rohitbhokarikardev@gmail.com"
] | rohitbhokarikardev@gmail.com |
77bc77e53ea6df71f915804b458fb12f10dd2e48 | aab39a3e6f61b5c19b964b70cfa29bc8b2d6f55b | /src/org/csu/mypetstore/persistence/ProductDao.java | cb93dff6498062ca60dbf5ca41a619f16372d5b9 | [
"AFL-3.0"
] | permissive | ElliotQi/MyPetStore | 56318d5b03c9d0e1d4a64820f53c93b5a88bc3f4 | e310378a577d61f93eea564f48b8dd3fe67b352d | refs/heads/master | 2021-02-11T17:17:00.952239 | 2020-04-01T17:46:46 | 2020-04-01T17:46:46 | 244,514,369 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 301 | java | package org.csu.mypetstore.persistence;
import org.csu.mypetstore.domain.Product;
import java.util.List;
public interface ProductDao {
List<Product> getProductListByCategory(String categoryId);
Product getProduct(String productId);
List<Product> searchProductList(String keywords);
}
| [
"782880940@qq.com"
] | 782880940@qq.com |
95552e730022e27cb3482a487318f8f7bd14e140 | c56be91e83a7027ba105948504527ec0ff1dfa46 | /src/main/java/com/turvo/bankingqueue/constant/ServiceType.java | 97f7dae11c848c72218001c0fdef1d228438ff2a | [] | no_license | vedaantnarayan/banking-queue | f27720c217590692152bd3bad8ff1e589fb0b256 | caa4c3c83ff1eeb623580aeaa854987ea13bd4d9 | refs/heads/master | 2020-05-01T16:55:45.549311 | 2019-04-05T09:11:58 | 2019-04-05T09:11:58 | 177,585,805 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 199 | java | package com.turvo.bankingqueue.constant;
public enum ServiceType {
ACC_VERIFICATION,BALANCE_ENQUIRY,CASH_WITHDRAW,CASH_DEPOSIT,CHECK_DEPOSIT,ACC_CLOSE,ACC_OPEN,MANAGER_APPROVAL, DOC_VERIFICATION
}
| [
"vedant.narayan@imaginea.com"
] | vedant.narayan@imaginea.com |
dd476fc16d626599089c0a00a4847e4abbfae971 | 4091d8a6371632c4d4e3c8e12cf781587b261b9c | /src/test/java/com/techproed/tests/Day08_FileDownloadTest.java | 27323749d969f450af0a85b575972894a085d58f | [] | no_license | dalerjonazimov/selenium_junit_framework | 42c198ad0e0a6fa637c21de59d19fbc292e2262c | 26282fbfc854568ab7bad2aba9b651b9954d82b0 | refs/heads/main | 2023-08-22T04:52:43.124810 | 2021-10-14T14:25:50 | 2021-10-14T14:25:50 | 416,694,460 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,291 | java | package com.techproed.tests;
import com.techproed.utilities.TestBase;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Day08_FileDownloadTest extends TestBase {
@Test
public void fileDownloadTest() throws InterruptedException {
//create a class: FileDownloadTest
//fileDownloadTest()
//Go to https://the-internet.herokuapp.com/download
driver.get("https://the-internet.herokuapp.com/download");
//download flower.png file
driver.findElement(By.linkText("flower.jpeg")).click();
//Then verify the file downloaded successfully
//We must put hard wait since file download takes a little bit time
//Implicit or explicit wait cannot fix the problem, download folder is windows based application
Thread.sleep(2000);
// Getting the PATH of the HOME directory with JAVA
String homePath = System.getProperty("user.home");
//This will be the file name that is downloaded
String pathOfFlower = homePath + "\\Downloads\\flower.jpeg";
boolean isDownloaded = Files.exists(Paths.get(pathOfFlower));
//Asserting if file download is successful
Assert.assertTrue(isDownloaded);
}
}
| [
"dalerjon.azimov@gmail.com"
] | dalerjon.azimov@gmail.com |
860e77d82b5c32a0db14abca11f526e47b33ab5c | c41a50840bac60d138f9134f958e9d827f20e8bb | /noqNgo_store-master/app/src/main/java/com/example/lee/noqngo/FirebaseMessagingService.java | fce1aef3cf5780c88d1e22eec6ab3c08ef099a5c | [] | no_license | limwonjin/pynchanggo | b6804d7e9ab97afb7d7044d03435675453c8514d | f56830ffc9d7a3cd17ad18d17fb1d742ac241ebf | refs/heads/master | 2021-01-24T08:45:29.853537 | 2017-08-23T05:12:27 | 2017-08-23T05:12:27 | 93,389,557 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,155 | java | package com.example.lee.noqngo;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.RemoteMessage;
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "FirebaseMsgService";
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendPushNotification(remoteMessage.getData().get("message"));
}
private void sendPushNotification(String message) {
System.out.println("received message : " + message);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.noti).setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher) )
.setContentTitle("Push Title ")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
wakelock.acquire(5000);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
| [
"rudghk5220@gmail.com"
] | rudghk5220@gmail.com |
d6812034734d281db94908aff13c4ebd2b90847f | be73270af6be0a811bca4f1710dc6a038e4a8fd2 | /crash-reproduction-moho/results/XRENDERING-418-5-25-FEMO-WeightedSum:TestLen:CallDiversity/org/xwiki/rendering/internal/renderer/xhtml/image/AbstractXHTMLImageTypeRenderer_ESTest_scaffolding.java | c9ddfffc85bb13e2715a6501336b8e9b6700b7ff | [] | no_license | STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application | cf118b23ecb87a8bf59643e42f7556b521d1f754 | 3bb39683f9c343b8ec94890a00b8f260d158dfe3 | refs/heads/master | 2022-07-29T14:44:00.774547 | 2020-08-10T15:14:49 | 2020-08-10T15:14:49 | 285,804,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 484 | java | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Sat Apr 04 04:07:12 UTC 2020
*/
package org.xwiki.rendering.internal.renderer.xhtml.image;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
@EvoSuiteClassExclude
public class AbstractXHTMLImageTypeRenderer_ESTest_scaffolding {
// Empty scaffolding for empty test suite
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
0623c366525efd913e6e5ac2265c4420f0441585 | 88fe2ea6fb75212f5821eae007357dca3e5a6745 | /src/jenis_transaksi.java | b3d72850b1f46d334dd2de4e810ff2b42d7d2c08 | [] | no_license | aulialigar/Modul10 | e379d906c53bc7f48d8111e78c8f65405fe71eec | 7b351bbb17bc0c0705894ed8c1ee78c6b18d1328 | refs/heads/master | 2021-01-22T04:23:18.930691 | 2017-02-10T06:41:21 | 2017-02-10T06:41:21 | 81,533,349 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,791 | java | /*
* 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.
*/
/**
*
* @author Smktelkom
*/
public class jenis_transaksi extends javax.swing.JFrame {
/**
* Creates new form jenis_transaksi
*/
public jenis_transaksi() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
saldo = new javax.swing.JButton();
penyetoran = new javax.swing.JButton();
penarikan = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
tarik = new javax.swing.JTextField();
Setor = new javax.swing.JTextField();
ket = new javax.swing.JLabel();
hasil = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
jLabel1.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("PILIH JENIS TRANSAKSI");
getContentPane().add(jLabel1);
jLabel1.setBounds(90, 40, 240, 40);
jLabel4.setFont(new java.awt.Font("FFF", 1, 24)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("ATM BNI SYARIAH BOJONEGORO");
getContentPane().add(jLabel4);
jLabel4.setBounds(50, 10, 320, 40);
saldo.setText("INFORMASI SALDO");
saldo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saldoActionPerformed(evt);
}
});
getContentPane().add(saldo);
saldo.setBounds(40, 90, 140, 30);
penyetoran.setText("PENYETORAN");
penyetoran.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
penyetoranActionPerformed(evt);
}
});
getContentPane().add(penyetoran);
penyetoran.setBounds(40, 140, 140, 30);
penarikan.setText("PENARIKAN");
penarikan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
penarikanActionPerformed(evt);
}
});
getContentPane().add(penarikan);
penarikan.setBounds(220, 140, 140, 30);
jButton4.setText("PETUNJUK");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
getContentPane().add(jButton4);
jButton4.setBounds(220, 90, 140, 30);
jButton5.setText("KELUAR");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
getContentPane().add(jButton5);
jButton5.setBounds(130, 280, 140, 30);
getContentPane().add(tarik);
tarik.setBounds(220, 180, 140, 30);
getContentPane().add(Setor);
Setor.setBounds(40, 180, 140, 30);
ket.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
ket.setForeground(new java.awt.Color(255, 255, 255));
getContentPane().add(ket);
ket.setBounds(40, 230, 220, 30);
hasil.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N
hasil.setForeground(new java.awt.Color(255, 255, 255));
getContentPane().add(hasil);
hasil.setBounds(240, 230, 140, 30);
jPanel1.setBackground(new java.awt.Color(255, 163, 49));
jPanel1.setMinimumSize(new java.awt.Dimension(400, 300));
jPanel1.setPreferredSize(new java.awt.Dimension(400, 300));
getContentPane().add(jPanel1);
jPanel1.setBounds(0, 0, 400, 330);
setSize(new java.awt.Dimension(416, 368));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void saldoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saldoActionPerformed
// TODO add your handling code here:
int saldo = 150000;
ket.setText("SALDO YANG ANDA MILIKI");
hasil.setText(""+saldo);
}//GEN-LAST:event_saldoActionPerformed
private void penarikanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_penarikanActionPerformed
// TODO add your handling code here:
String tarikan = tarik.getText();
int saldo = 150000;
int jmltarik = Integer.parseInt(tarikan);
int total = saldo-jmltarik;
hasil.setText(""+total);
}//GEN-LAST:event_penarikanActionPerformed
private void penyetoranActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_penyetoranActionPerformed
// TODO add your handling code here:
String setor = Setor.getText();
String saldolast = hasil.getText();
hasil.setText(""+saldolast);
int jmlsetor = Integer.parseInt(setor);
int lastsaldo = Integer.parseInt(saldolast);
int total = lastsaldo+jmlsetor;
hasil.setText(""+total);
}//GEN-LAST:event_penyetoranActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
// TODO add your handling code here:
dispose();
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
new petunjuk().setVisible(true);
this.dispose();
}//GEN-LAST:event_jButton4ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(jenis_transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(jenis_transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(jenis_transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(jenis_transaksi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* saldond display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new jenis_transaksi().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField Setor;
private javax.swing.JLabel hasil;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel ket;
private javax.swing.JButton penarikan;
private javax.swing.JButton penyetoran;
private javax.swing.JButton saldo;
private javax.swing.JTextField tarik;
// End of variables declaration//GEN-END:variables
}
| [
"aulialsh69@gmail.com"
] | aulialsh69@gmail.com |
75b74c21f68f444a90524e92924bf07496cf5d5c | 4e82f2361073a12c3fbe873b043fcdbd64b2935d | /app/src/main/java/com/execulia/poorvacreativity/MainActivity.java | 4e024aafad9b8a76cc56100862f2335cc33ad9b7 | [] | no_license | 0RutherFord0/Poorva_Creativity_Android_Application | 60fa21417cff1dff60f96998b6a7cdbc8da65fcf | 9a6183b29323adc6348e9aa37581e578e4aa94d3 | refs/heads/master | 2023-05-02T09:06:10.159215 | 2021-05-16T21:21:19 | 2021-05-16T21:21:19 | 364,594,683 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,883 | java | package com.execulia.poorvacreativity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.play.core.review.ReviewInfo;
import com.google.android.play.core.review.ReviewManager;
import com.google.android.play.core.review.ReviewManagerFactory;
import com.google.android.play.core.tasks.OnCompleteListener;
import com.google.android.play.core.tasks.OnSuccessListener;
import com.google.android.play.core.tasks.Task;
import com.google.firebase.messaging.FirebaseMessaging;
public class MainActivity extends AppCompatActivity {
String websiteURL = "https://poorvacreativity.com/"; // sets web url
private WebView webview;
SwipeRefreshLayout mySwipeRefreshLayout;
private ProgressBar progressBar;
//Review Manager Start
ReviewManager manager;
ReviewInfo reviewInfo;
//Review Manager End
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Firebase Execulia Start
FirebaseMessaging.getInstance().subscribeToTopic("notifications");
//Firebase Execulia End
//Review Manager Start
manager = ReviewManagerFactory.create(MainActivity.this);
Task<ReviewInfo> request = manager.requestReviewFlow();
request.addOnCompleteListener(new OnCompleteListener<ReviewInfo>() {
@Override
public void onComplete(@NonNull Task<ReviewInfo> task) {
if(task.isSuccessful()){
reviewInfo = task.getResult();
Task<Void> flow = manager.launchReviewFlow(MainActivity.this, reviewInfo);
flow.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void result) {
}
});
}else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
//Review Manager End
if( ! CheckNetwork.isInternetAvailable(this)) //returns true if internet available
{
//if there is no internet do this
setContentView(R.layout.activity_main);
//Toast.makeText(this,"No Internet Connection, Chris",Toast.LENGTH_LONG).show();
new AlertDialog.Builder(this) //alert the person knowing they are about to close
.setTitle("No internet connection available")
.setMessage("Please Check you're Mobile data or Wifi network.")
.setPositiveButton("Connect", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity( new Intent(Settings.ACTION_WIFI_SETTINGS));
finish();
}
})
// .setNegativeButton("No", null)
.show();
}
else
{
//Webview stuff
webview = findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl(websiteURL);
webview.setWebViewClient(new WebViewClientDemo());
webview.setWebChromeClient(new WebChromeClientDemo());
}
//Swipe to refresh functionality
mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
webview.reload();
}
}
);
//Progress bar
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
}
private class WebViewClientDemo extends WebViewClient {
@Override
// URL Scheme Change Start
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("market://")||url.startsWith("whatsapp://")||url.startsWith("tel:")||url.startsWith("mailto:"))
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
else{
view.loadUrl(url);
return true;
}
}
// URL Scheme Change End
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
mySwipeRefreshLayout.setRefreshing(false);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class WebChromeClientDemo extends WebChromeClient {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
}
//set back button functionality
@Override
public void onBackPressed() { //if user presses the back button do this
if (webview.isFocused() && webview.canGoBack()) { //check if in webview and the user can go back
webview.goBack(); //go back in webview
} else { //do this if the webview cannot go back any further
new AlertDialog.Builder(this) //alert the person knowing they are about to close
.setTitle("EXIT")
.setMessage("Are you sure. You want to close this app?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
}
class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
}
}
} | [
"adityatwd0@gmail.com"
] | adityatwd0@gmail.com |
e7619d5940ffa7a66bb1e70b21858db1826e4802 | 8614fe48fa591f7e3345f20deeedc751e12457b6 | /src/com/my/domain/dao/ClassDao.java | d2c75d9e140ac85e4906cf75b2a47b79ecd69dd2 | [] | no_license | KevinBrother/homework | 302762498f7c8ac0381d724ecda8ae093c654449 | d4f9961b9b62ab88e215cf8337456eeb5b244937 | refs/heads/master | 2021-01-23T06:20:30.486898 | 2017-07-10T02:45:27 | 2017-07-10T02:45:27 | 93,020,333 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,176 | java | package com.my.domain.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.my.domain.model.Teacher;
import com.my.util.CloseAllDao;
import com.my.util.DBHelper;
public class ClassDao {
protected static final Logger logger = LoggerFactory.getLogger(TeacherDao.class);
Connection conn = null;
Statement stmt = null;
PreparedStatement prepStmt = null;
ResultSet rs = null;
public void addTeach(Teacher teacher) {
try {
//获取链接
conn = DBHelper.getConnection();
logger.info("===>>>>>====" + teacher);
String sql = "insert into teacher (name, password) values ("
+ "'" + teacher.getName() + "','qwer1234')";
//得到运行环境,并且执行sql
stmt = conn.createStatement();
//获得结果
int re = stmt.executeUpdate(sql);
//处理结果
logger.info("===<<<<<=====" + re);
} catch (Exception e) {
e.printStackTrace();
}
finally {
CloseAllDao.close(stmt, prepStmt, rs);
}
}
}
| [
"1301239018@qq.com"
] | 1301239018@qq.com |
1e9bdadd8135a14513280a7aa50e2180401a08ea | 6d83a600343e0d20aec74cf7d681c1674229969d | /app/src/main/java/org/uni2biz/AuthorizationFragment.java | 825388f570e27dfa27b57d103db00ffcf0105447 | [] | no_license | BelayaUlyana/Uni2Biz | 99ee07fb003d61c0bbbc1d45847b343cd8c29874 | 24fdb81886a3fdc6c0e65369c6af8ef6bac0557b | refs/heads/master | 2020-04-30T19:25:42.029763 | 2019-06-23T12:08:38 | 2019-06-23T12:08:38 | 177,038,262 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,525 | java | package org.uni2biz;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.uni2biz.API.AuthorizationRequest;
import org.uni2biz.API.AuthorizationResponse;
import org.uni2biz.API.RetrofitClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.HttpException;
import retrofit2.Response;
public class AuthorizationFragment extends Fragment {
private EditText mLogin, mPassword;
private FragmentNavigation mListener;
public static AuthorizationFragment newInstance() {
return new AuthorizationFragment();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentNavigation) {
mListener = (FragmentNavigation) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement FragmentNavigation");
}
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_authorization, container, false);
mLogin = view.findViewById(R.id.etUserName);
mPassword = view.findViewById(R.id.etPassword);
Button btnRegistration = view.findViewById(R.id.btnRegistration);
btnRegistration.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mListener.openRegistrationFragment();
}
});
TextView btnForgotPassword = view.findViewById(R.id.btnForgotPassword);
btnForgotPassword.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mListener.openForgotPasswordFragment();
}
});
Button btnSignIn = view.findViewById(R.id.btnSignIn);
btnSignIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
validate(mLogin.getText().toString(), mPassword.getText().toString());
}
});
return view;
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
private void validate(String login, String password) {
if (login.length() > 4 && !password.isEmpty() && password.length() > 4) {
onValidateSuccess();
} else {
onValidationError(getString(R.string.fillAllFields));
}
}
public void onValidateSuccess() {
System.out.println("ValidateSuccess -> callback to activity to open another fragment/activity");
Call<AuthorizationResponse> call = RetrofitClient.getApiService().auth(
new AuthorizationRequest(mLogin.getText().toString(), Helpers.md5(mPassword.getText().toString())));
call.enqueue(new Callback<AuthorizationResponse>() {
@Override
public void onResponse(Call<AuthorizationResponse> call, Response<AuthorizationResponse> response) {
if (response.isSuccessful()) {
Toast.makeText(getContext(),"Authorization Successful", Toast.LENGTH_LONG).show();
} else {
String msg = response.body().getMessage();
String fields = response.body().getFields();
int code = response.body().getCode();
String res = response.body().getResponse();
Log.e("MSG",msg + "***" + fields + "***" + code + "***" + res);
Toast.makeText(getContext(), msg + " " + fields + " " + code + " " + res, Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<AuthorizationResponse> call, Throwable throwable) {
if (throwable instanceof HttpException) {
HttpException e = (HttpException) throwable;
}
}
});
}
public void onValidationError(String msg) {
Toast.makeText(this.getActivity(), msg, Toast.LENGTH_LONG).show();
}
}
| [
"belaya.ulyana@gmail.com"
] | belaya.ulyana@gmail.com |
4624c799ef602e09d913e0dd782e97fa24b4b8d0 | 1293ffb40081cebe2cfe9433d06bb9784a7f37ed | /Parallel Projects BackUp/forestmanagementsystemusingcollection/src/main/java/com/capgemini/forestmanagementsystemusingcollection/service/ProductService.java | af36a7706d4d9c16754368f69e29b90d4e46e2c2 | [] | no_license | Omkarnaik571/Omkar | 4b93a78e8525248391309aad78d7e21100c8c8a2 | d6826adeda0719b0e346dc5a60c57e3e69ddc050 | refs/heads/master | 2022-07-01T10:18:18.604812 | 2020-05-13T15:41:00 | 2020-05-13T15:41:00 | 225,843,596 | 1 | 0 | null | 2022-06-21T02:49:05 | 2019-12-04T10:46:58 | Java | UTF-8 | Java | false | false | 1,014 | java | package com.capgemini.forestmanagementsystemusingcollection.service;
import java.util.TreeMap;
import com.capgemini.forestmanagementsystemusingcollection.dto.ProductDetails;
import com.capgemini.forestmanagementsystemusingcollection.exceptions.ExceptionWhileDeleting;
import com.capgemini.forestmanagementsystemusingcollection.exceptions.ExceptionWhileDisplaying;
import com.capgemini.forestmanagementsystemusingcollection.exceptions.ExceptionWhileInserting;
import com.capgemini.forestmanagementsystemusingcollection.exceptions.ExceptionWhileModifying;
public interface ProductService {
public boolean addProduct(ProductDetails l) throws ExceptionWhileInserting;
public boolean removeProduct(Integer landId) throws ExceptionWhileDeleting;
public TreeMap<Integer,ProductDetails> displayAllProduct() throws ExceptionWhileDisplaying;
public boolean modifyProduct(ProductDetails p) throws ExceptionWhileModifying;
public ProductDetails getSingleProduct(Integer id) throws ExceptionWhileDisplaying;
}
| [
"omkarnaik571@gmail.com"
] | omkarnaik571@gmail.com |
84623979add298f3f783adc2cd005dee8cc7633f | a5d626f6eba5d127c43e3cba1bff8d77e9ac977f | /xdht-disease-sys/src/main/java/com/xdht/disease/sys/dao/RecordIndividualProtectiveEquipmentMapper.java | 2e92f34bc77a27dd0ad944ba490691526e964b43 | [] | no_license | liangzhifu/xdht-disease | 1ede89df37893b2e660159ba454b07a4208e629b | cd92f0c6eca713c1e490712d957765e54b43b726 | refs/heads/master | 2022-07-08T00:11:12.113321 | 2019-01-21T07:53:40 | 2019-01-21T07:53:40 | 135,237,897 | 0 | 8 | null | 2022-06-29T16:46:08 | 2018-05-29T03:43:39 | Java | UTF-8 | Java | false | false | 464 | java | package com.xdht.disease.sys.dao;
import com.xdht.disease.common.core.Mapper;
import com.xdht.disease.sys.model.RecordIndividualProtectiveEquipment;
import java.util.Map;
public interface RecordIndividualProtectiveEquipmentMapper extends Mapper<RecordIndividualProtectiveEquipment> {
/**
* 查询个体防护用品调查表
* @param id 记录表主键id
* @return 返回结果
*/
Map<String,Object> selectRecordBySceneId(Long id);
} | [
"1462439581@qq.com"
] | 1462439581@qq.com |
58ccd1ccc8c7dc09f0b5954f9b8dda7bc013c6e0 | 22cad97941a4efd72e81b773d7a7bdeee7dba35b | /25-ExpedientesX/src/expedientesx/modelo/negocio/GestorExpedientesImpl.java | b53ea1314cd5cd41a3809d1cacdf4c04529a6c76 | [] | no_license | ignaciocerdeira/SpringATSistemasFebrero2017 | 5ec98583e02dfdea9158534b19462206f20f234a | 7f3a008b5a8b9d1d0dce8a2b70b784dc7aba7a97 | refs/heads/master | 2020-05-20T22:18:10.451924 | 2017-03-09T12:16:32 | 2017-03-09T12:16:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,405 | java | package expedientesx.modelo.negocio;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import expedientesx.modelo.entidad.Expediente;
import expedientesx.modelo.persistencia.ExpedientesDao;
public class GestorExpedientesImpl implements GestorExpendientes {
@Autowired
private ExpedientesDao expedientesDao;
public void actualizar(Expediente expediente) {
expedientesDao.guardar(expediente);
System.out.println("Actualizado Expediente: " + expediente);
}
public void clasificar(Expediente expediente) {
if (!expediente.isClasificado()) {
expediente.setClasificado(true);
actualizar(expediente);
System.out.println("Expediente Clasificado: " + expediente);
}
}
public void desclasificar(Expediente expediente) {
if (expediente.isClasificado()) {
expediente.setClasificado(false);
actualizar(expediente);
System.out.println("Expediente Desclasificado: " + expediente);
}
}
public List<Expediente> listarTodos() {
List<Expediente>expedientes=expedientesDao.listar();
System.out.println("Mostrar "+expedientes.size()+" Expedientes: " + expedientes.toString());
return expedientes;
}
public Expediente mostrar(Long id) {
Expediente expediente=expedientesDao.buscar(id);
System.out.println("Mostrar Expediente: " + expediente.toString());
return expediente;
}
}
| [
"ATSTAFF"
] | ATSTAFF |
37dc73e96625aa08af32350a9e35bef0b80bc936 | da5ce7545d453663373487bdf6d4d983dcffb3b4 | /springboot/springboot-aop/src/main/java/com/zhihao/miao/service/OrderService.java | 6685a8dedf91de85520c0cd68469e0628ae0e4d2 | [] | no_license | jorfeng/springboot-demos | 738a707c08fa8c392a534db20638b3aea08542ea | 84d7e45250f92ba6c81f3c626dd009dce9be3f42 | refs/heads/master | 2020-03-23T21:30:09.950893 | 2018-05-29T10:22:49 | 2018-05-29T10:22:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 285 | java | package com.zhihao.miao.service;
import org.springframework.stereotype.Service;
/**
* @Auther : 苗志浩 (zhihao.miao@ele.me)
* @Date :2017/7/29
* @since 1.0
*/
@Service("orderService")
public class OrderService {
public String name(){
return "order home";
}
}
| [
"zhihao.miao@ele.me"
] | zhihao.miao@ele.me |
7c8df67f93f2305fe160f71c7ae7ccb64070bc18 | a16369facaad30e8560ee8f85770375e710223f7 | /jetsencloud/src/main/java/com/chanlin/jetsencloud/util/SystemShare.java | 00b92dd3cca6634c9455699621597275305df507 | [] | no_license | jecn/jetsen | c595bf36b255a0624a0daf07829e9be87f904243 | bad286f723b26aa9e48016b4b704499df57e514f | refs/heads/master | 2021-05-14T03:39:38.096781 | 2020-04-09T08:35:10 | 2020-04-09T08:35:10 | 116,622,373 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,690 | java | package com.chanlin.jetsencloud.util;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by ChanLin on 2017/11/20.
* ProtectEyes
* TODO:
*/
public class SystemShare {
private static final String PREFIX_NAME = "jetsen_catch";
/**
* 保存String类型数据
*
* @param context
* @param key
* @param value
*/
public static void setSettingString(Context context, String key,
String value) {
SharedPreferences clientPreferences = context.getSharedPreferences(
PREFIX_NAME, Context.MODE_MULTI_PROCESS);
SharedPreferences.Editor prefEditor = clientPreferences.edit();
prefEditor.putString(key, value);
prefEditor.commit();
}
/**
* 获取String类型数据
*
* @param context
*/
public static String getSettingString(Context context, String strKey) {
SharedPreferences clientPreferences = context.getSharedPreferences(
PREFIX_NAME, Context.MODE_MULTI_PROCESS);
String strValue = clientPreferences.getString(strKey, "");
return strValue;
}
/**
* 删除String类型数据
*
* @param context
*/
public static void ClearSettingString(Context context, String strKey) {
SharedPreferences clientPreferences = context.getSharedPreferences(
PREFIX_NAME, Context.MODE_MULTI_PROCESS);
SharedPreferences.Editor prefEditor = clientPreferences.edit();
prefEditor.remove(strKey);
prefEditor.commit();
}
/**
* 保存boolean类型数据
*
* @param context
*/
public static void setSettingBoolean(Context context, String strKey,
boolean value) {
SharedPreferences clientPreferences = context.getSharedPreferences(
PREFIX_NAME, Context.MODE_MULTI_PROCESS);
SharedPreferences.Editor prefEditor = clientPreferences.edit();
prefEditor.putBoolean(strKey, value);
prefEditor.commit();
}
/**
* 获取boolean类型数据
*
* @param context
*/
public static boolean getSettingBoolean(Context context, String strKey) {
SharedPreferences clientPreferences = context.getSharedPreferences(
PREFIX_NAME, Context.MODE_MULTI_PROCESS);
boolean value = clientPreferences.getBoolean(strKey, false);
return value;
}
public static boolean getSettingBoolean(Context context, String strKey,
boolean value) {
SharedPreferences clientPreferences = context.getSharedPreferences(
PREFIX_NAME, Context.MODE_MULTI_PROCESS);
boolean ret = clientPreferences.getBoolean(strKey, value);
return ret;
}
/**
* 保存int类型数据
*
* @param context
* @param value
*/
public static void setSettingInt(Context context, String strKey, int value) {
SharedPreferences clientPreferences = context.getSharedPreferences(
PREFIX_NAME, Context.MODE_MULTI_PROCESS);
SharedPreferences.Editor prefEditor = clientPreferences.edit();
prefEditor.putInt(strKey, value);
prefEditor.commit();
}
/**
* 获取int类型数据
*
* @param context
*/
public static int getSettingInt(Context context, String strKey) {
SharedPreferences clientPreferences = context.getSharedPreferences(
PREFIX_NAME, Context.MODE_MULTI_PROCESS);
int value = clientPreferences.getInt(strKey, 0);
return value;
}
}
| [
"xlwei920@163.com"
] | xlwei920@163.com |
09f22643a2d2eac411c767de5aa298081b49c315 | 42b3f807f81f89eecb384858d28ac58577647c2e | /src/Actions/SendMessage.java | 6f97a1ffa14ef3a0bdaafd238da28708745789bd | [] | no_license | HomieTaken/E-Commerce_Campus_Culture | ffd6ca95feebac19a5af9a9fde5f3d31aad44483 | 231de69de783fe42acf7209c24569b3f3678fd69 | refs/heads/master | 2020-03-22T05:41:54.218357 | 2018-07-21T14:31:04 | 2018-07-21T14:31:04 | 139,584,151 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,520 | java | package Actions;
import DataBase.DBOperation;
import Entity.Activity;
import Entity.Team;
import Operations.MessageOperate;
import Operations.ViewProduct;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;
import javax.swing.text.View;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.ResultSet;
public class SendMessage implements Action {
private String updateMessage;
private File pictureFile;
private int updateActivity;
private int updateTeamID;
private int reportTeamID;
private String briefReportSchool;
private String detailReportSchool;
private int receivedUser;
private int relatedProID;
public int getRelatedProID() {
return relatedProID;
}
public void setRelatedProID(int relatedProID) {
this.relatedProID = relatedProID;
}
public int getReceivedUser() {
return receivedUser;
}
public void setReceivedUser(int receivedUser) {
this.receivedUser = receivedUser;
}
public String getBriefReportSchool() {
return briefReportSchool;
}
public String getDetailReportSchool() {
return detailReportSchool;
}
public void setBriefReportSchool(String briefReportSchool) {
this.briefReportSchool = briefReportSchool;
}
public void setDetailReportSchool(String detailReportSchool) {
this.detailReportSchool = detailReportSchool;
}
public int getReportTeamID() {
return reportTeamID;
}
public void setReportTeamID(int reportTeamID) {
this.reportTeamID = reportTeamID;
}
public int getUpdateTeamID() {
return updateTeamID;
}
public void setUpdateTeamID(int updateTeamID) {
this.updateTeamID = updateTeamID;
}
public int getUpdateActivity() {
return updateActivity;
}
public void setUpdateActivity(int updateActivity) {
this.updateActivity = updateActivity;
}
public File getPictureFile() {
return pictureFile;
}
public String getUpdateMessage() {
return updateMessage;
}
public void setPictureFile(File pictureFile) {
this.pictureFile = pictureFile;
}
public void setUpdateMessage(String updateMessage) {
this.updateMessage = updateMessage;
}
@Override
public String execute() {
try {
ResultSet rs=MessageOperate.addActivityMessageRecord(updateActivity,updateMessage,pictureFile);
if(rs.next())
{
MessageOperate.sendToAllPeople(rs.getInt(1),updateActivity);
}
return SUCCESS;
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
public String comment(){
ActionContext actionContext=ActionContext.getContext();
Object user_id = actionContext.getSession().get("user_id");
if(user_id==null){
return "fail";
}
int userID=(int) user_id;
ResultSet rs = MessageOperate.addProCommentMessage(userID,relatedProID,updateMessage,pictureFile);
try {
if (rs.next()) {
// MessageOperate.addMessageToUser(rs.getInt(1), updateTeamID);
int teamID=ViewProduct.viewGivenPro(relatedProID).getTeamID();
MessageOperate.addMessageToUser(rs.getInt(1),teamID);
// MessageOperate.sendToUser(updateTeamID);
MessageOperate.sendToUser(teamID);
}
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
public String report(){
ActionContext actionContext=ActionContext.getContext();
Object user_id = actionContext.getSession().get("user_id");
if(user_id==null){
return "fail";
}
int userID=(int) user_id;
ResultSet rs = MessageOperate.addReportMessage(reportTeamID,userID,briefReportSchool,detailReportSchool,pictureFile);
try {
if (rs.next()) {
MessageOperate.addMessageToUser(rs.getInt(1),Team.getTeam(reportTeamID).getTeamSchool_id());
//MessageOperate.sendToUser(Team.getTeam());
}
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
public String responseUser(){
ActionContext actionContext=ActionContext.getContext();
Object user_id = actionContext.getSession().get("user_id");
if(user_id==null){
return "fail";
}
int userID=(int) user_id;
ResultSet rs = MessageOperate.addProCommentMessage(userID,relatedProID,updateMessage,pictureFile);
try {
if (rs.next()) {
MessageOperate.addMessageToUser(rs.getInt(1),receivedUser);
MessageOperate.sendToUser(receivedUser);
}
} catch (Exception e) {
e.printStackTrace();
}
// addAndSendMessage(rs,receivedUser);
return SUCCESS;
}
/* public void addAndSendMessage(ResultSet rs,int receiver){
try {
if (rs.next()) {
MessageOperate.addMessageToUser(rs.getInt(1),receivedUser);
MessageOperate.sendToUser(receivedUser);
}
} catch (Exception e) {
e.printStackTrace();
}
}*/
}
| [
"1812657725@qq.com"
] | 1812657725@qq.com |
0c986a2a5263a3af0edffc47656b6594f4ca7d1a | 5c2aedfa4b46aae3a90e73e39f11107dde8a9658 | /shiro-demo5/src/main/java/com/company/service/RoleService.java | 2e34cfbd340a6568c90508bcb8fa69aa90f59589 | [] | no_license | desperadoty/shiro | 9d6af1cf02d9432202d86bc342323163f80668b5 | 6d74f5c0d06fd02e30bb024b8a7750bbdb34c587 | refs/heads/master | 2021-07-04T09:59:50.729248 | 2017-09-26T15:57:56 | 2017-09-26T15:57:56 | 104,900,680 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 725 | java | package com.company.service;
import com.company.entity.Role;
/**
* Created by Administrator on 2017/5/23.
*/
public interface RoleService {
/**
* 添加角色
* @param role
* @return
*/
public Role createRole(Role role);
/**
* 移除角色
* @param roleId
*/
public void deleteRole(Long roleId);
/**
* 添加角色-权限之间的关系
* @param roleId
* @param permissionIds
*/
public void correlationPermissions(Long roleId, Long... permissionIds);
/**
* 移除角色-权限之间的关系
* @param roleId
* @param permissionIds
*/
public void uncorrelatonPermissions(Long roleId, Long... permissionIds);
}
| [
"desperadoty@gmail.com"
] | desperadoty@gmail.com |
f3c1073cb828d13a243c3f39eaf632f00735c994 | 7268ffeaec970c15da39ac3bb9a4c75970c6b1f3 | /app/src/main/java/com/example/guilhermedeoliveira/movieme/model/MovieSchema.java | 0c45e7916c69a857bf84a78ba685a98da034ff97 | [] | no_license | guilhermedeoliveira/movieme | 0f791fc2570efc6f80793e0b6cc084761d4ee669 | 1be4aa1b988486498c642826095946586a893aa1 | refs/heads/master | 2021-01-11T02:28:48.135126 | 2016-11-01T20:17:21 | 2016-11-01T20:17:21 | 70,925,288 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 808 | java | package com.example.guilhermedeoliveira.movieme.model;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by guilhermeoliveira on 20/10/16.
*/
public class MovieSchema {
@SerializedName("page")
private int mPage;
@SerializedName("results")
private List<Movie> mListMovie;
@SerializedName("total_results")
private int mTotalMovies;
@SerializedName("total_pages")
private int mTotalPages;
public int getPage() {
return mPage;
}
public void setPage(int page) {
this.mPage = page;
}
public List<Movie> getListMovie() {
return mListMovie;
}
public int getTotalMovies() {
return mTotalMovies;
}
public int getTotalPages() {
return mTotalPages;
}
}
| [
"contatoguilhermedeoliveira@gmail.com"
] | contatoguilhermedeoliveira@gmail.com |
74d343882d3853fdb610e9ffb6adb06f10d8e9c9 | f2958a88cd84aa2a47464ce603e7146bc88226c6 | /app/src/main/java/com/cqsynet/swifi/model/UrlRuleResponseObject.java | 24e7d1595fffc581126bbe72ce955a784aec22ac | [] | no_license | siyangstar/heikuai | 65ebccd1bd513dd2fefe2313821214cc407e41ef | bdcb0d6a44f9490e5dbd51ea7b6d7a4756a273b9 | refs/heads/master | 2021-05-01T22:15:55.384023 | 2019-09-10T06:57:20 | 2019-09-10T06:57:20 | 120,885,648 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 296 | java | /*
* Copyright (C) 2014 重庆尚渝
* 版权所有
*
* 功能描述:网址黑白名单返回数据结构对象
*
*
* 创建标识:zhaosy 20170623
*/
package com.cqsynet.swifi.model;
public class UrlRuleResponseObject extends BaseResponseObject {
public UrlRuleResponseBody body;
}
| [
"siyangstar@msn.com"
] | siyangstar@msn.com |
280922d7494cee37c796f0a7aa8266d8dd693d0f | 1f2749e514fc65d22fa6cf1da697cb493ea4fa26 | /myJava/src/com/zhao/vv/collections/set/TreeSetTest2.java | 398a358f1013f46fac8b2476b87ff23a36d71a0b | [] | no_license | LotharZhao/myXidian | 96ae5c690082d7b11c562e64891f814f4304ea6e | 5a4b25d1d9c209781132e698a204cd515ba65a97 | refs/heads/master | 2020-03-11T23:11:07.253621 | 2018-05-03T07:31:10 | 2018-05-03T07:31:10 | 130,314,833 | 4 | 0 | null | null | null | null | GB18030 | Java | false | false | 666 | java | package com.zhao.vv.collections.set;
import java.util.Comparator;
import java.util.TreeSet;
class M {
int age;
public M(int age) {
this.age = age;
}
public String toString() {
return "M[age:" + age + "]";
}
}
public class TreeSetTest2 {
public static void main(String[] args) {
TreeSet ts = new TreeSet<M>(new Comparator() {
// 根据M对象的age属性来决定大小
public int compare(Object o1, Object o2) {
M m1 = (M) o1;
M m2 = (M) o2;
return m1.age > m2.age ? -1 : m1.age < m2.age ? 1 : 0;
}
});
ts.add(new M(5));
ts.add(new M(-3));
ts.add(new M(9));
System.out.println(ts);
}
} | [
"iuui1995@163.com"
] | iuui1995@163.com |
2cf6332b639fdee076197a291683e032112b9d6f | 8d2ca9a6a69df8b0a125bc97d703ca9f7b1dddb9 | /app/src/androidTest/java/com/example/learnest/ExampleInstrumentedTest.java | 70b788bec3a9551a30ff1e36048ce9ebb105f4c1 | [] | no_license | aashutosh227/Learnest | 4fe989e669e834369aa0c519224bc141f632b51d | 036b75d1dbe8eed2e7576cd27807326473e5566b | refs/heads/master | 2020-09-23T05:41:10.429456 | 2019-12-02T16:39:55 | 2019-12-02T16:39:55 | 225,419,057 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 745 | java | package com.example.learnest;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.learnest", appContext.getPackageName());
}
}
| [
"aashutoshsingh126@gmail.com"
] | aashutoshsingh126@gmail.com |
dad723a0adb4021b45fd368b013466f7785a3688 | 54f352a242a8ad6ff5516703e91da61e08d9a9e6 | /Source Codes/AtCoder/arc058/A/1677896.java | fd8c9b540767c498fdb2cf57c890aa8788912fdd | [] | no_license | Kawser-nerd/CLCDSA | 5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb | aee32551795763b54acb26856ab239370cac4e75 | refs/heads/master | 2022-02-09T11:08:56.588303 | 2022-01-26T18:53:40 | 2022-01-26T18:53:40 | 211,783,197 | 23 | 9 | null | null | null | null | UTF-8 | Java | false | false | 4,298 | java | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class a {
public a(int i, int j, int k) {
p1 = i;
p2 = j;
length = k;
}
int p1;
int p2;
int length;
}
public class Main {
static boolean debug = true;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws Exception {
int N=sc.nextInt();
int k=sc.nextInt();
Set<Integer> s=new HashSet();
for(int i=0;i<k;i++)
s.add(sc.nextInt());
System.out.println(helper(N,s));
}
private static int helper(int n, Set<Integer> s) {
// TODO Auto-generated method stub
while(true){
String str=""+n;
boolean tag=true;
for(char c:str.toCharArray()){
if(s.contains(c-'0')){
tag=false;
break;
}
}
if(tag)
return n;
++n;
}
}
private static int helper(int[] arr) {
// TODO Auto-generated method stub
int res = 0;
for (int i = 1; i < arr.length - 1; i++) {
if (arr[i] == i && arr[i + 1] == (i + 1)) {
int tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
++i;
++res;
}
}
for (int i = 1; i < arr.length; i++) {
if (arr[i] == i) {
++res;
}
}
return res;
}
private static void print(String string) {
// TODO Auto-generated method stub
if (debug)
System.out.println(string);
}
private static void print(int[] data) {
if (debug) {
for (int i = 0; i < data.length; i++)
System.out.println(i + ":" + data[i]);
}
}
private static void print(String[] data) {
if (debug) {
for (int i = 0; i < data.length; i++)
System.out.println(i + ":" + data[i]);
}
}
private static void print(char[] data) {
if (debug) {
for (int i = 0; i < data.length; i++)
System.out.println(i + ":" + data[i]);
}
}
private static void print(double[] data) {
if (debug) {
for (int i = 0; i < data.length; i++)
System.out.println(i + ":" + data[i]);
}
}
private static void print(long[] data) {
if (debug) {
for (int i = 0; i < data.length; i++)
System.out.println(i + ":" + data[i]);
}
}
private static void print(int[][] data) {
if (debug) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[0].length; j++) {
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
}
private static void print(long[][] data) {
if (debug) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[0].length; j++) {
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
}
private static void print(char[][] data) {
if (debug) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[0].length; j++) {
System.out.print(i + " " + j + ":" + data[i][j] + " ");
}
System.out.println();
}
}
}
private static void print(String[][] data) {
if (debug) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[0].length; j++) {
System.out.print(i + " " + j + ":" + data[i][j] + " ");
}
System.out.println();
}
}
}
private static void print(double[][] data) {
if (debug) {
for (int i = 0; i < data[0].length; i++) {
for (int j = 0; j < data.length; j++) {
System.out.print(i + " " + j + ":" + data[i][j] + " ");
}
System.out.println();
}
}
}
public static void inPutData(char[][] c) {
for (int i = 0; i < c.length; i++) {
c[i] = sc.nextLine().toCharArray();
}
}
} Note: ./Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details. | [
"kwnafi@yahoo.com"
] | kwnafi@yahoo.com |
750ebe142210083f7e41e9b4fbfc934a3712cb50 | 5b8e0457c162cf526c6f68cf48d55966f9c55982 | /basesystem_web/src/main/java/org/car/common/utils/MD5.java | bce2b748b531f34fa41711ba11e61b688eb60a7d | [] | no_license | songwangwen/basesystem | 128c14bc6f4d81a43113be652aec038312ede8e2 | 82e2e29d1d9f260ae196bdf9055dcb4840bc5c02 | refs/heads/master | 2021-01-10T23:32:21.982317 | 2016-03-18T07:59:14 | 2016-03-18T07:59:14 | 54,184,111 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,564 | java | package org.car.common.utils;
import java.io.UnsupportedEncodingException;
import java.security.SignatureException;
import org.apache.commons.codec.digest.DigestUtils;
public class MD5{
private static MD5 md5;
// 产生一个MD5实例
public static MD5 getInstance() {
if (null != md5){
return md5;}
else {
makeInstance();
return md5;
}
}
// 保证同一时间只有一个线程在使用MD5加密
private static synchronized void makeInstance() {
if (null == md5)
md5 = new MD5();
}
/**
* 对字符串进行MD5签名
*
* @param text
* 明文
* @param charset
* 字符编码
*
* @return 密文
*/
public String getMd5(String text,String charset) {
return DigestUtils.md5Hex(getContentBytes(text, charset));
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
private byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
public static void main(String[] args) {
System.out.println(MD5.getInstance().getMd5("123456","UTF-8"));
}
}
| [
"songwangwen@163.com"
] | songwangwen@163.com |
fc7de60494ab9fc517c5d4935c3ce3aba3be439c | a8f0b3c17f773f4d3db3f3e79c6a64079f30a36c | /src/test/java/com/tw/BalanceFinderTest.java | 446809f36237bffb72042a7388a3044d4e27bcf7 | [] | no_license | JiaHaohu/silver-java-level-2 | 5d8a35b0e767471b5f86552d2cc2e76f02d5e1db | 1d045e0783aad320c2d28809934fd393ce61fd9e | refs/heads/master | 2022-09-30T11:04:30.220465 | 2020-06-07T09:10:35 | 2020-06-07T09:10:35 | 270,209,278 | 0 | 0 | null | 2020-06-07T05:58:24 | 2020-06-07T05:58:23 | null | UTF-8 | Java | false | false | 1,848 | java | package com.tw;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class BalanceFinderTest {
private static Stream<Arguments> createBalancedArray() {
//noinspection RedundantCast
return Stream.of(
Arguments.of((Object)new int[] {1, 1, 1, 2, 1}),
Arguments.of((Object)new int[] {10, 10}),
Arguments.of((Object)new int[] {10, 0, 1, -1, 10}),
Arguments.of((Object)new int[] {1, 1, 1, 1, 4}),
Arguments.of((Object)new int[] {1, 2, 3, 1, 0, 2, 3}),
Arguments.of((Object)new int[] {1, 1, 1, 2, 1})
);
}
private static Stream<Arguments> createUnbalancedArray() {
//noinspection RedundantCast
return Stream.of(
Arguments.of((Object)new int[] {2, 1, 1, 2, 1}),
Arguments.of((Object)new int[] {2, 1, 1, 1, 4}),
Arguments.of((Object)new int[] {2, 3, 4, 1, 2}),
Arguments.of((Object)new int[] {1, 2, 3, 1, 0, 1, 3}),
Arguments.of((Object)new int[] {1})
);
}
@ParameterizedTest
@MethodSource("createBalancedArray")
void should_return_true_if_balance(int[] balanced) {
assertTrue(BalanceFinder.isBalanced(balanced));
}
@ParameterizedTest
@MethodSource("createUnbalancedArray")
void should_return_false_if_not_balance(int[] unbalanced) {
assertFalse(BalanceFinder.isBalanced(unbalanced));
}
@Test
void should_return_false_if_array_is_empty() {
assertFalse(BalanceFinder.isBalanced(new int[0]));
}
} | [
"lxconan@gmail.com"
] | lxconan@gmail.com |
b7f27334b11d764bb14946efdb5a367d5e316806 | 8ec9c8921ec3d6d3d313df8f500a97a5faf5b8a6 | /guigu_controller/src/main/java/com/guigu/controller/curriculum/CourseInfoController.java | bec2b84b98eac8b852a4bcb5a859447c55b40f08 | [] | no_license | johny751/StuMgr-Java | e4b28db6977efb6e8bca771d9aab6d9a0466672c | 8d52c5d7a4351c0aeade72e0b9169c69c00b4bc6 | refs/heads/master | 2023-03-30T12:29:43.230846 | 2019-03-05T09:01:56 | 2019-03-05T09:01:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,596 | java | package com.guigu.controller.curriculum;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.guigu.dao.curriculum.CourseInfoMapper;
import com.guigu.domain.curriculum.Stage_course;
import com.guigu.domain.curriculum.vo.Course_addInfo;
import com.guigu.domain.curriculum.vo.Course_detailInfo;
import com.guigu.domain.curriculum.vo.Course_search;
import com.guigu.domain.eduoffice.LayUiPageInfo;
import com.guigu.service.curriculum.CourseInfoService;
/**
* 课程信息处理器类
* @author zy
*
*/
@Controller
@RequestMapping("/courseInfo")
public class CourseInfoController {
@Autowired
private CourseInfoService courseInfoService;
/**
* 加载下拉框课程数据
* @return
*/
@RequestMapping("/loadSelectCourseInfo")
public @ResponseBody List<CourseInfoMapper> loadSelectCourseInfo(String emp_id){
return this.courseInfoService.loadSelectCourseInfo(emp_id);
}
/**
* 查询所有显示的课程信息
*/
@RequestMapping("/queryAllCourseInfo")
public @ResponseBody LayUiPageInfo queryAllCourseInfo(int page,int limit,Course_search c_search){
System.out.println("---------------------------");
return this.courseInfoService.queryAllCourseInfo(page, limit,c_search);
}
/**
* 根据课程编号查询出该课程的所有信息
*
*/
@RequestMapping("/queryCourseInfoById")
public ModelAndView queryCourseInfoById(String tc_cid){
ModelAndView mav=new ModelAndView();
Course_detailInfo c_d=this.courseInfoService.queryCourseInfoById(tc_cid);
mav.setViewName("forward:/curriculumAndEduoffice/curriculum/Course_detailInfo.jsp");
mav.addObject("course",c_d);
return mav;
}
/**
* 根据课程编号查询出该课程所有的章节信息
*/
@RequestMapping("/querySectionsByCourseId")
public @ResponseBody LayUiPageInfo querySectionsByCourseId(int page,int limit,String tc_cid){
return this.courseInfoService.querySectionsByCourseId(page,limit,tc_cid);
}
/**
* 添加课程阶段信息
* @param stage_course
* @return addStage
*/
@RequestMapping("/addCourseinfo.action")
public @ResponseBody String addCourseinfo(Stage_course stage_course) {
return "添加失败";
}
/*
* 课程大纲上传Controller
* */
@RequestMapping(value = "/FileCourse" , method = RequestMethod.POST)
@ResponseBody
public JSONObject FileCoures(HttpServletRequest servletRequest,@RequestParam("file") MultipartFile file) throws IOException{
//如果文件内容不为空,就写入上传路径
JSONObject res = new JSONObject();
JSONObject resUrl = new JSONObject();
if(!file.isEmpty()) {
//获取原文件名称
String originalFilename =file.getOriginalFilename();
//获取原文件扩展名
String suffName=originalFilename.substring(originalFilename.lastIndexOf("."));
//产生新的文件名称
String newFilename=UUID.randomUUID()+suffName;
//上传文件路径
String path = servletRequest.getSession().getServletContext().getRealPath("/curriculumAndEduoffice/curriculum/stage");
//打印出文件名称
System.out.println("文件名称"+newFilename);
//上传文件名
File filepath=new File(path,newFilename);
//判断路径是否存在,没有的话就创建一个
if(!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文档中
File file1= new File(path+File.separator+newFilename);
file.transferTo(file1);
//返回的是一个URL对象
resUrl.put("url",file1.getPath());
res.put("code", 0);
res.put("msg", "");
res.put("data", resUrl);
System.out.println(res);
return res;
}else {
return res;
}
}
/**
*
*删除课程(逻辑删除,修改课程状态)
*/
@RequestMapping("/deleteCourseById")
@ResponseBody
public String deleteCourseById(String tc_cid){
// ModelAndView mav=new ModelAndView();
try {
this.courseInfoService.deleteCourseById(tc_cid);
return "ok";
} catch (Exception e) {
e.printStackTrace();
return "fail";
}
// mav.setViewName("forward:/curriculumAndEduoffice/curriculum/CourseInfo.jsp");
// return mav;
}
/**
* 根据表单提交的课程信息进行修改
*/
@RequestMapping("/updateCourseInfoById")
//参数列表: 课程基本信息对象 上传文件对象 选择的阶段编号(实现文件上传和创建文件时再启用)
public ModelAndView updateCourseInfoById(Course_detailInfo c_d,File f,String tc_sid){
ModelAndView mav=new ModelAndView();
try {
//修改课程基本信息
this.courseInfoService.updateCourseInfoById(c_d);
if(f!=null|| !f.exists() || f.length()!=0){
//修改课程的教学大纲
this.courseInfoService.updateCoutlineById(c_d.getTc_coutline(),c_d.getTc_cid());
}
//修改课程所属阶段
this.courseInfoService.updateCourseStageById(tc_sid,c_d.getTc_cid());
mav.addObject("message","修改成功!");
} catch (Exception e) {
e.printStackTrace();
mav.addObject("message","修改失败!");
}
mav.setViewName("forward:/curriculumAndEduoffice/curriculum/CourseInfo.jsp");
return mav;
}
/**
* 删除某个课程的章节(逻辑删除:修改状态)
*/
@RequestMapping("/deleteCourseSectionById")
public @ResponseBody String deleteCourseSectionById(String s_id){
String message="ok";
try {
this.courseInfoService.deleteCourseSectionById(s_id);
} catch (Exception e) {
message="fail";
e.printStackTrace();
}
return message;
}
/**
* 添加课程信息
*/
@RequestMapping("/addCouseInfo")
public @ResponseBody String addCouseInfo(Course_addInfo c_a){
String message="ok";
try {
//添加课程信息
this.courseInfoService.addCouseInfo(c_a);
//添加课程的阶段信息
this.courseInfoService.addCourseStage(c_a.getTc_sid());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
message="fail";
}
return message;
}
}
| [
"103305656@example.com"
] | 103305656@example.com |
f7fe30550e71ead951e2a6cfa793037157a3fb52 | 092886677ee219c04e7ebe3ff54bef85819b550e | /259/solution.java | 6ae5ac71472401fb72bc18c473ff79a70f7d94f3 | [] | no_license | kikixie95/leetcode | 9cbbeb311c97cedb6f04403f5a6fb2d74bd2b088 | cf92e5dd7c6de7b71b09bd722647f1f80f542668 | refs/heads/master | 2020-11-26T17:14:54.897315 | 2020-08-06T01:00:49 | 2020-08-06T01:00:49 | 229,153,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,086 | java | // brute force
class Solution {
public int threeSumSmaller(int[] nums, int target) {
int count = 0;
for(int i = 0; i < nums.length-2; i++){
for(int j = i+1; j < nums.length-1; j++){
for(int k = j+1; k < nums.length; k++){
if(nums[i]+nums[j]+nums[k] < target){
count++;
}
}
}
}
return count;
}
}
// three pointers
class Solution {
public int threeSumSmaller(int[] nums, int target) {
int count = 0;
Arrays.sort(nums);
for(int i = 0; i < nums.length-2; i++){
int low = i+1;
int high = nums.length-1;
while(low < high){
if(nums[i] + nums[low] + nums[high] < target){
count = count + high - low;
low++;
}else {
high-- ;
}
}
}
return count;
}
}
| [
"kikixie95@gmail.com"
] | kikixie95@gmail.com |
d67837ece94d31cb5cb337543c92ef1780fffbb6 | 3ebc80bfa82a967d788cc30858eaebcd5ff5da55 | /module_4/casestudy-module4/src/main/java/com/example/casestudymodule4/model/service/service/Impl/ServiceTypeServiceImpl.java | 1f4d49859f920ef5e2b82cdb98277d5b6e6f68a4 | [] | no_license | anhtannguyen2011/C0221G1-NguyenAnhTan | d96e07650fa76a8e2414617e176908de0da58c36 | c5675642a6fc3fbfd2df6e4ab0ad587d5a9c0617 | refs/heads/main | 2023-06-27T14:49:16.457643 | 2021-08-01T03:27:42 | 2021-08-01T03:27:42 | 342,121,566 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 696 | java | package com.example.casestudymodule4.model.service.service.Impl;
import com.example.casestudymodule4.model.entity.service.ServiceType;
import com.example.casestudymodule4.model.repository.service.IServiceTypeRepository;
import com.example.casestudymodule4.model.service.service.IServiceTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ServiceTypeServiceImpl implements IServiceTypeService {
@Autowired
private IServiceTypeRepository serviceTypeRepository;
@Override
public List<ServiceType> findAll() {
return serviceTypeRepository.findAll();
}
}
| [
"anhtannguyen2011@gmail.com"
] | anhtannguyen2011@gmail.com |
a6bb0c4fe43fb4b19c1327d72b59e4e7ef309590 | 2e7de32578b86ae47caa67dad03c956c100552de | /src/gamesettings/GameMath.java | 4f5009bd58f7738f991183fd4352787613322592 | [] | no_license | randyuncle/PD2-final-group-project | 8e84ca2220bf2aa6aa21ab3f3bb8ccb6525d216c | 6a065766b98ce727aba70262e7fd52c3cde43657 | refs/heads/main | 2023-05-08T09:09:39.437047 | 2021-06-03T06:46:20 | 2021-06-03T06:46:20 | 373,125,801 | 0 | 0 | null | null | null | null | BIG5 | Java | false | false | 4,351 | java | package gamesettings;
/**
* Helps with math calculations in the game.
*/
public class GameMath {
/**
* Calculates the distance between two points by using the distance formula.
*
* @param x1 The x-coordinate of the first point.
* @param y1 The y-coordinate of the first point.
* @param x2 The x-coordinate of the second point.
* @param y2 The y-coordinate of the second point.
*
* @return The distance between (x1,y1) and (x2,y2).
*/
public static double calculateDistance(double x1, double y1, double x2, double y2) {
return Math.sqrt(Math.pow(x1-x2, 2)+Math.pow(y1-y2,2));
}
/**
* Calculates the slope between two points. Uses a proportion to scale the
* slope so every bullet moves at the same pace. To do that, use the
* following sequence:
*
* First find the rise (y2-y1) and the run (x2-x1) and recored if they
* are negative.
*
* Find the bigger number; this will be the rise or the run.
* For this example, it will be rise.
*
* If the rise was the bigger number, then do the following.
* run = (Settings.SCALE_MAX * run) / rise;
*
* Set the rise to the value stored in Settings.SCALE_MAX.
* rise = Settings.SCALE_MAX;
*
* If the run was the bigger number, then do the following:
* rise = (Settings.SCALE_MAX * rise) / run;
* run = Settings.SCALE_MAX;
*
* In both instances, the bigger value will be set to Settings.SCALE_MAX.
*
* @param x1 The x-coordinate of the first point.
* @param x2 The x-coordinate of the second point.
* @param y1 The y-coordinate of the first point.
* @param y2 The y-coordinate of the second point.
*
* @return An array containing the slope's rise and run.
*/
public static double[] calculateSlope(double x1, double x2, double y1, double y2) {
double rise = y2 - y1, run = x2 - x1;
boolean nRise = false; // negative rise
boolean nRun = false; // negative run
if (rise < 0) {
rise *= -1;
nRise = true;
}
if (run < 0) {
run *= -1;
nRun = true;
}
//以下演算法,造成斜率=rise/run不變
//另外,根據Settings內的說明:SCALE_MAX=20,值是隨意定出的
if (Math.max(rise, run) == rise) {
run = (gamesettings.Settings.SCALE_MAX * run) / rise;
rise = gamesettings.Settings.SCALE_MAX;
} else {
rise = (gamesettings.Settings.SCALE_MAX * rise) / run;
run = gamesettings.Settings.SCALE_MAX;
}
if (nRise) rise *= -1;
if (nRun) run *= -1;
return new double[]{rise,run};
}
/**
* Calculates the angle that two points form. The third point is the point
* that forms a right triangle with the two points that were given. Calculate
* the angle by using the following sequence:
*
* Find the opposite side's length:
* Calculate: y2 - y1.
*
* Find the distance between (x1,y1) and (x2,y2) for hypotenuse:
* Calculate: call calculateDistance(x1,y1,x2,y2)
*
* Find the inverse sin of opp/hyp:
* Math.asin((y2-y1)/calculateDistance(x1,y1,x2,y2))
*
* Convert the result from radians to degrees:
* Math.toDegrees(result);
*
* @param x1 The x-coordinate of the first point.
* @param y1 The y-coordinate of the first point.
* @param x2 The x-coordinate of the second point.
* @param y2 The y-coordinate of the second point.
*
* @return Angle created by those points.
*/
public static double calculateAngle(double x1, double y1, double x2, double y2) {
double angle = Math.toDegrees(Math.asin((y1-y2)/calculateDistance(x1,y1,x2,y2)));
if (x1 < x2) {angle = 180 - angle;}
if (angle < 0) {angle += 360;}
return angle;
}
}
| [
"74038554+randyuncle@users.noreply.github.com"
] | 74038554+randyuncle@users.noreply.github.com |
5318bcb173702936088ba638b1b37394c6adbaf5 | 73267be654cd1fd76cf2cb9ea3a75630d9f58a41 | /services/cdm/src/main/java/com/huaweicloud/sdk/cdm/v1/model/ShowJobsResponse.java | 588030307111f944b8dd7c74053ea4280fe5d592 | [
"Apache-2.0"
] | permissive | huaweicloud/huaweicloud-sdk-java-v3 | 51b32a451fac321a0affe2176663fed8a9cd8042 | 2f8543d0d037b35c2664298ba39a89cc9d8ed9a3 | refs/heads/master | 2023-08-29T06:50:15.642693 | 2023-08-24T08:34:48 | 2023-08-24T08:34:48 | 262,207,545 | 91 | 57 | NOASSERTION | 2023-09-08T12:24:55 | 2020-05-08T02:27:00 | Java | UTF-8 | Java | false | false | 4,034 | java | package com.huaweicloud.sdk.cdm.v1.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.huaweicloud.sdk.core.SdkResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
/**
* Response Object
*/
public class ShowJobsResponse extends SdkResponse {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "total")
private Integer total;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "jobs")
private List<Job> jobs = null;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "page_no")
private Integer pageNo;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "page_size")
private Integer pageSize;
public ShowJobsResponse withTotal(Integer total) {
this.total = total;
return this;
}
/**
* 作业数,查询单个作业时为0
* @return total
*/
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public ShowJobsResponse withJobs(List<Job> jobs) {
this.jobs = jobs;
return this;
}
public ShowJobsResponse addJobsItem(Job jobsItem) {
if (this.jobs == null) {
this.jobs = new ArrayList<>();
}
this.jobs.add(jobsItem);
return this;
}
public ShowJobsResponse withJobs(Consumer<List<Job>> jobsSetter) {
if (this.jobs == null) {
this.jobs = new ArrayList<>();
}
jobsSetter.accept(this.jobs);
return this;
}
/**
* 作业列表,请参见jobs参数说明
* @return jobs
*/
public List<Job> getJobs() {
return jobs;
}
public void setJobs(List<Job> jobs) {
this.jobs = jobs;
}
public ShowJobsResponse withPageNo(Integer pageNo) {
this.pageNo = pageNo;
return this;
}
/**
* 返回指定页号的作业
* @return pageNo
*/
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public ShowJobsResponse withPageSize(Integer pageSize) {
this.pageSize = pageSize;
return this;
}
/**
* 每页作业数
* @return pageSize
*/
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
@Override
public boolean equals(java.lang.Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ShowJobsResponse that = (ShowJobsResponse) obj;
return Objects.equals(this.total, that.total) && Objects.equals(this.jobs, that.jobs)
&& Objects.equals(this.pageNo, that.pageNo) && Objects.equals(this.pageSize, that.pageSize);
}
@Override
public int hashCode() {
return Objects.hash(total, jobs, pageNo, pageSize);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ShowJobsResponse {\n");
sb.append(" total: ").append(toIndentedString(total)).append("\n");
sb.append(" jobs: ").append(toIndentedString(jobs)).append("\n");
sb.append(" pageNo: ").append(toIndentedString(pageNo)).append("\n");
sb.append(" pageSize: ").append(toIndentedString(pageSize)).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 ");
}
}
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
58e3f7aab0fad6b95012b6971c17e0da1f78f545 | 247decc6f92adaa23ee0f8700efe877de0178805 | /src/main/java/com/nkseguridad/app/Controller/VendedorController.java | 7acc49169731136d61ad1a2305e5af72dadaa059 | [] | no_license | Ferproco/nk-seguridad.app | a14aa3d16788d26a8734f04bf49068ec0b7a07fb | c9d5bd8fad6c877694203c68f26b853367dc8b80 | refs/heads/master | 2023-06-25T09:06:13.201320 | 2021-07-20T23:20:53 | 2021-07-20T23:20:53 | 303,004,463 | 0 | 1 | null | 2020-10-19T15:24:11 | 2020-10-10T23:03:24 | Java | UTF-8 | Java | false | false | 3,396 | java | package com.nkseguridad.app.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.nkseguridad.app.Entity.Vendedor;
import com.nkseguridad.app.Service.IVendedorService;
@RestController
@CrossOrigin(origins = "*", methods= {RequestMethod.GET,RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
@RequestMapping("api")
public class VendedorController {
@Autowired
private IVendedorService VendedorService;
@GetMapping("vendedor")
public ResponseEntity<?> ListarVendedores() {
List<Vendedor> LstVendedor = VendedorService.findAll();
if (LstVendedor != null) {
if (LstVendedor.size() != 0) {
return new ResponseEntity<>(LstVendedor, HttpStatus.OK);
} else {
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
} else {
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
}
@GetMapping("vendedor/{codigo}")
public ResponseEntity<?> BuscarPorCodigo(@PathVariable(name = "codigo") String codigo) {
Vendedor Vendedor = VendedorService.findByCodigo(codigo);
if (Vendedor != null) {
return new ResponseEntity<>(Vendedor, HttpStatus.OK);
} else {
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
}
@PostMapping("vendedor")
public ResponseEntity<?> GuardarVendedor(@RequestBody Vendedor vendedor) {
if (!VendedorService.findByExisteCodigo(vendedor.getCodigo())) {
Vendedor VendedorObj = VendedorService.save(vendedor);
return new ResponseEntity<>(VendedorObj, HttpStatus.CREATED);
} else {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
}
@PutMapping("vendedor")
public ResponseEntity<?> ModificarVendedor(@RequestBody Vendedor Vendedor) {
Vendedor VendedorUpdate = VendedorService.findByCodigo(Vendedor.getCodigo());
if (VendedorUpdate != null) {
VendedorUpdate.setNombre(Vendedor.getNombre());
VendedorUpdate.setCobrador(Vendedor.getCobrador());
VendedorUpdate.setCodnegocio(Vendedor.getCodnegocio());
VendedorUpdate.setCodusuario(Vendedor.getCodusuario());
VendedorUpdate.setCodzona(Vendedor.getCodzona());
VendedorUpdate.setCorreoe(Vendedor.getCorreoe());
VendedorUpdate.setDireccionfiscal(Vendedor.getDireccionfiscal());
VendedorUpdate.setInterno(Vendedor.getInterno());
VendedorUpdate.setMontometa(Vendedor.getMontometa());
VendedorUpdate.setStatus(Vendedor.getStatus());
VendedorUpdate.setLstComisiones(Vendedor.getLstComisiones());
Vendedor VendedorResult = VendedorService.updaVendedor(VendedorUpdate);
if (VendedorResult != null) {
return new ResponseEntity<>(VendedorResult, HttpStatus.OK);
} else {
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
| [
"a.araujo.cl@hotmail.com"
] | a.araujo.cl@hotmail.com |
e5219f2936bb8b288cecfaef9498d55e31c3913e | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/16/16_e59b91d017c7d0e8190fdc5fd4626ad0286efbe9/EmbeddedFiles/16_e59b91d017c7d0e8190fdc5fd4626ad0286efbe9_EmbeddedFiles_s.java | f6314fd0b8d26f5ab91c5e921f843c591017434f | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 1,897 | java | package pt.go2.fileio;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import pt.go2.application.Resources;
import pt.go2.response.AbstractResponse;
import pt.go2.response.GzipResponse;
public class EmbeddedFiles implements FileSystemInterface {
final private Map<String, AbstractResponse> pages = new HashMap<>();
public EmbeddedFiles(Configuration config) throws IOException {
final byte[] index, ajax, robots, map, css;
index = SmartTagParser.read(Resources.class
.getResourceAsStream("/index.html"));
ajax = SmartTagParser.read(Resources.class
.getResourceAsStream("/ajax.js"));
robots = SmartTagParser.read(Resources.class
.getResourceAsStream("/robots.txt"));
map = SmartTagParser.read(Resources.class
.getResourceAsStream("/map.txt"));
css = SmartTagParser.read(Resources.class
.getResourceAsStream("/screen.css"));
this.pages.put("/", new GzipResponse(index, ".html"));
this.pages.put("/ajax.js", new GzipResponse(ajax, ".js"));
this.pages.put("/robots.txt", new GzipResponse(robots, ".txt"));
this.pages.put("/sitemap.xml", new GzipResponse(map, ".xml"));
this.pages.put("/screen.css", new GzipResponse(css, ".css"));
if (!config.GOOGLE_VERIFICATION.isEmpty()) {
this.pages
.put(config.GOOGLE_VERIFICATION,
new GzipResponse(
("/google-site-verification: " + config.GOOGLE_VERIFICATION)
.getBytes(), ".html"));
}
}
@Override
public void start() {
}
@Override
public void stop() {
}
@Override
public AbstractResponse getFile(String filename) {
return pages.get(filename);
}
@Override
public List<String> browse() {
List<String> result = new ArrayList<>(pages.size());
result.addAll(pages.keySet());
return result;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
c1667dea2eb5ffe966eef5b3dd62fc0bdcebf3fd | 159997bda907cb16b3bd01838e309689d6041b24 | /src/main/java/curso/springboot/controller/ReportUtil.java | afde0220ce529b4626d7f73bda7325826f8ad2a2 | [] | no_license | GuilhermeJWT/SpringMvc-Jenkins-Thymeleaf-Heroku | b05e09225d2814eb6f568bd95d5c9a77aa0726e0 | 1db62f7a941cbf9a45a40372d4c0b4d4ec698d7b | refs/heads/main | 2023-06-16T04:09:20.321173 | 2021-07-14T22:02:12 | 2021-07-14T22:02:12 | 386,086,482 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,341 | java | package curso.springboot.controller;
import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletContext;
import org.springframework.stereotype.Component;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
@Component
public class ReportUtil implements Serializable{
private static final long serialVersionUID = 1L;
/*Retorna nosso PDF em Byte para download no navegador*/
public byte[] gerarRelatorio (List listDados, String relatorio, ServletContext servletContext) throws Exception{
//cria a lista de dados para o relatorio com nossa lista de objetos para imprimir
JRBeanCollectionDataSource jrbcds = new JRBeanCollectionDataSource(listDados);
//carregar o caminho do arquivo jasper compilado
String caminhoJasper = servletContext.getRealPath("relatorios")
+ File.separator + relatorio + ".jasper";
//Carrega o arquivo Jasper passando os Dados
JasperPrint impressoraJasper = JasperFillManager.fillReport(caminhoJasper, new HashMap(), jrbcds);
//Exporta para byte[] para fazer o download do PDF
return JasperExportManager.exportReportToPdf(impressoraJasper);
}
}
| [
"guiromanno@gmail.com"
] | guiromanno@gmail.com |
90aa2939704ba93356450d6e7d9eb58717b23f16 | 52571771439ac9b6e8ecc16775fa52b63c1cac3d | /LanHouse/src/view/TelaValorHora.java | cd8a380dee6ab6d620d60dbb94426820151cd357 | [] | no_license | vhpavoni/ISS2016 | eb92ccffbc3aeddc2b0899605f2740483eb80c7b | 6bc92bd648b759554ff6083fe622b87b33d65034 | refs/heads/master | 2020-06-13T17:27:33.276508 | 2016-12-05T01:29:37 | 2016-12-05T01:29:37 | 75,574,991 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,598 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package view;
import BancoDeDados.Persistencia;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.List;
import javax.swing.text.MaskFormatter;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import modelo.Cliente;
import modelo.ValorHora;
import modeloDAO.ValorHoraDAO;
/**
*
* @author GCD
*/
public class TelaValorHora extends javax.swing.JFrame {
MaskFormatter mHora = new MaskFormatter();
private ValorHora horas2;
public TelaValorHora(ValorHora valorHora) {
horas2 = valorHora;
try {
mHora.setMask("##.##");
mHora.setPlaceholderCharacter('0');
} catch (ParseException ex) {
}
initComponents();
this.setLocationRelativeTo(null);
}
/**
* Creates new form ValorHora
*/
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jFormattedTextField1 = new javax.swing.JFormattedTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
hora = new JFormattedTextField(mHora);
salvar = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
jFormattedTextField1.setText("jFormattedTextField1");
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setText("Valor cobrado por hora");
jLabel2.setText("R$:");
hora.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
horaKeyPressed(evt);
}
});
salvar.setText("Salvar");
salvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
salvarActionPerformed(evt);
}
});
jButton1.setText("Cancelar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(hora, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(salvar)
.addGap(38, 38, 38)
.addComponent(jButton1)))
.addGap(38, 38, 38))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jLabel1)
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(hora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(salvar)
.addComponent(jButton1))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void horaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_horaKeyPressed
}//GEN-LAST:event_horaKeyPressed
private void salvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarActionPerformed
ValorHora v = new ValorHora(Float.parseFloat(hora.getText()));
ValorHoraDAO v1 = new ValorHoraDAO();
v1.atualizar(v);
this.dispose();
}//GEN-LAST:event_salvarActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(final ValorHora horas3) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(TelaValorHora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TelaValorHora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TelaValorHora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TelaValorHora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TelaValorHora(horas3).setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JFormattedTextField hora;
private javax.swing.JButton jButton1;
private javax.swing.JFormattedTextField jFormattedTextField1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JButton salvar;
// End of variables declaration//GEN-END:variables
}
| [
"vh_pavoni@hotmail.com"
] | vh_pavoni@hotmail.com |
324240b01cf63f9c53ef30c7fd510bebd704839d | 030836b453a46e7748eac89e3ea576d1e903ba25 | /src/main/java/creational/abstractfactory/VisaFactory.java | e6868d1a8dbc60a9fccb804f7954477fe289bdc5 | [] | no_license | Patrickk80/JavaDesignPatterns | ec8047e348cb66201488cb6cf1e516d843d954a8 | 8f71a331d7556d1641de98d118731668a6ec39bd | refs/heads/master | 2023-02-28T15:23:43.790844 | 2021-01-24T11:56:02 | 2021-02-07T19:09:55 | 336,873,446 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 454 | java | package creational.abstractfactory;
public class VisaFactory extends CreditCardFactory {
@Override
public CreditCard getCreditCard(CardType cardType) {
switch (cardType) {
case GOLD: {
return new VisaGoldCreditCard();
}
case PLATINUM: {
return new VisaBlackCreditCard();
}
}
return null;
}
@Override
public Validator getValidator(CardType cardType) {
return new VisaValidator();
}
}
| [
"pwakooijman@gmail.com"
] | pwakooijman@gmail.com |
b313e7a2251a00b53d67f25e00f77c5d6d75302e | 1f1bd1171d80b0dd399a1ce82189b33952160602 | /src/test/java/com/ibm/health/HealthEndpointTest.java | 5f4ecbba4c544a85fd0fee94acd06ff220a47431 | [] | no_license | michaelsteven/java-spring-example | bcfc1ce50822537ba130b018ececc771d601ed05 | f9d7d5661656335291686522ededfb19ea0a81f4 | refs/heads/master | 2022-12-20T22:02:14.824760 | 2019-08-08T19:00:20 | 2019-08-08T19:00:20 | 201,319,953 | 0 | 0 | null | 2022-12-09T21:50:18 | 2019-08-08T19:00:18 | Java | UTF-8 | Java | false | false | 1,756 | java | package com.ibm.health;
import static org.mockito.Mockito.spy;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HealthEndpointTest {
@Autowired
private TestRestTemplate server;
HealthEndpoint controller;
MockMvc mockMvc;
BeanFactory beanFactory;
@BeforeEach
public void setup() {
controller = spy(new HealthEndpoint());
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@org.junit.jupiter.api.Test
@DisplayName("When called with {name} then it should return a 200 status")
public void when_called_with_name_should_return_200_status() throws Exception {
mockMvc.perform(get("/health"))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString().startsWith("{\"status\":\"UP\"");
}
}
| [
"michaelsteven@hepfer.org"
] | michaelsteven@hepfer.org |
49d70fbdcccf63552a496983111ab0a63f0309d0 | 8dba0a2b37be0545149586516df1cffa85d9e383 | /app/src/main/java/com/example/mrlanguageturkish/c_serials_3_31.java | 0a5d7c706035b6fd15fb9b4cc77198697b16a588 | [] | no_license | ghomdoust/MrLanguageTurkish | 9e2ee449ba77d99057f9e3903696f791ef91ce13 | ae69f0922d06a9537ec7a5b4b5a05760637f6760 | refs/heads/master | 2023-03-30T20:38:01.303512 | 2021-04-06T23:16:20 | 2021-04-06T23:16:20 | 355,352,171 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,608 | java | package com.example.mrlanguageturkish;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import ir.aghayezaban.mrlanguageturkish.R;
public class c_serials_3_31 extends AppCompatActivity {
WebView mWebView;
ProgressBar progressBar;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.c_serials_3_31);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
mWebView = (WebView) findViewById(R.id.mWebView);
progressBar.setVisibility(View.VISIBLE);
mWebView.setWebViewClient(new c_serials_3_31.Browser_home());
mWebView.setWebChromeClient(new c_serials_3_31.MyChrome());
WebSettings webSettings = mWebView.getSettings();
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.setScrollbarFadingEnabled(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
loadWebsite();
}
private void loadWebsite() {
ConnectivityManager cm = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
mWebView.loadUrl("https://aspb17.cdn.asset.aparat.com/aparat-video/b3e9a9644621c65678c2ea5829b100e222516467-480p.mp4");
} else {
mWebView.setVisibility(View.GONE);
}
mWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
myRequest.allowScanningByMediaScanner();
myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager myManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
myManager.enqueue(myRequest);
Toast.makeText(c_serials_3_31.this,"ویدیوی شما در حال بارگزاریست", Toast.LENGTH_SHORT).show();
}
});
}
class Browser_home extends WebViewClient {
Browser_home() {
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
setTitle(view.getTitle());
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
private class MyChrome extends WebChromeClient {
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
protected FrameLayout mFullscreenContainer;
private int mOriginalOrientation;
private int mOriginalSystemUiVisibility;
MyChrome() {}
public Bitmap getDefaultVideoPoster()
{
if (mCustomView == null) {
return null;
}
return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
}
public void onHideCustomView()
{
((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
this.mCustomView = null;
getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
setRequestedOrientation(this.mOriginalOrientation);
this.mCustomViewCallback.onCustomViewHidden();
this.mCustomViewCallback = null;
}
public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
{
if (this.mCustomView != null)
{
onHideCustomView();
return;
}
this.mCustomView = paramView;
this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
this.mOriginalOrientation = getRequestedOrientation();
this.mCustomViewCallback = paramCustomViewCallback;
((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
getWindow().getDecorView().setSystemUiVisibility(3846);
}
}
} | [
"47427371+ghomdoust@users.noreply.github.com"
] | 47427371+ghomdoust@users.noreply.github.com |
c0fbb8318b399f8ed1b0929958ba3981a9c7117b | 94022084e8585b2f8f580ef00d67785ea1455c2e | /waveform/app/src/main/java/com/ylz/waveform/callback/httpcallback/RequestStreamCallback.java | 87292f100e0de95a9d52cf004263572d97fe59ef | [] | no_license | eulinze/wave | bc8650a8aecd94dfc44f530544745533c93ba62c | 885bafcc542b0e7f373c90ed55767bfae376754c | refs/heads/master | 2020-08-03T14:46:51.244636 | 2020-01-12T11:27:04 | 2020-01-12T11:27:04 | 211,789,019 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 416 | java | package com.ylz.waveform.callback.httpcallback;
/**
*
*/
public interface RequestStreamCallback {
/**
* 数据刷新失败
* @param errorMessage 刷新失败提示信息
*/
public void getDataFail(String errorMessage);
/**
* 数据刷新成功
*/
public void getDataSuccess(Object obj);
/**
* 数据请求超时
*/
public void getDataFailTimeOut();
}
| [
"187519720892163.com"
] | 187519720892163.com |
817a76ee7d7f20688417e9b43bbca331f5093ba3 | f0851d2e525ad32aa4300cee318e38e064d62bfa | /src/main/java/com/apptasticsoftware/mfsapdmr/PdmrRegistry.java | 8a596d75ccf8272315bfb5a4101d37e5677c121d | [
"MIT"
] | permissive | w3stling/mfsa-pdmr | ecd9cb7ac39774d94446a3bb1fd259e94c6b4f04 | f03474c44abdfe95214c80e37146bd20f5c38079 | refs/heads/master | 2023-08-30T21:42:09.696711 | 2023-08-29T05:26:46 | 2023-08-29T05:26:46 | 229,556,211 | 1 | 0 | MIT | 2023-09-05T02:36:36 | 2019-12-22T11:16:38 | Java | UTF-8 | Java | false | false | 10,420 | java | /*
* MIT License
*
* Copyright (c) 2022, Apptastic Software
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.apptasticsoftware.mfsapdmr;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.function.BiConsumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
/**
* PDMR transaction registry for Malta Financial Services Authority (MFSA)
*/
public class PdmrRegistry {
private static final String URL = "https://www.mfsa.mt/firms/capital-markets/prevention-financial-market-abuse/notices/";
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy");
/**
* Get stream of PDMR transactions
* @return transactions transactions
* @throws IOException io exception
*/
public Stream<Transaction> getTransactions() throws IOException {
return parse();
}
private Stream<Transaction> parse() throws IOException {
ArrayList<Transaction> transactions = new ArrayList<>();
Document doc = Jsoup.connect(URL).get();
Element tableElement = doc.select("table").first();
Elements tableHeaderElements = tableElement.select("thead tr th");
String[] headers = new String[16];
for (int i = 0; i < tableHeaderElements.size(); i++) {
headers[i] = tableHeaderElements.get(i).text();
}
TransactionMapper mapper = new TransactionMapper();
mapper.initialize(headers);
Elements tableRowElements = tableElement.select(":not(thead) tr");
for (int i = 0; i < tableRowElements.size(); i++) {
Element row = tableRowElements.get(i);
Elements rowItems = row.select("td");
Transaction transaction = new Transaction();
for (int j = 0; j < rowItems.size(); j++) {
try {
mapper.createTransaction(transaction, j, rowItems.get(j).text());
} catch (Exception e) {
var logger = Logger.getLogger("com.apptasticsoftware.mfsapdmr");
logger.log(Level.WARNING, "Failed to parse transaction. ", e);
}
}
if (isValid(transaction)) {
transactions.add(transaction);
}
}
return transactions.stream();
}
private boolean isValid(Transaction transaction) {
return transaction != null && transaction.getDate() != null &&
!Double.isNaN(transaction.getPrice()) && !Double.isNaN(transaction.getVolume()) &&
transaction.getIssuer() != null && !transaction.getIssuer().isBlank();
}
static class TransactionMapper {
private static final String COLUMN_ISSUER = "Name of Issuer";
private static final String COLUMN_PDMR = "Person Discharging Managerial Responsibility";
private static final String COLUMN_DATE = "Date";
private static final String COLUMN_INSTRUMENT_TYPE = "Instrument Type";
private static final String COLUMN_NATURE_OF_TRANSACTION = "Nature of Transaction";
private static final String COLUMN_PLACE_OF_TRANSACTION = "Place of Transaction";
private static final String COLUMN_CURRENCY = "Currency";
private static final String COLUMN_PRICE = "Price";
private static final String COLUMN_VOLUME = "Volume";
private static final String COLUMN_OTHER_INFORMATION = "Other Information";
private static final HashMap<String, BiConsumer<Transaction, String>> COLUMN_NAME_FIELD_MAPPING;
final ArrayList<BiConsumer<Transaction, String>> columnIndexFieldMapping;
TransactionMapper() {
columnIndexFieldMapping = new ArrayList<>();
}
int initialize(String[] header) {
int i;
for (i = 0; i < header.length; ++i) {
if (header[i] == null)
break;
var headerColumnText = header[i].trim();
columnIndexFieldMapping.add(i, COLUMN_NAME_FIELD_MAPPING.get(headerColumnText));
}
return i;
}
Transaction createTransaction(Transaction transaction, int index, String value) {
var fieldMapping = columnIndexFieldMapping.get(index);
if (fieldMapping != null)
fieldMapping.accept(transaction, value);
return transaction;
}
private static double parseDouble(String value) {
var floatNumber = 0.0;
try {
value = value.replace(",","").trim();
value = value.replace(" ", "");
floatNumber = Double.valueOf(value);
}
catch (Exception e) {
var logger = Logger.getLogger("com.apptasticsoftware.mfsapdmr");
if (logger.isLoggable(Level.WARNING))
logger.log(Level.WARNING, "Failed to parse double. ", e);
floatNumber = Double.NaN;
}
return floatNumber;
}
static {
COLUMN_NAME_FIELD_MAPPING = new HashMap<>(32);
// Name of Issuer
COLUMN_NAME_FIELD_MAPPING.put(COLUMN_ISSUER, Transaction::setIssuer);
// Person Discharging Managerial Responsibility
COLUMN_NAME_FIELD_MAPPING.put(COLUMN_PDMR, (t, v) -> {
String pdmr = v;
int endPos = pdmr.indexOf(',');
if (endPos != -1) {
pdmr = pdmr.substring(0, endPos).trim();
}
t.setPdmr(pdmr);
});
// Date
COLUMN_NAME_FIELD_MAPPING.put(COLUMN_DATE, (t, v) -> t.setDate(LocalDate.parse(v, DATE_FORMATTER)));
// Instrument Type
COLUMN_NAME_FIELD_MAPPING.put(COLUMN_INSTRUMENT_TYPE, Transaction::setInstrumentType);
// Nature of Transaction
COLUMN_NAME_FIELD_MAPPING.put(COLUMN_NATURE_OF_TRANSACTION, Transaction::setNatureOfTransaction);
// Place of Transaction
COLUMN_NAME_FIELD_MAPPING.put(COLUMN_PLACE_OF_TRANSACTION, Transaction::setPlaceOfTransaction);
// Currency
COLUMN_NAME_FIELD_MAPPING.put(COLUMN_CURRENCY, Transaction::setCurrency);
// Price
COLUMN_NAME_FIELD_MAPPING.put(COLUMN_PRICE, (t, v) -> t.setPrice(parseDouble(v)));
// Volume
COLUMN_NAME_FIELD_MAPPING.put(COLUMN_VOLUME, (t, v) -> t.setVolume(parseDouble(v)));
// Other Information
COLUMN_NAME_FIELD_MAPPING.put(COLUMN_OTHER_INFORMATION, (t, v) -> {
t.setOtherInformation(v);
if (v != null) {
String role = null;
t.setCloselyAssociated(v.toLowerCase().contains("closely associated"));
if (v.toLowerCase().startsWith("director and ceo")) {
role = "Director and CEO";
}
int start1 = v.indexOf("holds the position of");
int start2 = v.indexOf("holds the positions of");
int start3 = v.indexOf("is a member of");
int start4 = v.indexOf("is the");
int start5 = v.indexOf("holds a position of");
int start6 = v.indexOf(" is a ");
int start = Math.max(start1, start2);
int end1 = v.lastIndexOf("within");
int end2 = v.lastIndexOf("of");
int end3 = v.toLowerCase().indexOf("of the issuer");
if (start != -1 && end1 != -1 && start < end1) {
role = v.substring(start + 22, end1 - 1).trim();
} else if (start5 != -1 && end1 != -1 && start5 < end1) {
role = v.substring(start5 + 19, end1 - 1).trim();
} else if (start3 != -1 && end2 != -1 && start3 < end2) {
role = v.substring(start3 + 5, end2 - 1).trim();
} else if (start4 != -1 && end2 != -1 && start4 < end2) {
role = v.substring(start4 + 3, end2 - 1).trim();
} else if (start6 != -1 && end1 != -1 && start6 < end1) {
role = v.substring(start6 + 6, end1 - 1).trim();
} else if (end3 != -1) {
role = v.substring(0, end3).trim();
}
if (role != null) {
role = role.trim();
if (role.startsWith("a ")) {
role = role.substring(2).trim();
} else if (role.startsWith("an ")) {
role = role.substring(3).trim();
}
int endPos = role.indexOf(" - ");
if (endPos != -1) {
role = role.substring(0, endPos);
}
t.setRole(role);
}
}
});
}
}
}
| [
"peter.westling@gmail.com"
] | peter.westling@gmail.com |
4826ecd0634227a5de8e1b45eae0e01c47c19bcb | 841f4589acbf79df3cfc610cb3cca612cb65a8ca | /src/main/java/cn/soneer/assetdata/vo/AncientPoemsVo.java | 9c0677fccb634b374cecb408197feb8f51882bfe | [] | no_license | soneger/assetdata | 729fb2e584dbaea42706b2805be6bbdc5d6dac61 | 7b2a7db569438bfee4fef3804129f1327eaa0f85 | refs/heads/master | 2023-03-22T14:30:54.367848 | 2021-03-21T13:19:48 | 2021-03-21T13:19:48 | 343,676,874 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 306 | java | package cn.soneer.assetdata.vo;
import lombok.Data;
/**
* project:assetdata
* class:AncientPoemsVo
* describe:TODO
* time:2021/3/20 13:35
* author:soneer
* version:1.0
*/
@Data
public class AncientPoemsVo {
private Integer id;
private String title;
private String author;
}
| [
"344309663@qq.com"
] | 344309663@qq.com |
5900c34f247ac6196e606fcc6b69452dcef39092 | be73270af6be0a811bca4f1710dc6a038e4a8fd2 | /crash-reproduction-moho/results/XRENDERING-422-19-14-NSGA_II-LineCoverage:ExceptionType:StackTraceSimilarity/org/xwiki/rendering/wikimodel/xhtml/filter/XHTMLWhitespaceXMLFilter_ESTest_scaffolding.java | ff873ba06fa4cf18c49a27783d35fb03bc2271b5 | [] | no_license | STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application | cf118b23ecb87a8bf59643e42f7556b521d1f754 | 3bb39683f9c343b8ec94890a00b8f260d158dfe3 | refs/heads/master | 2022-07-29T14:44:00.774547 | 2020-08-10T15:14:49 | 2020-08-10T15:14:49 | 285,804,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 471 | java | /**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Mon Apr 06 16:07:14 UTC 2020
*/
package org.xwiki.rendering.wikimodel.xhtml.filter;
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
@EvoSuiteClassExclude
public class XHTMLWhitespaceXMLFilter_ESTest_scaffolding {
// Empty scaffolding for empty test suite
}
| [
"pouria.derakhshanfar@gmail.com"
] | pouria.derakhshanfar@gmail.com |
563a0a5fe971f10576515cea288810878d873d45 | 62e3f2e7c08c6e005c63f51bbfa61a637b45ac20 | /B-Genius_AdFree/app/src/main/java/com/google/android/gms/common/internal/t.java | c379b7403392c847eec299dac33d9085dc8e9fb0 | [] | no_license | prasad-ankit/B-Genius | 669df9d9f3746e34c3e12261e1a55cf5c59dd1c6 | 1139ec152b743e30ec0af54fe1f746b57b0152bf | refs/heads/master | 2021-01-22T21:00:04.735938 | 2016-05-20T19:03:46 | 2016-05-20T19:03:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 855 | java | package com.google.android.gms.common.internal;
import android.content.Context;
import android.content.ServiceConnection;
public abstract class t
{
private static final Object a = new Object();
private static t b;
public static t a(Context paramContext)
{
synchronized (a)
{
if (b == null)
b = new u(paramContext.getApplicationContext());
return b;
}
}
public abstract boolean a(String paramString1, ServiceConnection paramServiceConnection, String paramString2);
public abstract void b(String paramString1, ServiceConnection paramServiceConnection, String paramString2);
}
/* Location: C:\Users\KSHITIZ GUPTA\Downloads\apktool-install-windws\dex2jar-0.0.9.15\dex2jar-0.0.9.15\classes_dex2jar.jar
* Qualified Name: com.google.android.gms.common.internal.t
* JD-Core Version: 0.6.0
*/ | [
"kshitiz1208@gmail.com"
] | kshitiz1208@gmail.com |
49404bbcbdf978de0e82b73250b3471ea223e6f8 | e19a7ddf43e471f448bbd4aabfaaa241cb589d37 | /src/main/java/com/outsource/qa/pages/RailConfirmItineraryPage.java | 7f54fa08589d511861e4f5abba855ce616ec2224 | [] | no_license | shiwanthalakmal/outsource-ui-eurostar-pageobjects | 54358d09f3653152f2d1a99b2de04620e39fa572 | 7336d30671f867b7c5296aac64de67d109c7cee4 | refs/heads/master | 2016-09-13T21:43:02.335782 | 2016-05-22T10:32:40 | 2016-05-22T10:32:40 | 56,612,679 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,047 | java | package com.outsource.qa.pages;
import com.outsource.qa.panels.RailplusFooterPanel;
import com.outsource.qa.panels.RailplusHeaderPanel;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
/**
* Created by user on 5/15/2016.
*/
public class RailConfirmItineraryPage extends BasicPage {
RailplusHeaderPanel headerPanel;
RailplusFooterPanel footerPanel;
@FindBy(how= How.XPATH,using = "//*[@id='shop']/h1") private WebElement lblConfirmationTitle;
@FindBy(how= How.XPATH,using = "//*[@id='shop']/fieldset/table/tbody/tr[2]/td[1]/table/tbody/tr[1]/td[2]/strong") private WebElement lblVerifyDestinationPlace;
@FindBy(how= How.XPATH,using = "//*[@id='shop']/fieldset/table/tbody/tr[2]/td[1]/table/tbody/tr[1]/td[4]/strong") private WebElement lblVerifyArrivalPlace;
@FindBy(how= How.XPATH,using = "//*[@id='shop']/fieldset/table/tbody/tr[2]/td[2]/span") private WebElement lblVerifyTicketPrice;
@FindBy(how= How.XPATH,using = "//*[@id='shop']/fieldset/table/tbody/tr[2]/td[1]/span") private WebElement lblVerifyPassengerDetails;
@FindBy(how= How.XPATH,using = "//*[@id='shop']/fieldset/table/tbody/tr[3]/td[2]/span") private WebElement lblBookingFee;
@FindBy(how= How.XPATH,using = "//*[@id='shop']/fieldset/table/tbody/tr[4]/td[2]/strong") private WebElement lblTotalTravelFee;
@FindBy(how= How.XPATH,using = "//*[@id='btnCheckOut']") private WebElement btnCheckOutProceed;
@FindBy(how= How.XPATH,using = "//*[@id='btnContinue']") private WebElement btnContinueShopping;
@FindBy(how= How.XPATH,using = "//*[@id='button-cart']/div/a") private WebElement lnkShoppingBag;
@FindBy(how= How.XPATH,using = "//*[@id='shop']/fieldset/table/tbody/tr[2]/td[2]/input") private WebElement btnRemoveItem;
@FindBy(how= How.XPATH,using = "html/body/div[3]/div[1]/span") private WebElement lblAlertTitle;
@FindBy(how= How.XPATH,using = "html/body/div[3]/div[11]/div/button[1]") private WebElement btnAlertAccept;
public RailConfirmItineraryPage(RemoteWebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
headerPanel = new RailplusHeaderPanel(driver);
footerPanel = new RailplusFooterPanel(driver);
}
public RailConfirmItineraryPage check_And_Validate_Confirmation_Page(String title){
Assert.assertEquals(title,lblConfirmationTitle.getText());
return this;
}
public RailConfirmItineraryPage check_And_Validate_Shopping_bag(String items){
Assert.assertEquals(items,lnkShoppingBag.getText());
return this;
}
public RailConfirmItineraryPage check_And_Validate_Shopping_Bucket_Total(String total){
int netTotal = (Integer.parseInt(lblBookingFee.getText()) + Integer.parseInt(lblVerifyTicketPrice.getText()));
Assert.assertEquals(total,String.valueOf(netTotal));
return this;
}
public RailConfirmItineraryPage check_And_Validate_Passenger_Details(String details,String age){
Assert.assertEquals("Mrs Mala Kumari(25 - Australia)","Mrs "+details+"("+age+" - Australia)");
return this;
}
public RailConfirmItineraryPage check_And_Validate_Travel_Locations(String desti,String arrival){
Assert.assertTrue(lblVerifyArrivalPlace.getText().contains(arrival.toUpperCase()));
Assert.assertTrue(lblVerifyDestinationPlace.getText().contains(desti.toUpperCase()));
return this;
}
public RailConfirmItineraryPage check_And_Validate_Cart_Travel_Cost(String cost){
return this;
}
public RailPaymentPage step_Proceed_Checkout_Flow(){
btnCheckOutProceed.click();
return new RailPaymentPage(driver);
}
public RailplusHomePage step_Back_To_Continue_Shopping(){
btnContinueShopping.click();
return new RailplusHomePage(driver);
}
public RailConfirmItineraryPage step_Remove_ShoppingCart_Item(){
btnRemoveItem.click();
return this;
}
public RailplusHomePage step_Remove_CartItem_Acceptance_Overlay(){
btnAlertAccept.click();
return new RailplusHomePage(driver);
}
public RailConfirmItineraryPage step_Initial_Checkout(){
btnCheckOutProceed.click();
return this;
}
public RailDeliveryInfoPage step_Final_Checkout(){
btnCheckOutProceed.click();
return new RailDeliveryInfoPage(driver);
}
}
| [
"shiwanthak@zone24x7.com"
] | shiwanthak@zone24x7.com |
e627934d553b7a198b2ed6d25205887992a15fe9 | 93caab98ba5cb7208dbd8fb80081f927c84e68df | /Battleship/src/battleship/Board.java | 021f6de24aa834614f2425e2f7a55c6552f876cc | [] | no_license | prudvikomaram/Java-Projects | 7b63919f43ea080a5f45327597977fbfa69463f1 | 1e1091226bbd35aeda8a137e6996f5b66a9da43d | refs/heads/master | 2020-10-01T08:13:32.066099 | 2016-05-04T17:44:55 | 2016-05-04T17:44:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,822 | java | /*
* 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 battleship;
import java.util.Random;
/**
*
* @author leijurv
*/
public class Board {
int[][] board;
public Board(Board b){
board=new int[b.board.length][b.board[0].length];
for (int i=0; i<b.board.length; i++){
System.arraycopy(b.board[i],0,board[i],0,b.board[i].length);
}
}
public Board(int[][] bo){
Board b=new Board();
b.board=bo;
board=(new Board(b)).board;
}
public Board(){
board=new int[10][10];
}
public int[] place(int length,int[][] filt,boolean need){
Random r=new Random();
int[][] filter=new int[10][10];
for (int XX=0; XX<10; XX++){
System.arraycopy(filt[XX],0,filter[XX],0,10);
}
for (int ii=0; ii<200; ii++){
//System.out.println(new Board(filt));
//for (int xp=0; xp<2; xp++){
int xp=r.nextInt(2);
int yp=1-xp;
int x=r.nextInt(10-xp*(length-1));
int y=r.nextInt(10-yp*(length-1));
x-=xp;
y-=yp;
boolean w=true;
int k;
for (k=0; k<length; k++){
x+=xp;
y+=yp;
if (x>9){
w=false;
break;
}
if (y>9){
w=false;
break;
}
if (isShip(x,y)||isShip(x+1,y)||isShip(x,y+1)||isShip(x-1,y)||isShip(x,y-1)){
w=false;
break;
}
//System.out.println(x+","+y+","+filter[x][y]);
if (filter[x][y]==-1){
w=false;
break;
}
filter[x][y]+=2;
}
if (w){
if (need){
for (int i=0; i<board.length; i++){
for (int j=0; j<board[0].length; j++){
if (filter[i][j]==1&&board[i][j]!=1&&filter[i][j]<2){
w=false;
}
}
}
}
if (w){
for (int i=0; i<board.length; i++){
for (int j=0; j<board[0].length; j++){
if (filter[i][j]>1){
board[i][j]=1;
}
}
}
return new int[]{x,y};
}
}
/*
for (int i=k-1; i>0; i--){
x-=xp;
y-=yp;
if (filter[x][y]>1){
filter[x][y]-=2;
}else{
System.out.println(i+","+k);
}
}*/
for (int i=0; i<10; i++){
for (int j=0; j<10; j++){
if (filter[i][j]>1){
filter[i][j]-=2;
}
}
}
}
return null;
}
@Override
public String toString(){
String res="";
for (int y=0; y<board[0].length; y++){
for (int x=0; x<board.length; x++){
//res=res+(board[x][y]==-1?"M":(board[x][y]==1?"H":"O"));
res=res+board[x][y];
}
res=res+"\n";
}
return res;
}
public boolean isShip(int x,int y){
if (x<0||x>9){
return false;
}
if (y<0||y>9){
return false;
}
return board[x][y]==1;
}
}
| [
"leijurv@gmail.com"
] | leijurv@gmail.com |
2538cba480b402900822faf35858bf88d4b36569 | fb5a349c5452d9ccd2ce44d48aab5f8152a1f905 | /src/main/java/com/gsww/java/reflection/DumpMethods.java | 82d2700b62e03aa1d03dfc4080a504b095d468d3 | [] | no_license | shaolei583/JavaStudy | 4189315345de50bb633985f8e74bd8bebf53ec80 | 493a50a364f1ce0a6b4e6a9869bcd4ab32017542 | refs/heads/master | 2021-01-10T04:20:43.342130 | 2016-03-17T15:40:59 | 2016-03-17T15:40:59 | 54,121,579 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 375 | java | package com.gsww.java.reflection;
import java.lang.reflect.Method;
public class DumpMethods {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> classType = Class.forName("com.gsww.java.other.Common");
Method[] methods = classType.getDeclaredMethods();
for(Method method:methods){
System.out.println(method);
}
}
}
| [
"349277728@qq.com"
] | 349277728@qq.com |
d1447d7864238ff6d323e09135e25bd0db4c2033 | 839ab6eceaebaaa1df055fed981b6749707b3bae | /kt/InvoicingSystem/src/main/java/cn/kgc/dao/UsersMapper.java | 343e2682115842114ddd20ba85aad971836f9e16 | [] | no_license | lixijun-1116/tcbd1016 | 18a7f8612ee49f7e7af307f2554ae9edd81240a5 | 71efd6228622c30a413d61f79ecec9ce5e9ec1c4 | refs/heads/master | 2022-12-30T03:19:49.045939 | 2020-10-15T09:10:52 | 2020-10-15T09:10:52 | 231,722,209 | 1 | 0 | null | 2022-12-16T01:42:32 | 2020-01-04T06:52:40 | HTML | UTF-8 | Java | false | false | 298 | java | package cn.kgc.dao;
import cn.kgc.entity.Users;
import org.apache.ibatis.annotations.Param;
public interface UsersMapper {
//登录
Users selectUsersByUserNameAndPassword(@Param("userName") String userName,
@Param("password")String password);
}
| [
"57042902+1279810365@users.noreply.github.com"
] | 57042902+1279810365@users.noreply.github.com |
34a87bc00f286cce395f5bcd07e0bd495785ef86 | c87df64f1363d61c1a71a00143c465b05f66d1a1 | /src/java/Controller/HuySuaPhieuNhap.java | c5ed5b809e9b77f427ef2bc58df7b98cb9ddc8ba | [] | no_license | tlatforlz/KidPlaza-Web | 3c7ce7b4be31f855382128658af112e37be939c7 | 49abde4d051e7540c3f4437d93a35cd47a46c122 | refs/heads/master | 2021-07-03T23:02:39.564911 | 2017-09-26T03:09:18 | 2017-09-26T03:09:18 | 88,953,550 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,479 | java | /*
* 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 Controller;
import DAO.SANPHAM_DAO;
import DTO.SANPHAM;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author tranl
*/
public class HuySuaPhieuNhap extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
String MaPhieuNhap = request.getParameter("MaPhieuNhap");
SANPHAM_DAO sp_dp = new SANPHAM_DAO();
ArrayList<SANPHAM> list = sp_dp.getListSP_temp(MaPhieuNhap);
for(SANPHAM sp : list){
sp_dp.XoaSanPhamMau(sp.getMaSanPham(), MaPhieuNhap);
sp_dp.XoaKhoAnhMau(sp.getMaSanPham(), MaPhieuNhap);
sp_dp.XoaLoaiSanPhamMau(sp.getMaSanPham(), MaPhieuNhap);
}
RequestDispatcher rd = request.getRequestDispatcher("DanhSachPhieuNhap");
rd.forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(HuySuaPhieuNhap.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(HuySuaPhieuNhap.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| [
"tranleanhthe@gmail.com"
] | tranleanhthe@gmail.com |
6c88ea831df5e1d1cbebeb38d347d1606e8de85b | 5f3bca0c9cb7c9dc8463a6d2a4602e3802cc29a5 | /src/main/java/com/github/lan1tian/kafka/simple/consumer/KafkaSimpleConsumer.java | b398ed345bbf40383fd775ccca773da07f4d98f4 | [] | no_license | lan1tian/kafka-learn | 0be864c4760d550469d0ffc09a3ef27b4c31f62d | 82b9a9bf013cde8c1656c1d3b787df8a9d62bc5a | refs/heads/master | 2021-01-09T19:50:12.632094 | 2020-02-23T01:45:07 | 2020-02-23T01:45:07 | 242,433,541 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,578 | java | package com.github.lan1tian.kafka.simple.consumer;
//
//import com.github.lan1tian.kafka.simple.config.KafkaConfig;
//import kafka.consumer.ConsumerConfig;
//import kafka.consumer.ConsumerIterator;
//import kafka.consumer.KafkaStream;
//import kafka.javaapi.consumer.ConsumerConnector;
//import kafka.message.MessageAndMetadata;
//import kafka.serializer.StringDecoder;
//import kafka.utils.VerifiableProperties;
//
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.Properties;
//
//public class KafkaSimpleConsumer {
//
// private final ConsumerConnector consumer;
//
// private KafkaSimpleConsumer() {
// Properties props = new Properties();
// //zookeeper 配置
// props.put("zookeeper.connect", "127.0.0.1:2181");
//
// //group 代表一个消费组
// props.put("group.id", KafkaConfig.GROUP);
//
// //zk连接超时
// props.put("zookeeper.session.timeout.ms", "4000");
// props.put("zookeeper.sync.time.ms", "200");
//// props.put("auto.commit.interval.ms", "1000");
//// props.put("auto.offset.reset", "smallest");
// //序列化类
// props.put("serializer.class", "kafka.serializer.StringEncoder");
// //关闭自动提交
// props.put("enable.auto.commit", false);
//
//
// ConsumerConfig config = new ConsumerConfig(props);
//
// consumer = kafka.consumer.Consumer.createJavaConsumerConnector(config);
// }
//
// void consume() {
// Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
// topicCountMap.put(KafkaConfig.TOPIC, new Integer(1));
//
// StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());
// StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties());
//
// Map<String, List<KafkaStream<String, String>>> consumerMap =
// consumer.createMessageStreams(topicCountMap, keyDecoder, valueDecoder);
// KafkaStream<String, String> stream = consumerMap.get(KafkaConfig.TOPIC).get(0);
// ConsumerIterator<String, String> it = stream.iterator();
// while (it.hasNext()) {
// MessageAndMetadata<String, String> metadata = it.next();
// System.out.println("offset:" + metadata.offset() + ",message:" + metadata.message());
//// consumer.commitOffsets();
// }
// System.out.println("finish batch >>>");
// }
//
// public static void main(String[] args) {
// new KafkaSimpleConsumer().consume();
// }
//
//}
| [
"1361959119@qq.com"
] | 1361959119@qq.com |
8aa65f278f664af427e090d2f114839aa7a4cc48 | ba1d1da3d7e87467b5142dd5acfd50f9bffd81b7 | /Transport/Transport-ejb/src/main/java/pi/transport/services/CourseServiceRemote.java | ac3f993a270de0748f1b6ee7245bccba01053226 | [] | no_license | zodijacky/transportProject_jsf | 2e01f8d01867670956e7039932a55be39140d889 | 82d14cf51f0f03d99ae05f644a539bbe9769eab9 | refs/heads/master | 2021-01-12T06:12:52.630058 | 2016-12-25T13:20:50 | 2016-12-25T13:20:50 | 77,326,708 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 628 | java | package pi.transport.services;
import java.util.List;
import javax.ejb.Remote;
import pi.transport.persistance.Course;
import pi.transport.persistance.Driver;
import pi.transport.persistance.User;
@Remote
public interface CourseServiceRemote {
public void create(Course course);
public Course find(Integer id);
public void update(Course course);
public void delete(Course course);
public void delete(Integer id);
public List<Course> findAll();
public List<Course> findByDriver(Driver driver);
public List<Course> FindCourseByCost(Double cost);
// public Course FindCourseByNbPassangers(double cost);
}
| [
"omar.mansour@esprit.tn"
] | omar.mansour@esprit.tn |
0aa3f9a26514d296b20ec965195e8531a71d53e4 | 87c29953a8324ad994daf8c05ca944de4f001edc | /elo7/src/br/com/elo7/pattern/PagamentoViaMoip.java | bd07c4f08563d29b555ead102c549d5a692885a7 | [] | no_license | luiz158/tdc-sao-paulo-2014 | 3893224e87c105437a88a81fd3f82d25d6855a16 | 4ee64b7bfad4867afec54046d4a17e18fa938b72 | refs/heads/master | 2021-01-18T02:24:12.966817 | 2014-08-27T13:27:48 | 2014-08-27T13:27:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 366 | java | package br.com.elo7.pattern;
public class PagamentoViaMoip implements RegraDePagamento {
private Jaiminho jaiminho;
public PagamentoViaMoip(Jaiminho jaiminho) {
this.jaiminho = jaiminho;
}
public void paga() {
System.out.println("Conecta no Moip");
System.out.println("Dados do usuario no Moip");
System.out.println("Faz pagamento no Moip");
}
}
| [
"alexandre.gama.lima@gmail.com"
] | alexandre.gama.lima@gmail.com |
ac29ef402e3ebf889847b80e10c303b01035f232 | 54ed39d8ce339e8ee0efdc7e503f02c1ccd8d3f3 | /src/main/java/com/store/orders/OrderRepository.java | 5a91335e509abae27420b1bcf69806d9278f6abb | [] | no_license | mermanu/ctest | cc9425404772e1f691cd3b07ca59ae7cfa5e89e7 | d4b1692b96173266e971c9b8f67b5faee8889725 | refs/heads/master | 2023-01-10T16:09:18.006480 | 2020-11-18T14:52:49 | 2020-11-18T14:52:49 | 313,962,833 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 128 | java | package com.store.orders;
import com.store.system.Repository;
public final class OrderRepository extends Repository<Order> {}
| [
"mmerida.oliveros@gmail.com"
] | mmerida.oliveros@gmail.com |
07265e2cdd6d7ba6a00904a10c4d6f21c8b4709e | 30bd9a06cdae38055ca55150b00cc86c635c1fb9 | /Roster/src/com/codingdojo/web/models/Player.java | 42ff54761d9be50c9a6c96cfe017f4b5501bb8a7 | [] | no_license | Erictimami/MiniProjects_Servlets_Java | dd1e40044be63d14a3ce4426b743ec7bc2cb7b41 | 3471eb420e832748248af8c592e1d20794d99986 | refs/heads/master | 2020-04-26T06:53:55.623796 | 2019-03-01T23:26:40 | 2019-03-01T23:26:40 | 173,379,097 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 124 | java | package com.codingdojo.web.models;
public class Player {
public String firstName;
public String lastName;
public int
}
| [
"timameric@gmail.com"
] | timameric@gmail.com |
0fea56b6587ad567457ee737770f80322365aab6 | d66c312b87241a19715be9e3e3b04c945fc78be5 | /src/main/java/ar/edu/unju/fi/tp1pto1/controller/ProvinciaController.java | 37b9e0f886fcabaa8fb5cb1a95aab7d88e69fd06 | [] | no_license | anabella-mv/Valdez_Mailen_Anabella_EDM_TP1 | f5eeab1fd50888e13b1f79e47922e73401d399a0 | efc44fcc29aa6536152e3f45339061c4c463e457 | refs/heads/master | 2023-03-31T12:11:05.066516 | 2021-04-11T23:46:17 | 2021-04-11T23:46:17 | 356,999,146 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 804 | java | package ar.edu.unju.fi.tp1pto1.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import ar.edu.unju.fi.tp1pto1.model.Provincia;
@Controller
class ProvinciaController {
//Provincia unaProvincia = new Provincia(); //instanciando la clase provincia, estamos creando una variable una provincia que tiene un objeto asignando a un espacio de memoria
@Autowired
Provincia unaProvincia = new Provincia ();
@GetMapping({"/provincia"})
public String cargarProvincia(Model model) {
unaProvincia.setNombre("Jujuy Argentina");
model.addAttribute("anabella", unaProvincia);
return "provincia";
}
} | [
"Flia. Valdez-Vargas@DESKTOP-0BBIMTT"
] | Flia. Valdez-Vargas@DESKTOP-0BBIMTT |
3f83092f074511056801282c37df4979fc5ea2bb | 53452abebe9b928fd158865b8ace9345709abf04 | /src/main/java/emag/lapachet/route/SaleApiEndpoint.java | 8ffa4cc2ea687edb1ed1ff1b56ba74813637450f | [
"MIT"
] | permissive | viorelgheba/lapachet-app | b9c819fde320228dd2e6c021c4e6bfb2683a0c69 | 8b23d3bdaaec7deddbdb3d11e8c66b372f8d9c88 | refs/heads/master | 2020-07-07T23:43:36.338955 | 2016-09-04T07:19:43 | 2016-09-04T07:19:43 | 67,285,559 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 797 | java | package emag.lapachet.route;
import com.google.gson.Gson;
import emag.lapachet.entity.SaveSale;
import emag.lapachet.service.SqlSale;
import org.bson.Document;
import spark.Service;
import static emag.lapachet.util.JsonUtil.json;
public class SaleApiEndpoint implements EndpointInterface {
public static final Gson GSON;
static {
GSON = new Gson();
}
private SqlSale sqlSale;
public SaleApiEndpoint() {
sqlSale = new SqlSale();
}
@Override
public void configure(Service spark) {
spark.post("/api/sales", "application/json", (req, res) -> {
SaveSale saveSale = GSON.fromJson(req.body(), SaveSale.class);
return new Document().append("orderId", sqlSale.addSale(saveSale).toString());
}, json());
}
}
| [
"viorel.gheba@emag.ro"
] | viorel.gheba@emag.ro |
30598ee2aeac85659981bf42ce2aab244a267d4c | 622dd0028a4aeb8c1434cb2be463ec3435fb0ac7 | /Module-3/case_study/jsp_servlet/furama_resort/src/main/java/repository/DBConnection.java | 2370d5031727a499d4ab3334e19e23dcbecdb758 | [] | no_license | nttv/C1120G1-NguyenThiTuongVi | f779c401476704d7f97693225c4aa92ef9b6cafd | 17a6eadbba2ac3e5a6529209ddbd05bc721ff759 | refs/heads/main | 2023-04-29T05:56:24.008750 | 2021-05-18T15:44:34 | 2021-05-18T15:44:34 | 316,414,238 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,041 | java | package repository;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
private static final String HOST = "localhost";
private static final String PORT = "3306";
private static final String DATABASE = "cs_furama_db";
private static final String USERNAME = "root";
private static final String PASSWORD = "123qwe!@#";
private static Connection connection;
public static Connection open() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" + HOST + ":" + PORT + "/" + DATABASE, USERNAME, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close() {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| [
"nttuongvi.36@gmail.com"
] | nttuongvi.36@gmail.com |
0dd9ec8597880752c586f3301e07c1704235cfed | d516276cdfc222ec7bf38837e7bc12341993dd9c | /patterns-codebeispiele/de.bht.fpa.examples.adapter/src/common/professional/IOrder.java | 2d0ecb7530a08bcf312fac5e81ac07e7f76ed35b | [] | no_license | gnomcheck/BHT-FPA | ef2e3448c4832d26fb2f94447e524eb593a008bd | 37769199aab93a0aa09a9b2836674231ac54dafe | refs/heads/master | 2021-01-18T12:32:46.401696 | 2013-05-24T20:20:53 | 2013-05-24T20:20:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 81 | java | package common.professional;
public interface IOrder {
double getPrice();
}
| [
"siamak.h@gmx.de"
] | siamak.h@gmx.de |
aab34af81211f74a23253a4accc3b895e976b80b | 2e521fdee37bfada6b392119026a67e0498c539d | /build/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/android/support/constraint/R.java | 1ca82dbcf3c35798e4e7cd48c3527cd3048156cd | [] | no_license | vsiv16/SquadUp2.0 | 3bfebc0ab9abb3b7efe3691b2518152e2a99f99c | e8776af2e0d8966180722f24be2368b4d00582bb | refs/heads/master | 2020-12-20T01:36:31.192421 | 2020-01-24T01:48:13 | 2020-01-24T01:48:13 | 235,917,467 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,872 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.constraint;
public final class R {
private R() {}
public static final class attr {
private attr() {}
public static final int barrierAllowsGoneWidgets = 0x7f030038;
public static final int barrierDirection = 0x7f030039;
public static final int chainUseRtl = 0x7f03006a;
public static final int constraintSet = 0x7f03009e;
public static final int constraint_referenced_ids = 0x7f03009f;
public static final int content = 0x7f0300a0;
public static final int emptyVisibility = 0x7f0300cb;
public static final int layout_constrainedHeight = 0x7f03012c;
public static final int layout_constrainedWidth = 0x7f03012d;
public static final int layout_constraintBaseline_creator = 0x7f03012e;
public static final int layout_constraintBaseline_toBaselineOf = 0x7f03012f;
public static final int layout_constraintBottom_creator = 0x7f030130;
public static final int layout_constraintBottom_toBottomOf = 0x7f030131;
public static final int layout_constraintBottom_toTopOf = 0x7f030132;
public static final int layout_constraintCircle = 0x7f030133;
public static final int layout_constraintCircleAngle = 0x7f030134;
public static final int layout_constraintCircleRadius = 0x7f030135;
public static final int layout_constraintDimensionRatio = 0x7f030136;
public static final int layout_constraintEnd_toEndOf = 0x7f030137;
public static final int layout_constraintEnd_toStartOf = 0x7f030138;
public static final int layout_constraintGuide_begin = 0x7f030139;
public static final int layout_constraintGuide_end = 0x7f03013a;
public static final int layout_constraintGuide_percent = 0x7f03013b;
public static final int layout_constraintHeight_default = 0x7f03013c;
public static final int layout_constraintHeight_max = 0x7f03013d;
public static final int layout_constraintHeight_min = 0x7f03013e;
public static final int layout_constraintHeight_percent = 0x7f03013f;
public static final int layout_constraintHorizontal_bias = 0x7f030140;
public static final int layout_constraintHorizontal_chainStyle = 0x7f030141;
public static final int layout_constraintHorizontal_weight = 0x7f030142;
public static final int layout_constraintLeft_creator = 0x7f030143;
public static final int layout_constraintLeft_toLeftOf = 0x7f030144;
public static final int layout_constraintLeft_toRightOf = 0x7f030145;
public static final int layout_constraintRight_creator = 0x7f030146;
public static final int layout_constraintRight_toLeftOf = 0x7f030147;
public static final int layout_constraintRight_toRightOf = 0x7f030148;
public static final int layout_constraintStart_toEndOf = 0x7f030149;
public static final int layout_constraintStart_toStartOf = 0x7f03014a;
public static final int layout_constraintTop_creator = 0x7f03014b;
public static final int layout_constraintTop_toBottomOf = 0x7f03014c;
public static final int layout_constraintTop_toTopOf = 0x7f03014d;
public static final int layout_constraintVertical_bias = 0x7f03014e;
public static final int layout_constraintVertical_chainStyle = 0x7f03014f;
public static final int layout_constraintVertical_weight = 0x7f030150;
public static final int layout_constraintWidth_default = 0x7f030151;
public static final int layout_constraintWidth_max = 0x7f030152;
public static final int layout_constraintWidth_min = 0x7f030153;
public static final int layout_constraintWidth_percent = 0x7f030154;
public static final int layout_editor_absoluteX = 0x7f030156;
public static final int layout_editor_absoluteY = 0x7f030157;
public static final int layout_goneMarginBottom = 0x7f030158;
public static final int layout_goneMarginEnd = 0x7f030159;
public static final int layout_goneMarginLeft = 0x7f03015a;
public static final int layout_goneMarginRight = 0x7f03015b;
public static final int layout_goneMarginStart = 0x7f03015c;
public static final int layout_goneMarginTop = 0x7f03015d;
public static final int layout_optimizationLevel = 0x7f030160;
}
public static final class id {
private id() {}
public static final int barrier = 0x7f080023;
public static final int bottom = 0x7f080026;
public static final int chains = 0x7f080038;
public static final int dimensions = 0x7f080053;
public static final int direct = 0x7f080054;
public static final int end = 0x7f08005f;
public static final int gone = 0x7f08006f;
public static final int invisible = 0x7f08007e;
public static final int left = 0x7f080084;
public static final int none = 0x7f08009a;
public static final int packed = 0x7f0800a2;
public static final int parent = 0x7f0800a4;
public static final int percent = 0x7f0800a9;
public static final int right = 0x7f0800b4;
public static final int spread = 0x7f0800de;
public static final int spread_inside = 0x7f0800df;
public static final int standard = 0x7f0800e3;
public static final int start = 0x7f0800e4;
public static final int top = 0x7f0800fd;
public static final int wrap = 0x7f080118;
}
public static final class styleable {
private styleable() {}
public static final int[] ConstraintLayout_Layout = { 0x10100c4, 0x101011f, 0x1010120, 0x101013f, 0x1010140, 0x7f030038, 0x7f030039, 0x7f03006a, 0x7f03009e, 0x7f03009f, 0x7f03012c, 0x7f03012d, 0x7f03012e, 0x7f03012f, 0x7f030130, 0x7f030131, 0x7f030132, 0x7f030133, 0x7f030134, 0x7f030135, 0x7f030136, 0x7f030137, 0x7f030138, 0x7f030139, 0x7f03013a, 0x7f03013b, 0x7f03013c, 0x7f03013d, 0x7f03013e, 0x7f03013f, 0x7f030140, 0x7f030141, 0x7f030142, 0x7f030143, 0x7f030144, 0x7f030145, 0x7f030146, 0x7f030147, 0x7f030148, 0x7f030149, 0x7f03014a, 0x7f03014b, 0x7f03014c, 0x7f03014d, 0x7f03014e, 0x7f03014f, 0x7f030150, 0x7f030151, 0x7f030152, 0x7f030153, 0x7f030154, 0x7f030156, 0x7f030157, 0x7f030158, 0x7f030159, 0x7f03015a, 0x7f03015b, 0x7f03015c, 0x7f03015d, 0x7f030160 };
public static final int ConstraintLayout_Layout_android_orientation = 0;
public static final int ConstraintLayout_Layout_android_maxWidth = 1;
public static final int ConstraintLayout_Layout_android_maxHeight = 2;
public static final int ConstraintLayout_Layout_android_minWidth = 3;
public static final int ConstraintLayout_Layout_android_minHeight = 4;
public static final int ConstraintLayout_Layout_barrierAllowsGoneWidgets = 5;
public static final int ConstraintLayout_Layout_barrierDirection = 6;
public static final int ConstraintLayout_Layout_chainUseRtl = 7;
public static final int ConstraintLayout_Layout_constraintSet = 8;
public static final int ConstraintLayout_Layout_constraint_referenced_ids = 9;
public static final int ConstraintLayout_Layout_layout_constrainedHeight = 10;
public static final int ConstraintLayout_Layout_layout_constrainedWidth = 11;
public static final int ConstraintLayout_Layout_layout_constraintBaseline_creator = 12;
public static final int ConstraintLayout_Layout_layout_constraintBaseline_toBaselineOf = 13;
public static final int ConstraintLayout_Layout_layout_constraintBottom_creator = 14;
public static final int ConstraintLayout_Layout_layout_constraintBottom_toBottomOf = 15;
public static final int ConstraintLayout_Layout_layout_constraintBottom_toTopOf = 16;
public static final int ConstraintLayout_Layout_layout_constraintCircle = 17;
public static final int ConstraintLayout_Layout_layout_constraintCircleAngle = 18;
public static final int ConstraintLayout_Layout_layout_constraintCircleRadius = 19;
public static final int ConstraintLayout_Layout_layout_constraintDimensionRatio = 20;
public static final int ConstraintLayout_Layout_layout_constraintEnd_toEndOf = 21;
public static final int ConstraintLayout_Layout_layout_constraintEnd_toStartOf = 22;
public static final int ConstraintLayout_Layout_layout_constraintGuide_begin = 23;
public static final int ConstraintLayout_Layout_layout_constraintGuide_end = 24;
public static final int ConstraintLayout_Layout_layout_constraintGuide_percent = 25;
public static final int ConstraintLayout_Layout_layout_constraintHeight_default = 26;
public static final int ConstraintLayout_Layout_layout_constraintHeight_max = 27;
public static final int ConstraintLayout_Layout_layout_constraintHeight_min = 28;
public static final int ConstraintLayout_Layout_layout_constraintHeight_percent = 29;
public static final int ConstraintLayout_Layout_layout_constraintHorizontal_bias = 30;
public static final int ConstraintLayout_Layout_layout_constraintHorizontal_chainStyle = 31;
public static final int ConstraintLayout_Layout_layout_constraintHorizontal_weight = 32;
public static final int ConstraintLayout_Layout_layout_constraintLeft_creator = 33;
public static final int ConstraintLayout_Layout_layout_constraintLeft_toLeftOf = 34;
public static final int ConstraintLayout_Layout_layout_constraintLeft_toRightOf = 35;
public static final int ConstraintLayout_Layout_layout_constraintRight_creator = 36;
public static final int ConstraintLayout_Layout_layout_constraintRight_toLeftOf = 37;
public static final int ConstraintLayout_Layout_layout_constraintRight_toRightOf = 38;
public static final int ConstraintLayout_Layout_layout_constraintStart_toEndOf = 39;
public static final int ConstraintLayout_Layout_layout_constraintStart_toStartOf = 40;
public static final int ConstraintLayout_Layout_layout_constraintTop_creator = 41;
public static final int ConstraintLayout_Layout_layout_constraintTop_toBottomOf = 42;
public static final int ConstraintLayout_Layout_layout_constraintTop_toTopOf = 43;
public static final int ConstraintLayout_Layout_layout_constraintVertical_bias = 44;
public static final int ConstraintLayout_Layout_layout_constraintVertical_chainStyle = 45;
public static final int ConstraintLayout_Layout_layout_constraintVertical_weight = 46;
public static final int ConstraintLayout_Layout_layout_constraintWidth_default = 47;
public static final int ConstraintLayout_Layout_layout_constraintWidth_max = 48;
public static final int ConstraintLayout_Layout_layout_constraintWidth_min = 49;
public static final int ConstraintLayout_Layout_layout_constraintWidth_percent = 50;
public static final int ConstraintLayout_Layout_layout_editor_absoluteX = 51;
public static final int ConstraintLayout_Layout_layout_editor_absoluteY = 52;
public static final int ConstraintLayout_Layout_layout_goneMarginBottom = 53;
public static final int ConstraintLayout_Layout_layout_goneMarginEnd = 54;
public static final int ConstraintLayout_Layout_layout_goneMarginLeft = 55;
public static final int ConstraintLayout_Layout_layout_goneMarginRight = 56;
public static final int ConstraintLayout_Layout_layout_goneMarginStart = 57;
public static final int ConstraintLayout_Layout_layout_goneMarginTop = 58;
public static final int ConstraintLayout_Layout_layout_optimizationLevel = 59;
public static final int[] ConstraintLayout_placeholder = { 0x7f0300a0, 0x7f0300cb };
public static final int ConstraintLayout_placeholder_content = 0;
public static final int ConstraintLayout_placeholder_emptyVisibility = 1;
public static final int[] ConstraintSet = { 0x10100c4, 0x10100d0, 0x10100dc, 0x10100f4, 0x10100f5, 0x10100f7, 0x10100f8, 0x10100f9, 0x10100fa, 0x101031f, 0x1010320, 0x1010321, 0x1010322, 0x1010323, 0x1010324, 0x1010325, 0x1010326, 0x1010327, 0x1010328, 0x10103b5, 0x10103b6, 0x10103fa, 0x1010440, 0x7f03012c, 0x7f03012d, 0x7f03012e, 0x7f03012f, 0x7f030130, 0x7f030131, 0x7f030132, 0x7f030133, 0x7f030134, 0x7f030135, 0x7f030136, 0x7f030137, 0x7f030138, 0x7f030139, 0x7f03013a, 0x7f03013b, 0x7f03013c, 0x7f03013d, 0x7f03013e, 0x7f03013f, 0x7f030140, 0x7f030141, 0x7f030142, 0x7f030143, 0x7f030144, 0x7f030145, 0x7f030146, 0x7f030147, 0x7f030148, 0x7f030149, 0x7f03014a, 0x7f03014b, 0x7f03014c, 0x7f03014d, 0x7f03014e, 0x7f03014f, 0x7f030150, 0x7f030151, 0x7f030152, 0x7f030153, 0x7f030154, 0x7f030156, 0x7f030157, 0x7f030158, 0x7f030159, 0x7f03015a, 0x7f03015b, 0x7f03015c, 0x7f03015d };
public static final int ConstraintSet_android_orientation = 0;
public static final int ConstraintSet_android_id = 1;
public static final int ConstraintSet_android_visibility = 2;
public static final int ConstraintSet_android_layout_width = 3;
public static final int ConstraintSet_android_layout_height = 4;
public static final int ConstraintSet_android_layout_marginLeft = 5;
public static final int ConstraintSet_android_layout_marginTop = 6;
public static final int ConstraintSet_android_layout_marginRight = 7;
public static final int ConstraintSet_android_layout_marginBottom = 8;
public static final int ConstraintSet_android_alpha = 9;
public static final int ConstraintSet_android_transformPivotX = 10;
public static final int ConstraintSet_android_transformPivotY = 11;
public static final int ConstraintSet_android_translationX = 12;
public static final int ConstraintSet_android_translationY = 13;
public static final int ConstraintSet_android_scaleX = 14;
public static final int ConstraintSet_android_scaleY = 15;
public static final int ConstraintSet_android_rotation = 16;
public static final int ConstraintSet_android_rotationX = 17;
public static final int ConstraintSet_android_rotationY = 18;
public static final int ConstraintSet_android_layout_marginStart = 19;
public static final int ConstraintSet_android_layout_marginEnd = 20;
public static final int ConstraintSet_android_translationZ = 21;
public static final int ConstraintSet_android_elevation = 22;
public static final int ConstraintSet_layout_constrainedHeight = 23;
public static final int ConstraintSet_layout_constrainedWidth = 24;
public static final int ConstraintSet_layout_constraintBaseline_creator = 25;
public static final int ConstraintSet_layout_constraintBaseline_toBaselineOf = 26;
public static final int ConstraintSet_layout_constraintBottom_creator = 27;
public static final int ConstraintSet_layout_constraintBottom_toBottomOf = 28;
public static final int ConstraintSet_layout_constraintBottom_toTopOf = 29;
public static final int ConstraintSet_layout_constraintCircle = 30;
public static final int ConstraintSet_layout_constraintCircleAngle = 31;
public static final int ConstraintSet_layout_constraintCircleRadius = 32;
public static final int ConstraintSet_layout_constraintDimensionRatio = 33;
public static final int ConstraintSet_layout_constraintEnd_toEndOf = 34;
public static final int ConstraintSet_layout_constraintEnd_toStartOf = 35;
public static final int ConstraintSet_layout_constraintGuide_begin = 36;
public static final int ConstraintSet_layout_constraintGuide_end = 37;
public static final int ConstraintSet_layout_constraintGuide_percent = 38;
public static final int ConstraintSet_layout_constraintHeight_default = 39;
public static final int ConstraintSet_layout_constraintHeight_max = 40;
public static final int ConstraintSet_layout_constraintHeight_min = 41;
public static final int ConstraintSet_layout_constraintHeight_percent = 42;
public static final int ConstraintSet_layout_constraintHorizontal_bias = 43;
public static final int ConstraintSet_layout_constraintHorizontal_chainStyle = 44;
public static final int ConstraintSet_layout_constraintHorizontal_weight = 45;
public static final int ConstraintSet_layout_constraintLeft_creator = 46;
public static final int ConstraintSet_layout_constraintLeft_toLeftOf = 47;
public static final int ConstraintSet_layout_constraintLeft_toRightOf = 48;
public static final int ConstraintSet_layout_constraintRight_creator = 49;
public static final int ConstraintSet_layout_constraintRight_toLeftOf = 50;
public static final int ConstraintSet_layout_constraintRight_toRightOf = 51;
public static final int ConstraintSet_layout_constraintStart_toEndOf = 52;
public static final int ConstraintSet_layout_constraintStart_toStartOf = 53;
public static final int ConstraintSet_layout_constraintTop_creator = 54;
public static final int ConstraintSet_layout_constraintTop_toBottomOf = 55;
public static final int ConstraintSet_layout_constraintTop_toTopOf = 56;
public static final int ConstraintSet_layout_constraintVertical_bias = 57;
public static final int ConstraintSet_layout_constraintVertical_chainStyle = 58;
public static final int ConstraintSet_layout_constraintVertical_weight = 59;
public static final int ConstraintSet_layout_constraintWidth_default = 60;
public static final int ConstraintSet_layout_constraintWidth_max = 61;
public static final int ConstraintSet_layout_constraintWidth_min = 62;
public static final int ConstraintSet_layout_constraintWidth_percent = 63;
public static final int ConstraintSet_layout_editor_absoluteX = 64;
public static final int ConstraintSet_layout_editor_absoluteY = 65;
public static final int ConstraintSet_layout_goneMarginBottom = 66;
public static final int ConstraintSet_layout_goneMarginEnd = 67;
public static final int ConstraintSet_layout_goneMarginLeft = 68;
public static final int ConstraintSet_layout_goneMarginRight = 69;
public static final int ConstraintSet_layout_goneMarginStart = 70;
public static final int ConstraintSet_layout_goneMarginTop = 71;
public static final int[] LinearConstraintLayout = { 0x10100c4 };
public static final int LinearConstraintLayout_android_orientation = 0;
}
}
| [
"vsivani01@gmail.com"
] | vsivani01@gmail.com |
65f27db7c0e2ea7642b03f81c4a9e33f32c52785 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_e1c157f6b9ef2f2da94caaedbbc1b0367adaef01/PlugIn/2_e1c157f6b9ef2f2da94caaedbbc1b0367adaef01_PlugIn_s.java | 0892bfa2eabaa066b8688133ff5eb074153c4a75 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 4,515 | java | /**
* License: GPL
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License 2
* as published by the Free Software Foundation.
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package mpicbg.ij.clahe;
import java.util.ArrayList;
import ij.IJ;
import ij.ImagePlus;
import ij.Undo;
import ij.WindowManager;
import ij.gui.GenericDialog;
import ij.gui.Roi;
import ij.process.ByteProcessor;
/**
* &lsquot;Contrast Limited Adaptive Histogram Equalization&rsquot; as
* described in
*
* <br />BibTeX:
* <pre>
* @article{zuiderveld94,
* author = {Zuiderveld, Karel},
* title = {Contrast limited adaptive histogram equalization},
* book = {Graphics gems IV},
* year = {1994},
* isbn = {0-12-336155-9},
* pages = {474--485},
* publisher = {Academic Press Professional, Inc.},
* address = {San Diego, CA, USA},
* }
* </pre>
*
* @author Stephan Saalfeld <saalfeld@mpi-cbg.de>
* @version 0.3b
*/
public class PlugIn implements ij.plugin.PlugIn
{
static private int blockRadius = 63;
static private int bins = 255;
static private float slope = 3;
static private ByteProcessor mask = null;
static private boolean fast = true;
static private boolean composite = true;
/**
* Get setting through a dialog
*
* @param imp
* @return
*/
final static private boolean setup( final ImagePlus imp )
{
final ArrayList< Integer > ids = new ArrayList< Integer >();
final ArrayList< String > titles = new ArrayList< String >();
titles.add( "*None*" );
ids.add( -1 );
for ( final int id : WindowManager.getIDList() )
{
final ImagePlus impId = WindowManager.getImage( id );
if ( impId.getWidth() == imp.getWidth() && impId.getHeight() == imp.getHeight() )
{
titles.add( impId.getTitle() );
ids.add( id );
}
}
final GenericDialog gd = new GenericDialog( "CLAHE" );
gd.addNumericField( "blocksize : ", blockRadius * 2 + 1, 0 );
gd.addNumericField( "histogram bins : ", bins + 1, 0 );
gd.addNumericField( "maximum slope : ", slope, 2 );
gd.addChoice( "mask : ", titles.toArray( new String[ 0 ] ), titles.get( 0 ) );
gd.addCheckbox( "fast_(less_accurate)", fast );
if ( imp.getNChannels() > 1 )
gd.addCheckbox( "process_as_composite", composite );
gd.addHelp( "http://pacific.mpi-cbg.de/wiki/index.php/Enhance_Local_Contrast_(CLAHE)" );
gd.showDialog();
if ( gd.wasCanceled() ) return false;
blockRadius = ( ( int )gd.getNextNumber() - 1 ) / 2;
bins = ( int )gd.getNextNumber() - 1;
slope = ( float )gd.getNextNumber();
final int maskId = ids.get( gd.getNextChoiceIndex() );
if ( maskId != -1 ) mask = ( ByteProcessor )WindowManager.getImage( maskId ).getProcessor().convertToByte( true );
else mask = null;
fast = gd.getNextBoolean();
if ( imp.isComposite() )
composite = gd.getNextBoolean();
return true;
}
/**
* {@link PlugIn} access
*
* @param arg not yet used
*/
@Override
final public void run( final String arg )
{
final ImagePlus imp = IJ.getImage();
synchronized ( imp )
{
if ( !imp.isLocked() )
imp.lock();
else
{
IJ.error( "The image '" + imp.getTitle() + "' is in use currently.\nPlease wait until the process is done and try again." );
return;
}
}
if ( !setup( imp ) )
{
imp.unlock();
return;
}
Undo.setup( Undo.TRANSFORM, imp );
run( imp );
imp.unlock();
}
/**
* Process an {@link ImagePlus} with the static parameters. Create mask
* and bounding box from the {@link Roi} of that {@link ImagePlus} and
* the selected {@link #mask} if any.
*
* @param imp
*/
final static public void run( final ImagePlus imp )
{
if ( fast )
FastFlat.getInstance().run( imp, blockRadius, bins, slope, mask, composite );
else
Flat.getInstance().run( imp, blockRadius, bins, slope, mask, composite );
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
3f4c3ab17fdabb0711fa0bb64d38605c696b094c | f2bca2892cb309c3d4457f7457ec2c244095ada9 | /src/main/java/User.java | d4e2aa8b0abd734654f362edc5b392f92028e8e2 | [] | no_license | Yury6720/Stone-Scissors-Paper-Lizard-Spock | 375f76d2335bbbedbcdba3dbbdca81e1439c33e2 | d721141336e3a0049b18ce351442500116778a84 | refs/heads/master | 2023-06-01T11:07:05.739022 | 2021-06-13T22:08:18 | 2021-06-13T22:08:18 | 373,975,642 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,506 | java | import java.util.Scanner;
public class User implements Movable {
private final Scanner inputScanner;
public User() {
inputScanner = new Scanner(System.in);
}
@Override
public Move getMove() {
System.out.print("Камень - 'К',\nНожницы - 'Н', \nБумага - 'Б' \nЯщерица - 'Я' \nСпок - 'С' \nКаков будет Ваш ход?\n");
String userInput = inputScanner.nextLine();
userInput = userInput.toUpperCase();
char firstLetter = userInput.charAt(0);
if (firstLetter == 'К' || firstLetter == 'Н' || firstLetter == 'Б'|| firstLetter == 'Я' || firstLetter == 'С') {
// Ввод корректный
switch (firstLetter) {
case 'К':
return Move.ROCK;
case 'Б':
return Move.PAPER;
case 'Н':
return Move.SCISSORS;
case 'Я':
return Move.LIZARD;
case 'С':
return Move.SPOCK;
}
}
System.out.println("Упс! Ход неверный \nПопробуйте ещё\n");
return getMove();
}
public boolean playAgain() {
System.out.print("Хотите сыграть еще раз? \n Д/Н\n");
String userInput = inputScanner.nextLine();
userInput = userInput.toUpperCase();
return userInput.charAt(0) == 'Д';
}
}
| [
"kuzminskij5683415@gmail.com"
] | kuzminskij5683415@gmail.com |
e53297993d814f63d596fc99c511c945e0d63813 | a214f4030b13e37fca6096c82e827f616961b117 | /example/libs/library/build/generated/source/buildConfig/debug/net/jful/dynamiclistview/BuildConfig.java | 47a44f262da3e2053ccc023d1e1aa6b8c5c8d384 | [] | no_license | githubzoujiayun/dynamiclistview | da54831d3002c1cf4c327fe3643f019641c8961e | 256c705ba6e92f8ebb38aac56a3daef54a73f4ba | refs/heads/master | 2021-01-15T18:59:25.913035 | 2015-03-09T09:00:02 | 2015-03-09T09:00:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 455 | java | /**
* Automatically generated file. DO NOT MODIFY
*/
package net.jful.dynamiclistview;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "net.jful.dynamiclistview";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
}
| [
"jaehochoe@ncsoft.co.kr"
] | jaehochoe@ncsoft.co.kr |
ad3ec46122ec07febcff7495e4e5fd54b8951ab5 | c070e1a63401fa6d194b182e1fc9f2b80c4bb330 | /mockig good/JMockItDemo/src/test/java/com/dxc/mock/AppTest.java | 48e1b3b034d9df9d5527044e53a986d5edfc3fdf | [] | no_license | rwagon13/dxc | 666351f265021d11b6e9e71acacbee65c2c2ab7f | 8efa3062a4665531eef11a05d47aef35b0c1ffe5 | refs/heads/master | 2022-12-14T05:27:25.918575 | 2020-08-28T07:01:44 | 2020-08-28T07:01:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 640 | java | package com.dxc.mock;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| [
"prasanna@hexaware.com"
] | prasanna@hexaware.com |
eacca511c9358842b7763808635302cb53fec3e5 | b030aa6629be2a81a6d357fea04c869f07b0f223 | /src/com/learntoday/customtag/package-info.java | f10d08fcb34853c731d1b73af8a2c002fd92226b | [] | no_license | danillovinicius/java-ee-java-server-pages | f7b8ff08852cf54d0554350db7e52fe75f7914db | 9630213fabc3fc561962eb1ebadfe51a36e3dd07 | refs/heads/master | 2021-01-20T13:43:30.668614 | 2017-05-07T17:05:30 | 2017-05-07T17:05:30 | 90,521,148 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 78 | java | /**
*
*/
/**
* @author danilolima
*
*/
package com.learntoday.customtag; | [
"danillovinicius@gmail.com"
] | danillovinicius@gmail.com |
88b35e38874003f697b03c540397bb629ea13cdc | d04001e2937238053b44c6128a51a4bcf6d0b8a2 | /src/main/java/seedu/address/commons/exceptions/WrongPasswordException.java | 88a0df2d13aec75b65f819c41b664a9bb1fbf99e | [
"MIT"
] | permissive | CS2103AUG2017-F11-B1/main | d9578a41a087808dbe44e2d6afed0d60ae8a6555 | 6510d20790c58bc1ca09bc787a2ceb4a76c19b28 | refs/heads/master | 2021-08-16T07:01:50.087278 | 2017-11-19T07:05:02 | 2017-11-19T07:05:02 | 105,418,088 | 0 | 4 | null | 2017-11-19T07:05:02 | 2017-10-01T03:58:17 | Java | UTF-8 | Java | false | false | 501 | java | package seedu.address.commons.exceptions;
/**
* Signals that the given Password do not match the existing one.
*/
public class WrongPasswordException extends Exception {
private static final String MESSAGE_WRONG_PASSWORD = "Wrong Password";
public WrongPasswordException() {
super(MESSAGE_WRONG_PASSWORD);
}
/**
* @param cause of the main exception
*/
public WrongPasswordException(Throwable cause) {
super(MESSAGE_WRONG_PASSWORD, cause);
}
}
| [
"syy.mns@gmail.com"
] | syy.mns@gmail.com |
9af2c4ac838d7fe4e880dc7658da52994ee2d38e | 853b0bec5bc9b5499925336c1f6959ae9ea4dccc | /wxzj2/src/com/yaltec/wxzj2/biz/draw/dao/BatchRefundDao.java | 6991e184eefe29ffb08d91a667ea98660d6110a7 | [] | no_license | QuietClickCode/wxzj2 | 598e69af218da5218e2befcc948f353027b34447 | c08061f7bbfaf616b32846e7ac1a171efcd0b33b | refs/heads/master | 2020-06-28T20:59:48.715250 | 2019-08-03T06:11:38 | 2019-08-03T06:11:38 | 200,339,358 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,049 | java | package com.yaltec.wxzj2.biz.draw.dao;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.yaltec.wxzj2.biz.draw.entity.CodeName;
import com.yaltec.wxzj2.biz.draw.entity.ShareAD;
import com.yaltec.wxzj2.biz.property.entity.Developer;
/**
*
* @ClassName: BatchRefundDao
* @Description: 批量退款Dao接口
*
* @author yangshanping
* @date 2016-8-23 下午02:46:48
*/
@Repository
public interface BatchRefundDao {
public List<CodeName> queryShareAD_LY2(Map<String, String> parasMap);
public List<CodeName> queryShareAD_LY(Map<String, String> parasMap);
public List<CodeName> queryShareAD_DY(String lybh);
public List<CodeName> queryShareAD_LC(Map<String, String> parasMap);
public List<CodeName> queryShareAD_FW(Map<String, String> parasMap);
public void saveRefund_PL(Map<String, String> parasMap);
public Developer getDeveloperBylybh(String lybh);
public List<ShareAD> QryExportShareAD(Map<String, String> parasMap);
}
| [
"2572417548@qq.com"
] | 2572417548@qq.com |
c146dbf28680138f3298bb752418c395090068f5 | 857f16e92c7ba04ce5b000f48c0f528f20f57704 | /Theatre/src/test/java/com/cap/TheatreApplicationTests.java | 523f69fa9dee4a124324bbc4f50df6274a923a03 | [] | no_license | pradeep-kumar-maurya/capgemini-sprint-2-microservices-with-angular | 7e018448e50b5732ac1a70b580e1c83fed9f0975 | 328126c288f0efb2ac89b0fd52f5be8bdcd4714b | refs/heads/master | 2022-07-13T23:25:59.653838 | 2020-05-10T09:54:37 | 2020-05-10T09:54:37 | 262,756,203 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 546 | java | package com.cap;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.cap.bean.Theatre;
import com.cap.service.TheatreServiceI;
@SpringBootTest
class TheatreApplicationTests {
@Autowired
private TheatreServiceI service;
@Test
void checkTheatres() {
List<Theatre> list = service.theatreNames("HYDERABAD");
Assertions.assertEquals(2, list.size());
}
} | [
"pk454649@gmail.com"
] | pk454649@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.